How to handle unknown child routes with wildcard in Angular

Question: I need help with routing today. I've a set of components each with a different route. I want to add 'PageNotFoundComponent' for wildcard route in parent as well as child. What I mean is, this is my URL:
http://localhost:8888/programs/cohorts
cohorts is a child of programs. I want to redirect to PageNotFoundComponent when either programs or cohorts is wrong. Here is my code:
app-routing.module.ts
...
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';

const routes: Routes = [
    { path: 'login', component: LoginComponent },
    {
        path: '',
        component: ProgramsComponent,
        canActivate: [AuthGuard]
        children: [
            {
                path: 'programs/:dashboardId',
                component: DashboardComponent
            },
            {
                path: 'programs/:dashboardId/:subPageId',
                component: DashboardComponent
            },
            {
                path: 'programs/**',
                component: PageNotFoundComponent
            }
        ]
    },
    { path: '**', component: PageNotFoundComponent }
];

@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule],
    providers: [DashboardModelResolver, DashboardListResolver]
})
export class AppRoutingModule {}

I'm making mistake somewhere. Please point out and help me.
This is working perfectly fine: http://localhost:8888/prrrooogrm/cohorts
But this is giving blank screen: http://localhost:8888/programs/cooohrt
I tried this also:
imports: [
    RouterModule.forRoot(routes),
    RouterModule.forChild([
        {
            path: '**',
            component: PageNotFoundComponent
        }
    ])
],

Answer: Url http://localhost:8888/programs/cooohrt is matched by programs/:dashboardId
So blank screen is probaly result of DashboardComponent
If you want to match id to valid object you can use RouteGuard
or simply redirect from your component when you realize that object doesn't exist
this.router.navigate(['404-not-found'], { skipLocationChange });

skipLocationChange is there to keep original (wrong) url to be visible for user. '404-not-found' is simply anything which is not matched by any url (to be correct matched by your wildcard url)
Comment: How to do that. Please elaborate your answer
Comment: the easiest way is to use navigate on Router without location change, see extended answer
Comment: That is fine but where do i put that line. in which file or module
Comment: put it to DashboardComponent where you are using :dashboardId. when dashboardId is unexpected then route to not found
Answer: const routes: Routes = [
  {
    path: '',
    component: HomeComponent,
    pathMatch: 'full'
  },
  {
    path: 'not-found',
    component: NotFoundComponent,
    pathMatch: 'full'
  },
  {
    path: '**',
    redirectTo: 'not-found',
    pathMatch: 'full'
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Comment: There's no path like `not-found` in my case.
Comment: post details of PageNotFoundComponent


Limit of multivariable functions

Question: limit of $\sqrt{x^2 + y^2} \sin(1/y)$ as $(x,y) \rightarrow (0,0)$
limit of $2xy/(x^2 - y + 5xy)$ as $(x,y) \rightarrow(0,0)$
Having trouble finding the answers for the questions above. According to book in one of them limit shouldn't exist and in the another one limit should exist but i don't have the answer unfortunately. Appreciate any help.
Comment: For the first it might be easier to consider $x\sin(1/x)$ and then try to use the same logic.
Answer: (1) $|\sin(1/y)|\le 1$
(2) Let $d$ the denominator when you divide top and bottom by $xy.$
If $x=y,$ $|d|$ goes to infinity.
If $x^2=y,$ $d$ goes to $5.$

Limit of multivariable functions


Oscillatory integral and Van der Corput

Question: I have questions about an oscillatory integral.  Physics papers say the oscillations should "cancel each other out".  By this logic, does this integral converge?
$$ \int_0^{\infty} e^{-i x^3} \, dx < \infty$$
Can we even replace it with a monic polynomial $p(x) = x^n + o(x^n)$ and still get convergence?
$$ \int_0^{\infty} e^{-i p(x)} \, dx < \infty$$
What is an upper bound for the constant this converges?
According to this thesis one can use Van der Corput trick to establish convergence, but I have only seen it to prove that $\{ p(n)\}_{n \in \mathbb{N}}$ is equidistributed $(\mod 1)$  is there a relation?
Answer: The integral $\int_1^\infty e^{-ix^r}\,dx$ is convergent if $r>1$. It is enough to study the integral between $1$ and $\infty$. The change of variables $x^r=t$  gives
$$
\int_1^\infty e^{-ix^r}\,dx=\frac1r\int_1^\infty e^{-it}\,t^{1/r-1}\,dt,\quad 1/r-1<0.
$$
Now  $e^{-it}$ has a bounded primitive and $t^{1/r-1}$ is decreasing and converges to $0$. By Dirichlet's criterion (which amounts to integration by parts) the integral converges.
The argument generalizes to the case in which $x^r$ is replaced by a monic polynomial of degree $n\ge2$: $p(x)=x^n+\dots$. Let $z$ be such that $p$ is increasing and convex on $[z,\infty)$. The change of variables $t=p(z)$ gives
$$
\int_z^\infty e^{-ip(x)}\,dx=\int_{p(z)}^\infty e^{-it}\,t^{1/r-1}\,\frac{dt}{p'(p^{-1}(t))},\quad 1/r-1<0.
$$
It is easy to check that $1/p'(p^{-1}(t))$ is decreasing and converges to $0$, so that the integral is convergent.

Oscillatory integral and Van der Corput


Why are the algebras of the associative operad unital?

Question: According to the n-lab page:

The associative operad Assoc is an operad which is generated by a
  binary operation $\Theta$ satisfying
$$\Theta\circ(\Theta,1)=\Theta\circ(1,\Theta)$$

It then goes on to say that:

Assoc is hence the operad whose algebras are monoids; i.e. objects equipped with an associative and unital binary operation.

Huh? Where did unitality come from? Sure there's this $1$ floating about, but I thought that just got interpreted as the identity function, as opposed to a distinguished element.
Comment: I think the nLab is not a good reference for mathematical structures, unless you are interested in their specific point of view. For many mathematicians, it gives more confusion than it solves.
Answer: I think something is a bit awry. If you "go back in time" (see previous revisions of the page), you see that first the operad was defined as one whose algebras were associative unital algebras (aka monoids), then someone added that it was generated by a single operation $\Theta$ with the associativity relation.
But if you take the construction of an operad defined by generators and relations (like here), you'll see that if there are no generators of arity $0$, then the resulting operad won't have any operations of arity $0$ (because if $k_i \geq 1$ for all $i$, then $k_1 + \dots + k_r \geq 1$...). So there are two things here:

The operad $\mathrm{Assoc}$ (or $\mathrm{Assoc}_+$) of unitary associative algebras, generated by $\Theta$ in arity $2$ and $*$ in arity $0$ subject to $\Theta \circ (1, \Theta) = \Theta \circ (\Theta, 1)$ and $\Theta (*, 1) = 1 = \Theta (1, *)$. This is the one that Ittay Weiss describes.
The operad $\mathrm{Assoc}_0$ of merely associative algebras generated by just $\Theta$ in degree $2$, subject to the previous relation.

These two are not equal, of course -- the only difference is in arity $0$.
You are indeed right to say that $1$ is taken to be an identity operation: it's an operation with arity $1$, and in the endomorphism operad it's the identity.
Comment: Thanks for catching that. Indeed, somebody edited carelessly. I have briefly fixed it now. But of course the entry is still stubby and looking for somebody to expand it further. If you have time and energy, feel invited.
Answer: The associative operad as a non-symmetric operad has precisely one $n$-ary operation for each $n\ge 0$. In particular, it has a $0$-ary operation which gives you the unit in the monoid. The symmetric version of the associative operation (the symmetrization of the non-planar version) has $\Sigma_n$ (the set of permutations on $n$ letters) as the set of $n$-ary operations. In particular, the $0$-ary operations is a singleton set, giving rise to the unit of the monoid.


IE9 does not accept unicode string in Javascript

Question: I tried to run my webapp with IE 9 (it already runs well in Firefox and Chrome) and  I continuously get The error

Script1014: Invalid Character

The debugger yields one line of code that contains the string "\ufdd0'keywordize-keys". I realize that this is an artifact of ClojureScript which I use to compile down to Javascript. I.e. Clojurscript symbol :keywordize-keys.
Now I was looking for a solution and I tried adding the encoding to the import HTML tag

this, however, does not make the error go away. Any Ideas?
Answer: Make sure the webserver serves the js/advanced.js resource with the correct charset.
See http://www.w3.org/International/O-HTTP-charset.en.php


How to implement a scroll page arrow button with variable thickness?

Question: I was wondering how I could change the thickness of the arrow on my website which is used as a scroll button. I would like something similar to this websites arrow in terms of thickness. example of arrow

Here is my codepen
.next {
  position:absolute;
  bottom:0;
  left:50%;
  margin-left:-40px;
  transform:rotate(-90deg);
  cursor:pointer;
}

Kind Regards,
Liam.
Comment: Use a different font? It's a "<" character using the "Roboto" font.
Answer: In the example you linked to an arrow is implemented differently than in your pen. Here's how it's done:

#arrow {
  border: 3px solid black;
  height: 50px;
  width: 50px;
  transform: rotate(45deg) translateY(-15px) translateX(5px);
  border-top: none;
  border-left: none;
}

Basically, you create a square, turn it 45 degrees and add a border on right and bottom sides. Now you can just change border thickness in the border property to change the arrow width.
P.S. you can use Chrome Developer Tools to inspect elements on websites. I.e. if you like how something looks on some website, you can just see how they implemented it.
Comment: @LiamDocherty the arrow is there, it is just black on a dark background and you can't see it :-)
Comment: Hi, thanks for the amazing answer! What am I doing wrong? I have copied and pasted your code and nothing happens. [my site](http://codepen.io/ldocherty1/pen/EZLOdP) Could it be something to do with the JS?
Comment: @LiamDocherty change the border color to white and you'll see ;-)
Answer: You just need to set the font-size and perhaps font-weight properties since the arrow you are showing is a character
Answer: Those next elements on your codepen are text so the property you would have to use would be font-size: 10px;
I would also recommend using the html down triangle character: ▼
Answer: Test this:

>


OpenCV in python complains when i try to use 64F in Sobel blur

Question: I am trying to make an object detection tool (given a sample) using Contours.
I have had some progress however when the object is in front of another object with a complicated structure (a hand or a face for example), or the object and its background merge in colors, it stops detecting the edges and thus doesnt give a good contour.
After reading through the algorithms documentation, I discovered that it works on the basis that the edges are detected by difference in color intensity - for example if the object is black and the background is black it will not detect it.
So now i am trying to apply some effects and blurs to try and make it work.
I am currently trying to get a combined Sobel blur (in both axis) with hopes that given enough light it will define the edges - since the product will be used by phones who have flash.
So when i tried to do it:
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
frame = cv2.GaussianBlur(frame, (5, 5), 10)
frameX = cv2.Sobel(frame, cv2.CV_64F, 1, 0)
frameY = cv2.Sobel(frame, cv2.CV_64F, 0, 1)
frame = cv2.bitwise_or(frameX, frameY)

I get an error saying the cv2.findContours supports only CV_8UC1 images when the mode is not CV_RETR_FLOODFILL.
Here is the line that triggers the error:
counturs, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)

I started messing around with this thing only 1 week ago and im surprised how easy it is to get results but some of the error messages are ridiculous.
Edit: I did try to swap the mode to be CV_RETR_FLOODFILL but that did not fix the problem, then it didnt work at all.
Answer: The reason is that findContours function expects a binary image (an image consists of 0's and 1's) whose type is 8 bit integer (uint8). The developers might have done this to reduce the memory usage since there is no point in storing binary values with 64 bits instead of 8 bits. Convert frame into uint8 type by just using
frame = np.uint8(frame)


Spotify API Authorization Code Flow Returning 'unsupported_grant_type' Error

Question: I am trying to access the Spotify Web API using a Node.js app. I have specified the grant_type as authorization_code yet receive an unsupported_grant_type error with description grant_type must be client_credentials, authorization_code or refresh_token.
As far as I can tell my post request is properly formatted and values are all correct. Not sure what else to check.
app.post('/auth', (req, res)=>{
  const auth = Buffer
                .from(`${process.env.CLIENT_ID}:${process.env.CLIENT_SECRET}`)
                .toString('base64');
  axios.post(token_uri, {}, {
      params: {
      'grant_type': 'authorization_code',
      'code': req.body.code,
      'redirect_uri': redirect_uri,
      client_id: process.env.CLIENT_ID,
      client_secret: process.env.CLIENT_SECRET
    }, headers: {
        'Authorization': `Basic ${auth}`,
        'Content-Type':'application/x-www-form-urlencoded'
      }
    })
    .then(res=>{
      console.log(res.data)
    })
    .catch(err=>{
      console.log(err)
    })
})

Answer: You set the content type correctly, but you are sending the data in JSON format instead of x-www-form-urlencoded format.
The following JSON format
      params: {
      'grant_type': 'authorization_code',
      'code': 'my_secret_code
    }

can be converted to x-www-form-urlencoded like this:
params = 'grant_type=authorization_code&code=my_secret_code'

Try updating your request like this:
  const params = 'grant_type=authorization_code&code=' + req.body.code
               + '&redirect_uri=' + redirect_uri
               + '&client_id=' + process.env.CLIENT_ID
               + '&client_secret=' + process.env.CLIENT_SECRET';

  axios.post(token_uri,
    params,
    {
      headers: {
          'Authorization': `Basic ${auth}`,
          'Content-Type':'application/x-www-form-urlencoded'
        }
    })
    .then(res=>{
      console.log(res.data)
    })
    .catch(err=>{
      console.log(err)
    })


How to calculate appropriate google maps zoom level

Question: I have a tricky question...I am using the google maps static API to create an image of a map with markers on it.  What I am struggling to do is calculate the appropriate zoom level, given the positions of the two markers I want to display.
I have latitudeA, longitudeA, latitudeB, longitudeB, and the center point (easy).  Does anyone know of a formula to solve for zoom level?
Thanks!
Answer: I took 3 static maps at levels 11, 12 and 13, and used the "Maps Labs" feature of Google Maps, holding down the shift key at the corresponding min/max latitude/longtitude marks.  Then I wrote a Perl program to calculate the latitude/longtitude ranges, the expected values (with the formula I predicted by inspecting the data), and the deltas (ie. abs(expected - range)), which should be close to zero.
Once I had convinced myself that I had gotten as close as I could, here were my results:
Z11:  LatRange[0.323999]  ExpLat[ 0.324]  DeltaLat[  0.0000000000000019]
Z11:  LonRange[0.439999]  ExpLon[  0.44]  DeltaLon[  0.0000000000000023]

Z12:  LatRange[0.161999]  ExpLat[ 0.162]  DeltaLat[  0.0000000000000010]
Z12:  LonRange[0.219999]  ExpLon[  0.22]  DeltaLon[  0.0000000000000011]

Z13:  LatRange[0.081000]  ExpLat[ 0.081]  DeltaLat[  0.0000000000000031]
Z13:  LonRange[0.109999]  ExpLon[  0.11]  DeltaLon[  0.0000000000000006]

And the formulas I used were:
ExpLat = 0.162 * (2 ** (12 - Z))
ExpLon = 0.220 * (2 ** (12 - Z))

Where ExpLat, ExpLon are the expected latitude and longtitude ranges, and Z is the zoom level.
Answer: Even though you are using the static maps api,  you can still reference the regular maps script file, and then do a bounding box calculation:
map = new GMap2(document.getElementById("map"));

// Define the two corners of the bounding box
var sw = new GLatLng(59.0, 13.12); //any lat,lng pair
var ne = new GLatLng(60.35, 16.90);

var bounds = new GLatLngBounds(sw, ne);

var zoom = map.getBoundsZoomLevel(bounds));

Comment: Sorry, i didn't do enough research.  Apparently if you don't specify a zoom OR center, but include markers on the map, google static maps will fit the bounds for you
Comment: See question http://stackoverflow.com/questions/6048975/google-maps-v3-how-to-calculate-the-zoom-level-for-a-given-bounds - it seems to have an answer to how to do this manually.
Comment: well technically I'm not using the maps api, all I'm trying to do is get a map image to embed in an email.  Is there no way to do this (mathematically) without using GMap calls?
Comment: Are you using any type of programming language to calculate this, or are you just trying to copy/paste the link from somewhere?
Comment: Technically this is in PHP, but i'm trying to get an appropriate static google maps link like:

"http://maps.googleapis.com/maps/api/staticmap?center=centerLat,centerLng&zoom=zoomLevel&size=widthxheight&maptype=roadmap&markers=color:green%7Clabel:P%7CLat1,Long1&markers=color:red%7Clabel:D%7CLat2,Long2&sensor=false";
Comment: Sorry, I am not much use when it comes to php.


Distance measure for binary arrays

Question: Basically if I have binary sequence that I want to check against, and I want to determine how far other binary sequences are to this first sequence, what is the most appropriate measure to use.
The distance measures i have seen, like Manhattan etc., all give numeric values indicating ultimately the difference, not how far one sequence is from another.
For example -
A - 0101000010
B - 0000000010
C - 0101000000
D - 0000000100
C is much closer in similarity to A, than B is.
I want a measure that calculates a percentage of the relative distances between all the values seen. The distance measures would score B and D the same - I want to show that D is actually further in similarity than B, and that C is the closest.
I have tried SOkal-SneathIV and other distance measures from "A Survey of Binary SImilarity and Distance Measures", 2009 - however for the sequences which have the same mismatches (regardless of position) end up with the same score - whereas I want the position reflected in the measure.
Thanks,
U.
Answer: Why not just counting the components of the array that differ?
This way the distance from A to be will be 2, from A to C 1, and from A to d 3.
Or if you prefer the square root of 2, of 1, of 3.
Comment: Yes but then any sequences which have the same differences will receive the same score. So if SeqX and SeqY have two changes in total but in different places then the score would be 2 in both cases - I want a measure to help say which one is further from  being identical. Thanks. U.
Answer: Here is a relatively standard distance measure for binary sequences:
$d(x,y) = 2^{-n}$ where $x$ and $y$ have the same first $n$ digits and differ thereafter.

Distance measure for binary arrays


Has anyone created a method for cloning a squarespace site to create a new squarespace site?

Question: As I understand it, Squarespace provides no method to clone a site. Clone means to create a new squarespace site (not re-create ex-squarespace).
My latest project includes creating a 'base site' and then cloning it for different customers (and each clone will have it's own template tweaks, new blogs and calendar, etc), but all the rest of the content will be the same as the original.
I'm figuring that some enterprising developer/firm has solved this problem using scripts, etc.  Please help! Or I will need to use Weebly instead, which DOES support cloning sites.
Answer: Unfortunately, it's not possible. Here's a similar question on stackoverflow, and an official answer from Squarespace.
Answer: I spoke with a Squarespace rep...  He explained that it is possible if you follow these steps:
1.)  Select the website from your Dashboard that you want to DUPLICATE.
2.)  Click on the 3 dots and choose "DUPLICATE WEBSITE."
3.)  You will need to invite the future recipient of the new website to be a "Contributor."
4.)  Then you may Transfer Ownership to that "Contributor."
Contact Squarespace and describe the above steps and they will help you through it.


what is the average cost of a product, given the cost of each case and its probability

Question: for the 33rd sum, part a, I did
average cost = 5[P(x<8.04)] + 6.5[P(X>8.04)]
i got 5.46 but the text says 5.11
where did i go wrong
also, the answer for part b says 7.39. Is that possible, given that its supposed to be 'average' but 7.39 is greater than 6.50 (the maximum cost)?
Comment: You seem to have ignored the last sentence, where you're told very short rods are scrapped. I think you have the answer to (b) instead.
Comment: no i didnt ignore it, it says cost and since they are sold for 1, the cost is still 5, so i included it in the first term. first I thought it would be 4 instead but in that case, i should subtract the selling price from the normal rods and the long ones as well, but its not given so thats not possible.
Comment: I think the short rods  _net_ cost is only $\$4$ since they recoup $\$1$ from the sale as scrap. That might give you the text answer. I agree that there's some ambiguity in the question.
Comment: i tried that too even though the net costs for the others is not known, but i still did not get the answer. maybe its just wrong in the textbook lol
Comment: Maybe - that does happen. I agree that the answer to (b) makes no sense. For (a) the net costs for the others is $\$5$. Last thing to check might be your calculation of the probabilities (three of them for the three intervals). In any case I think you do understand the principles involved. Perhaps it's time just to move on.
Comment: I think the idea of (b) is that if a rod is too short then it is not usable. Taking a more extreme example, if you spent $\$5$ on each attempt to make an item, but $99$ out of $100$ attempts created worthless junk that couldn't even be sold for scrap, then the average cost per _usable_ item would be $\$500.$
Answer: Let $X$ denote the length of a rod and let $Z=(X-8.02)/0.04$.
For (a) you should be calculating:
$$4\text{Pr}(X<8.00)+5\text{Pr}(8.00<X<8.04)+6.5\text{Pr}(X>8.04)$$
Now, $$\text{Pr}(X<8.00)=\text{Pr}(X>8.04)=\text{Pr}(Z>0.5)=0.5-0.19146=0.30854$$
and
$$\text{Pr}(8.00<X<8.04)=2(0.19146)=0.38292.$$
Substituting:
$$4(0.30854)+5(0.38292)+6.5(0.30854)=5.15427$$
(The difference in answers is probably due to rounding errors.)
For (b) the average cost is:
$$\begin{align*}\frac{4\text{Pr}(X<8.00)+5\text{Pr}(8.00<X<8.04)+6.5\text{Pr}(X>8.04)}{\text{Pr}(8.00<X<8.04)+\text{Pr}(X>8.04)}\end{align*}$$
The denominator is $1-\text{Pr}(X<8.00)=1-0.30854=0.69146$
So the average cost is the answer from (a) divided by $0.69146$, i.e. $7.45$
Comment: +1 This answer to (b) is reasonable if it's interpreted as (total cost of all rods)/(number of saleable rods) but not if it's meant to be (total cost of saleable rods)/(number of salable rods). You and the text think the former, which is probably the right reading, but the other is defensible. The question is ambiguous.


Deduct 10% transaction fee when user donates userpoints to another user using rules - Drupal 7

Question: I want to use rules to deduct 10% of the transaction amount from a donor each time he donates userpoints to another user using the userpoints_donate contrib module. Currently there are no rules events or actions from the userpoints_donate contrib module
possible events: user donates points to another user
possible conditions: donation_amount <=> a particular value
possible actions: grant points to donor = (donation_amount * -0.1, i.e grant -10% of donation_amount to donor)
How can i achieve this? Thanks
Answer: If you see userpoints_donate.module userpoints_donation_giveform_submit function is reponsible to award points to another user
/**
 * Submit function to give another user points.
 */
function userpoints_donation_giveform_submit($form, &$form_state) {
  global $user;

  $points = $form_state['values']['amount'];
  $to = $form_state['validated_account'];

  $tid = NULL;
  if (isset($form_state['values']['tid'])) {
    $tid = $form_state['values']['tid'];
  }

  $params = array(
    'uid'    => $to->uid,
    'points' => $points,
    'operation'  => 'userpoints_donation_received',
    'entity_type' => 'user',
    'entity_id' => $user->uid,
    'description' => $form_state['values']['reason'],
    'tid'    => $tid,
  );
  userpoints_userpointsapi($params);

  $params = array(
    'uid'    => $user->uid,
    'points' => -$points,
    'operation'  => 'userpoints_donation_given',
    'entity_type' => 'user',
    'entity_id' => $to->uid,
    'description' => $form_state['values']['reason'],
    'tid'    => $tid,
  );
  userpoints_userpointsapi($params);
}

As you see above
userpoints_userpointsapi($params); is called to award $points with transaction operation userpoints_donation_received .
You can use hook_userpoints($op, $params = array()) to act upon certain operations. When other modules award  points to a user, your hook will be called, among others.

$op: The operation to be acted upon.
      'setting'
        Pass a field set and fields that would be displayed in the userpoints
        settings page. For example, this can be used for your program to ask
        the admin to set a number of points for certain actions your module
        performs. The function should return an array object conforming to
        FormsAPI structure.
'points before'   Calls your module, and others, before the points are
  processed. You can   prevent points from being awarded by returning
  FALSE.
'points after'   Calls your module, and others, after points are
  processed. You can take   certain actions if you so wish. Return value
  is ignored.
The $params variable is the original $params array as sent to
  userpoints_userpointsapi

Using "Points after" $op and  in $params check for operation "userpoints_donation_received"  you make a call to deduct 10 % points using..

userpoints_userpointsapi($params); API function..
<?php
function YOURMODULENAME_userpoints($op, $params) {
  if ($op == "points after") {
    if ($params['operation'] == "userpoints_donation_received") {
      $transaction_params = $params;
      $transaction_params['points'] = -( $transaction_params['points'] / 10);
      $transaction_params['operation'] = "userpoints_donation_transaction_fee";
      $transaction_params['description'] = "Transaction Fee";
      userpoints_userpointsapi($transaction_params);
    }
  }
}

Comment: Thanks for your detailed explanation and code. I'll try this out now and accept your answer if it works, i appreciate.
Comment: when i try this code in a custom module, i get the code printed out on my screen: function userpoints_commission_userpoints($op, $params) { if ($op == "points after") { if ($params['operation'] == "userpoints_donation_received") { $transaction_params = $params; $transaction_params['points'] = -( $transaction_params['points'] / 10); $transaction_params['operation'] = "userpoints_donation_transaction_fee"; $transaction_params['description'] = "Transaction Fee"; userpoints_userpointsapi($transaction_params); } } }
Comment: the code also shows up as ajax error on screen when i try to perform any userpoints transaction. apart from that, it just shows up at the top of every page
Comment: Wrap them up with  211  //receiver user
    [points] => 500
    [operation] => userpoints_donation_received
    [entity_type] => user
    [entity_id] => 1  //donor user
    [description] => some donation
    [tid] =>
    [reference] =>
    [display] =>
    [status] => 0
    [expired] =>
    [parent_txn_id] =>
    [expirydate] => 0
    [time_stamp] => 1396955841
    [changed] => 1396955841
    [txn_id] => 6
    [approver_uid] => 0
)
Comment: disabling the custom module, the credit and deduction works fine with the userpoints donation module, just troubleshooting to see the problem isn't from donation module


Gmail picking up parts of media-query styles (Mailchimp)

Question: I'm finishing up a Mailchimp template and Gmail is the biggest headache now.
In my head I have some styles (css) and media queries. If I put the media-queries at the bottom - it stops most of the styles from getting through. If I put the media queries at the top - all my styles work perfectly but the mail looks "broken down" (like it should under 600px width / Mobile) like the media queries already kicked in.
Firstly I didn't think Gmail should read anything inside of a media-query and secondly why are is my mail shown "responsive" when I have full browser width?
---- on a side note ---- I know I can go through everything and add inline styles but, I have three templates and I'd rather not if I can get away with it :)
Comment: See http://stackoverflow.com/a/11697326/595525
Comment: Gmail strips everything outside of the body tag, which includes style tags. Perhaps this unusual behavior is because you have the media query somewhere in the body? What you are describing sounds weird - you'll need to post code and screenshots if you want anyone to help resolve the situation. On the side note, you can work in the style tag, just run it through one of these [inlining tools](http://stackoverflow.com/questions/791070/what-tools-to-automatically-inline-css-style-to-create-email-html-code/17882057#17882057) before sending.
Comment: Yes. this is  strange. However, the CSS you write in mailchimp renders as inline when you send your campaigns. So I guess the issue is there? Is anyone familiar with the way Mailchimp works with the css styles in the head?
Answer: I found out through extensive google-ing that I'm not the only one in the world that had this (weird) problem. I quote Lucas Mainardi below that posted an answer to a similar problem for Outlook.com.
Basically, putting an extra style tag with your media queries just before the closing body tag will fix things.
I've tested on my devices (gmail, iphone, thunderbird) and it doesn't seem to do any damage for clients that didn't have problems before. I'm also waiting for my Mailchimp inbox inspections to finish (where I test more clients like Outlook, Android etc). I'll edit my answer if it seems to do any harm, otherwise consider this a solution.

Hello James,
In the comments bellow I posted a possible solution to this issue in Outlook.com.
The problem seems to be the area in which the email is loaded. Apparently, the area starts out in a small size and is resized a few seconds later, but in that time the media queries fire up and display the mobile version. This is because the media queries are read first in the hierarchy of the code (they're at the head section) and the HTML email is read second.
The solution I found is to place the style section which contains the media queries after the HTML e-mail, specifically right above the closing body tag.
I tried this out in Litmus and all seemed to work just fine across the board (no other browsers/mobile devices/e-mail servers seem to be affected negatively, displaying the exact same version of the email with the styles in the head section).

Taken from http://emailwizardry.nightjar.com.au/2013/08/28/media-queries-in-html-email-cover-all-your-bases/


Max/Min principles of Helmhotz-like equations

Question: Let $\Omega  \subset {R^n}$ be a bounded domain and $u \in {C^2}\left( \Omega  \right) \cap {C^0}\left( {\bar \Omega } \right)$.  Which ones of the following 6 equalities and inequalities have the maximum or minimum principles?
I tried answering (2), (4) and (6).  Please help.
(1) $\Delta u\left( x \right) + u\left( x \right) = 0$   in $\Omega $  ${\rm{  }} \Rightarrow {\rm{   }}$ ?
(2) $\Delta u\left( x \right) - u\left( x \right) = 0$   in $\Omega $    $ \Rightarrow {\rm{   }}\mathop {\max }\limits_{\bar U} u = \mathop {\max }\limits_{\partial U} u{\rm{ }},{\rm{ }}\mathop {\min u}\limits_{\bar U}  = \mathop {\min u}\limits_{\partial U} $
(3) $\Delta u\left( x \right) + u\left( x \right) \ge 0$  in  $\Omega {\rm{   }} \Rightarrow {\rm{   }}$  ?
(4) $\Delta u\left( x \right) - u\left( x \right) \ge 0$   in $\Omega $    $ \Rightarrow {\rm{   }}\mathop {\max }\limits_{\bar U} u = \mathop {\max }\limits_{\partial U} u{\rm{ }}$
(5) $\Delta u\left( x \right) + u\left( x \right) \le 0$  in  $\Omega {\rm{   }} \Rightarrow {\rm{   }}$  ?
(6) $\Delta u\left( x \right) - u\left( x \right) \le 0$   in $\Omega $   ${\rm{   }} \Rightarrow {\rm{    }}\mathop {\min u}\limits_{\bar U}  = \mathop {\min u}\limits_{\partial U} $
Answer: Certainly the first one doesn't have a min/max principle. Consider that equation in 1 dimension with domain $[0, 2\pi]$. One solution is given by $u(x) = \sin(x)$ depending on boundary conditions but the max and min don't occur on the boundary. Likewise, (3) and (5) won't have min/max principles. As far as the other ones, I'm fairly certain you are correct.


Various ways to return multiple values of the same type

Question: Say I have a Java method that prompts the user for various double values and returns them back to the main method:
  double Prompt(double theta, double omega, double length, double mass) {
    double theta_read, omega_read, length_read, mass_read;
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Initial angle [rad]: ");
    theta_read = 0.0;
    try {
      theta_read = Double.parseDouble(br.readLine());
    } catch (IOException ioe) {
      System.out.println(ioe);
      System.exit(1);
    }
    theta = theta_read;
    System.out.print("Initial angular velocity [rad/sec]: ");
    omega_read = 0.0;
    try {
      omega_read = Double.parseDouble(br.readLine());
    } catch (IOException ioe) {
      System.out.println(ioe);
      System.exit(1);
    }
    omega = omega_read;
    System.out.print("Length of pendulum [m]: ");
    length_read = 0.0;
    try {
      length_read = Double.parseDouble(br.readLine());
    } catch (IOException ioe) {
      System.out.println(ioe);
      System.exit(1);
    }
    length = length_read;
    System.out.print("Mass of pendulum bob [kg]: ");
    mass_read = 0.0;
    try {
      mass_read = Double.parseDouble(br.readLine());
    } catch (IOException ioe) {
      System.out.println(ioe);
      System.exit(1);
    }
    mass = mass_read;
    //return code here
  }

Using the example above, what are the different ways one could return multiple values of the same type, and what are the merits of each?
Comment: Your code is a little weird because the doubles you're passing in are passed by value. Changing their values in that method will not change the values of the ones in the calling code - maybe you knew that. Anyway, it's redundant and unnecessary to have a *_read version of every variable in your code.
Answer: The easiest way to return multiple values is by returning a Double array, arrayList, or any type-double hashMap.
If you have to return three values, using arrays would be:
double array[] = new double[3];
array[0] = value1;
array[1] = value2;
array[2] = value3;
return array;

The problem of using this solution is that you must need to know the quantity of values you need to return from the beginning. If that's not the case you should proceed with the next one:
And with arraylists
ArrayList<double> arraylist = new ArrayList<double>();
arraylist.add(value1);
arraylist.add(value2);
arraylist.add(value3);
return arraylist;

This solution can be better for cases where you don't have the quantity of elements to use. And, if you want to use string-indexed values, you can use Hashmaps:
HashMap<String, double> map = new HashMap<String, double>();
map.put("first value", value1);
map.put("second value", value2);
map.put("third value", value3);
return map;

In all situations you can do this inside a for-loop (obviously), however, depending on the situation, if you have a limited quantity of elements, using simple arrays is the best solution. If you don't know the quantity use arraylists, and finally if you require to use string indexes hashmaps are the solution. Using arrays would be the trivial solution.
Comment: Please make your answer complete.  You mention three different methods, so please format your answer accordingly.  _What are the advantages/disadvantages of each approach?_
Answer: I can see three basic options here, considering you would work with double as an example:

Return array of double values

PRO: this is perhaps the easiest solution, quickly coded and with quite small memory usage since you work with primitive types here; if you need a new value, you just define array with one more element and add the new value to the end of the array
CON: you would have to "remember" what value is on which index and you would have to ensure these positions never change, otherwise callers of the method would start to have problems in the code that uses these returned values

Prepare your own class that hold all the values as its fields

PRO: this is probably the safest way, provided you either have all those values as zero (or other default value - in case of using primitives) or null (in case of using Double) to make adding new values in future releases safer (meaning it does not affect callers who started to use the class earlier); also, this is not limited to one data type only
CON: additional class to take care of - very simple one, so this is basically not a con :-)

Use HashMap of Double values

PRO: this may be somewhat easier to write/read - the more if you define your own class (enum?) for the map keys to ensure users only get supported values; HashMap is usually very fast
CON: somewhat more complicated as you would have more classes to manage; increased memory usage due to bigger amount of objects needed to achieve what you need; if you have only few values to return, this is probably unnecessarily complex

My personal choice would probably be to go with option 2 - use your own class and store the values in its fields, although it also depends on the usage scenario. In your case this could very likely be the way to go.
Comment: Option 2 would not have bigger memory usage, it would actually be smaller. An object with 4 int fields is the size of an object overhead + 4 int values, An array with 4 values is the size of an object overhead (the array object) + 4 int values + 1 int for the array length.
Comment: How about getters/setters, don't they need to be taken into account?
Comment: You're talking about the overhead of loading an additional class, I'm talking about the overhead of an object instance. You should never consider eliminating a class for size reasons, especially not if it removes clarity of the code. The memory usage of a single class or a single instance is meaningless, however the memory usage of 10000+ instances may make a difference.
Comment: OK, now I see your point. Thanks for bringing this up, I have edited the answer.
Answer: There are 4 ways to return multiple values from a method:

Return an array.
Return a collection, e.g. list or set.
Return an object with values.
Pass in a result collector.

Options 1 and 2 usually require all values to be same type, although that type can be a super class or interface. In the extreme case of using Object, any type can be used, but it eliminates the type safety of Java, so that's not a good idea.
Option 3 will require a custom class, but multiple values can have different names and types, providing more structure to heterogeneous values.
Option 4 can be use array (unlikely), collection, or custom class. Useful if multiple calls should keep adding to the same collector.
So, if all values are the same type, without different meaning, use option 1 or 2.
If values have different meaning, use option 3.
If repeated calls should append/merge with previous results, use option 4.
If values have same meaning, but different type, consider using an interface to unify the type.

In your case, you have 4 values of same type but different meaning, so option 3 would be best.
The prompt() method could then be a static method of that class, prompting the user and returning an instance of the class with the entered values. It should probably take the BufferedReader (or Scanner) as a parameter, in case the caller might want to prompt for other values too.

As an example to show this:
// Option 1 (return an array)
return new double[] { theta, omega, length, mass };

// Option 2 (return a collection)
List<Double> result = new ArrayList<>();
result.add(theta);
result.add(omega);
result.add(length);
result.add(mass);
return result;

// Option 3 (return an object)
// Not showing full implementation of Pendulum because it should be obvious)
return new Pendulum(theta, omega, length, mass);

// Option 4 (result collector)
void prompt(Pendulum result) {
    // existing code, then
    result.setTheta(theta);
    result.setOmega(omega);
    result.setLength(length);
    result.setMass(mass);
}


var cannot be resolved to a type - java-10

Question: I simply installed JDK 10 on my mac machine. Checked for the version:-
localhost:java-10 vinayprajapati$ java -version
java version "10" 2018-03-20
Java(TM) SE Runtime Environment 18.3 (build 10+46)
Java HotSpot(TM) 64-Bit Server VM 18.3 (build 10+46, mixed mode)

Just to make sure that compiler used is also same version, I ran below:-
localhost:java-10 vinayprajapati$ javac -version
javac 10

I created a simple Maven project with following structure:-
localhost:java-10 vinayprajapati$ tree
.
├── pom.xml
├── src
│   ├── main
│   │   └── java
│   │       └── com
│   │           └── practice
│   │               └── java_10
│   │                   └── App.java
│   └── test
│       └── java
│           └── com
│               └── practice
│                   └── java_10
│                       └── AppTest.java
└── target

My pom.xml is:-
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.practice</groupId>
    <artifactId>java-10</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>java-10</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.7.0</version>
                <configuration>
                    <release>10</release>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>org.ow2.asm</groupId>
                        <artifactId>asm</artifactId>
                        <version>6.1</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>
</project>

My App.java file is:-
package com.practice.java_10;

import java.util.ArrayList;

public class App {
    public static void main(String[] args) {
        var list = new ArrayList<String>();
        System.out.println("Hello Java 10! Shall I welcome you?");

    }
}

I ran mvn compile and mvn install and both worked successfully. Proof below:-
localhost:java-10 vinayprajapati$ mvn compile
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------< com.practice:java-10 >------------------------
[INFO] Building java-10 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ java-10 ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /Users/vinayprajapati/Desktop/project/java-10/java-10/src/main/resources
[INFO]
[INFO] --- maven-compiler-plugin:3.7.0:compile (default-compile) @ java-10 ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 1 source file to /Users/vinayprajapati/Desktop/project/java-10/java-10/target/classes
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.823 s
[INFO] Finished at: 2018-03-23T01:49:13+05:30
[INFO] ------------------------------------------------------------------------
localhost:java-10 vinayprajapati$ mvn install
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------< com.practice:java-10 >------------------------
[INFO] Building java-10 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ java-10 ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /Users/vinayprajapati/Desktop/project/java-10/java-10/src/main/resources
[INFO]
[INFO] --- maven-compiler-plugin:3.7.0:compile (default-compile) @ java-10 ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ java-10 ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /Users/vinayprajapati/Desktop/project/java-10/java-10/src/test/resources
[INFO]
[INFO] --- maven-compiler-plugin:3.7.0:testCompile (default-testCompile) @ java-10 ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 1 source file to /Users/vinayprajapati/Desktop/project/java-10/java-10/target/test-classes
[INFO]
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ java-10 ---
[INFO] Surefire report directory: /Users/vinayprajapati/Desktop/project/java-10/java-10/target/surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.practice.java_10.AppTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.029 sec

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

[INFO]
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ java-10 ---
[INFO] Building jar: /Users/vinayprajapati/Desktop/project/java-10/java-10/target/java-10-0.0.1-SNAPSHOT.jar
[INFO] META-INF/maven/com.practice/java-10/pom.xml already added, skipping
[INFO] META-INF/maven/com.practice/java-10/pom.properties already added, skipping
[INFO]
[INFO] --- maven-install-plugin:2.4:install (default-install) @ java-10 ---
[INFO] Installing /Users/vinayprajapati/Desktop/project/java-10/java-10/target/java-10-0.0.1-SNAPSHOT.jar to /Users/vinayprajapati/.m2/repository/com/practice/java-10/0.0.1-SNAPSHOT/java-10-0.0.1-SNAPSHOT.jar
[INFO] Installing /Users/vinayprajapati/Desktop/project/java-10/java-10/pom.xml to /Users/vinayprajapati/.m2/repository/com/practice/java-10/0.0.1-SNAPSHOT/java-10-0.0.1-SNAPSHOT.pom
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.157 s
[INFO] Finished at: 2018-03-23T01:49:22+05:30
[INFO] ------------------------------------------------------------------------

When ran mvn exec:java -Dexec.mainClass="com.practice.java_10.App", I got error as below :-
localhost:java-10 vinayprajapati$ mvn exec:java -Dexec.mainClass="com.practice.java_10.App"
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------< com.practice:java-10 >------------------------
[INFO] Building java-10 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- exec-maven-plugin:1.6.0:java (default-cli) @ java-10 ---
[WARNING]
java.lang.Error: Unresolved compilation problem:
    var cannot be resolved to a type

    at com.practice.java_10.App.main (App.java:11)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:564)
    at org.codehaus.mojo.exec.ExecJavaMojo$1.run (ExecJavaMojo.java:282)
    at java.lang.Thread.run (Thread.java:844)
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.019 s
[INFO] Finished at: 2018-03-23T01:51:02+05:30
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.6.0:java (default-cli) on project java-10: An exception occured while executing the Java class. Unresolved compilation problem:
[ERROR]     var cannot be resolved to a type
[ERROR]
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

I am not sure why am I getting this error. Any thoughts are welcome. Meanwhile I try searching for root cause.
Answer: You have to set the runtime plugin to Java 10 too or the root configuration. Right now it's just the compiler.
Comment: When you run a maven command like `compile` or `exec` you are activating a plugin. There are default plugins and configurations, you changed those for the `maven-compiler-plugin` to use Java 10. Look up "maven executions" and the exec plugin. Or you can try adding this to the top of your code
`10`
Comment: No. Either the `java` goal in Maven or the `exec` plugin, just like you did with the maven compiler plugin.
Comment: You seems correct. I figured out that compiled code version was 9 while execution JRE version was 10.
Comment: Best solution for this is toolchains http://maven.apache.org/guides/mini/guide-using-toolchains.html.
Comment: you mean the JRE? I checked for both java and javac versions and both point to java-10
Comment: sorry, not really good at maven. would you mind putting more details in your answer itself?
Answer: In my case I had:
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>17</source> <-----
                <target>17</target> <-----
           ...

And I had to match this version with <java.version> value
Comment: Would have been ideal if you had included the whole POM so someone reading this in the future could figure out what you changed.
Comment: @FreelanceConsultant I added arrows for that. For the rest I think it's enough searchable
Comment: Without the rest of the pom, I have no idea where this is supposed to be placed.
Comment: @FreelanceConsultant just search `maven-compiler-plugin`. If you cannot find it in your pom, then this isn't a problem for you


TypeScript does not recognize that React is being imported and used in my linter in VSCode

Question: I'm building an app using React Native with TypeScript. I do my navigation using React Navigation.
In my navigator I'm using Icons from React Native Elements for the tabs. In order to use them I have to import React. But my linter does not recognize that I use it. It says:
[ts] 'React' is declared but its value is never read.

Here is my code:
import DetailScreen from "../screens/Detail";
import HomeScreen from "../screens/Home";
import LoadingScreen from "../screens/Loading";
import OptionsScreen from "../screens/Options";
import SettingsScreen from "../screens/Settings";
import React from "react";
import { Platform } from "react-native";
import { Icon } from "react-native-elements";
import {
  createBottomTabNavigator,
  createDrawerNavigator,
  createStackNavigator,
  createSwitchNavigator,
  NavigationSceneRendererProps,
  NavigationTransitionProps,
  StackViewTransitionConfigs,
  TabScene,
  TransitionConfig
} from "react-navigation";

// Some other code

const HomeStack = createStackNavigator(
  { DetailScreen, HomeScreen, OptionsScreen },
  // TODO: Rename the config from 'CustomTransitionConfig' to 'dynamicModalTransition'.
  { initialRouteName: "HomeScreen", transitionConfig: dynamicModalTransition }
);

HomeStack.navigationOptions = {
  tabBarLabel: "Home",
  tabBarIcon: ({ tintColor }: TabScene) => <Icon name="ios-home" type="ionicon" color={tintColor} />
};

const SettingsStack = createStackNavigator({ SettingsScreen });

SettingsStack.navigationOptions = {
  tabBarLabel: "Settings",
  tabBarIcon: ({ tintColor }: TabScene) => <Icon name="ios-cog" type="ionicon" color={tintColor} />
};

const MainNavigator = Platform.select({
  ios: createBottomTabNavigator({ HomeStack, SettingsStack }),
  android: createDrawerNavigator({ HomeStack, SettingsStack })
});

const RootSwitch = createSwitchNavigator(
  { LoadingScreen, MainNavigator },
  { initialRouteName: "MainNavigator" }
);

export default RootSwitch;

What is going on here? Why does TypeScript not recognize React?
A suberror of this is that the <Icon />s properties each have the error:
[ts] '>' expected.
[ts] Cannot find name 'name'.
any

It just says color and type respectively.
Comment: Try doing `import * as React from "react";`.
Comment: @zeh Thank you for your help! I did, and it did not work.
Answer: Use the file extension .tsx instead of .ts when the file contains JSX syntax like <Icon ... />.


classification imbalance data - bias and class weight

Question: This page shows a classification problem. They have used bias as well as bias along with class weights.

What is the difference between bias and weights? In some other techniques such as Random Forest, we could adjust cut off from 50% to say 90% so that if the edge node has 90% examples of high-density class then only it will predict that class. Out of bias and weights, which one is similar to cut off probability?
When should I use just one of them or both? I can always run 3 models 1 with bias, 1 with class weight and 1 with both and compare the results. But is there any better reference?

keras.layers.Dense(1, activation='sigmoid',
                   bias_initializer=output_bias)

and
weighted_history = weighted_model.fit(
    train_features,
    train_labels,
    batch_size=BATCH_SIZE,
    epochs=EPOCHS,
    callbacks = [early_stopping],
    validation_data=(val_features, val_labels),
    # The class weights go here
    class_weight=class_weight)

Comment: The article you reference represents a basic misunderstanding of proper accuracy scoring rules.  See http://fharrell.com/post/class-damage
Comment: This sentence is confusing. "They have used bias as well as bias along with class weights." Is it possible that you've repeated a phrase? Is there a clearer way to express what you mean?
Comment: Cross-posted at https://datascience.stackexchange.com/q/67001/55122
Answer: The snippet you are showing takes is a layer that takes the output of a 16-dimensional hidden layer (let's call it $\mathbf{h}$) and does the following:
$$o = \sigma\left( \mathbf{w}^\top\mathbf{h} + b \right)$$
where $\mathbf{w} \in \mathbb{R}^{16}$ is the weight vector (inside fo TF is a matrix with a single row) and $b \in \mathbb{R}$ is the bias.
The role of bias, here, is to learn a preference for the most frequent class. If $o$ is positive, the model predicts, if it's negative, it predicts the other class. A reasonable strategy for the model is to learn a strong bias towards the most frequent class and learn to look for evidence why it should be otherwise. If you remove the bias from the model, you are basically forcing the model not to use this strategy which might be often hard to learn.
Another way if interpreting the bias is by viewing it as a kind of prior probability and the other term as getting evidence against the prior.
The class weights are used when computing the loss function. Here, you have two classes and thus you would have two weights $w_0$ and $w_1$. So, the loss will be as if there were $w_0$ examples of class $0$ and $w_1$ examples of class $1$. In this way, you can the underrepresented class more prominent and make sure the model learns more about it, but it also skews the bias term to a different distribution than is in the data.
Comment: There is, of course, no clear answer, you need to experiment, it very much depends on your data. Unless your data is so imbalanced that you would not be able to learn a suitable representation for the minority class, I would avoid setting class weights, so you train on a realistic distribution of target classes.
Comment: what do you mean `if o is positive`? `o` is a calculation, right? how would we know its value before calculating? I understand function of weights. But in this case they have an extra input `class_weight=class_weight`, what does it do?
Comment: Oh sorry, I misunderstood your question, I thought you meant different weights. By being positive I meant "gets evaluated as a positive number when it gets evaluated".
Comment: I edited, so it should make sense now.
Comment: could you answer my question 2? i am still not clear
Answer:
When we're talking about the estimated parameters of a neural network, a "bias" is any constant that's added to an input. Consider logistic regression, i.e. a neural network without hidden layers and a single, sigmoidal output. This network has the prediction equation
$$
  \hat{y} = \sigma(w^\top x+b)
  $$
where $x$ is the input vector, $w$ is the vector of weights and $b$ is the bias. The function $\sigma$ yields probabilities as its output: $0<\sigma(z)=\frac{1}{\exp(-z)+1}<1$. For this model, it should be obvious that increasing $b$ while keeping all else equal increases the predicted probability; contrariwise, decreasing $b$ does the opposite.
However, the situation becomes more complex when we consider a neural network with hidden layers. This is because changing the bias for a node at the "beginning" or "middle" of the network can increase or decrease the predicted probability, depending on what happens "downstream" of the unit.
Finally, the utility of class weights in neural networks is not as simple as presented in your TensorFlow tutorial. The intuition that we have about instance weights in simple settings like logistic regression do not hold when using over-parameterized neural networks. Indeed, neural networks are flexible enough that they can effectively overcome instance weighting.

Jonathon Byrd, Zachary C. Lipton. "What is the Effect of Importance Weighting in Deep Learning?"

Importance-weighted risk minimization is a key ingredient in many machine learning algorithms for causal inference, domain adaptation, class imbalance, and off-policy reinforcement learning. While the effect of importance weighting is well-characterized for low-capacity misspecified models, little is known about how it impacts over-parameterized, deep neural networks. Inspired by recent theoretical results showing that on (linearly) separable data, deep linear networks optimized by SGD learn weight-agnostic solutions, we ask, for realistic deep networks, for which many practical datasets are separable, what is the effect of importance weighting? We present the surprising finding that while importance weighting impacts deep nets early in training, so long as the nets are able to separate the training data, its effect diminishes over successive epochs. Moreover, while L2 regularization and batch normalization (but not dropout), restore some of the impact of importance weighting, they express the effect via (seemingly) the wrong abstraction: why should practitioners tweak the L2 regularization, and by how much, to produce the correct weighting effect? We experimentally confirm these findings across a range of architectures and datasets.

If by "bias" you only mean the ultimate bias applied in the final network layer, it should be clear that you have a choice to achieve a desired trade-off between classification errors:

You can adjust the final bias in the neural network to move all predicted probabilities up or down. This will distort the predicted probabilities. The caveat to focusing on hard classifications is that you're discarding all of the fine-grained information conveyed by a predicted probability. Frank Harrell has written a number of posts here and elsewhere about the dangers of using hard-and-fast cutoffs.
You can leave the final bias at whatever value minimizes the loss, and instead choose a different threshold to transform predicted probabilities into class designations. That is, instead of having the rule "If $\hat{y} > 0.5$, predict 'This is an image of a dog,'" you can use the rule "If $\hat{y} > 0.9$, predict 'This is an image of a dog.'" This option does not distort the predicted probabilities, and instead only changes which observations are allocated to which class.

In light of the foregoing, my recommendation is to not use class weights. Let the optimizer find the optimal value of your weights and biases. Ideally, the decisions you make should result from a contextual consideration of the risks involved: if you're wrong, is a healthy person taking an unnecessary course of antibiotics? Or is a healthy person having a limb amputated? Or is a sick person missing out on a treatment? Is the treatment critical to their life, or is it too risky considering their overall health, age and other infirmities?
If you need some sort of a hard decision (perhaps because you're creating an automation system requiring minimal human intervention), then you should pick a decision threshold which achieves your desired trade-off of correct predictions against incorrect predictions. That is, any time you're making a decision on the basis of a machine learning model's prediction, you're at risk of either a false positive or false negative. You should carefully assess the risks to your organization of both types of errors, and choose a threshold which balances the costs of both types of errors. In some problems, this means you'll tolerate a higher false positive rate in order to find as many positives as possible; in others, you'll tolerate a higher false negative rate in order that the positives that you uncover are "high confidence" targets.
Answer: As far as I know the bias_initializer is used in order to set the initial weights/biases.
class_weight is used when you have inbalanced distribution of classes eg. 10 roses (class 0), 1 tulip (class 1) and 2 coliflowers (class 2)
The model will learn the features of roses pretty well but disregard tulips and coliflowers since they are way less represented in the training data.
I personally take a representative sample of my training data. This poses some risk as not all classes may be included or your file might not be representative of your whole training data. I then take this representative file and calculate the class distribution on it.
The following function takes an input csv file and counts all the classes. Then the weight distribution is calculated and a dictionary returned which the model.fit will consume.
def getClassDistribution(path, lines):
    print('getting class distribution')
    progress = 0
    classes = dict()
    # open sample file and count classes
    with open(path, "r",encoding="utf-8",errors='ignore') as f:
        line = f.readline()
        while line:
            if line != '':
                label = int(line[-2:-1])
                if label in classes:
                    classes[label] += 1
                else:
                    classes[label] = 1
            printProgressBar(progress,lines)
            progress += 1
            line = f.readline()
    max = 0
    # calculate weight distribution
    for x in classes:
        if classes[x] > max:
            max = classes[x]
    for x in classes:
        classes[x] = classes[x]/max
        classes[x] = 1 + (1 - classes[x])
    print()
    return classes

classDistr = getClassDistribution(trainPath+"0.data", trainSteps*trainBadgeSize)

this will yield a dictionary like this:
classDistr = {0: 1.0,
                1: 10.0,
                2: 5.0}

then in model.fit:
class_weight=classDistr,

Basically it tells the network to train ten times "harder" on tulips and 5 times harder on coli-flowers accommodating for the different amount of samples.
Another example of the usage:
I want to predict upward/downward movement. I have 70% of upward classes and 30% of downward classes. The model might get stuck predicting upward, simply because it is much more likely to occur rather than looking on the features.
One solution is to get 50% up 50% down in the train data, another way of accommodation is class_weights
Answer: If your input has mean zero and standard deviation one, and your hidden layers are properly initialized then the output of your very first forward pass should have mean zero and standard deviation one (as I understand it). If the activation function on your output is softmax then your output for three classes will be [0.333, 0.333, 0.333] while the targets will be [0, 0, 1] etc. That's quite a large loss from the get go. If the classes are unbalanced, e.g. 1x [1, 0, 0], 1x [0, 1, 0], and 8x [0, 0, 1] then you might want the first forward pass to output [0.1, 0.1, 0.8] instead. Since the network will most likely learn some values that are close to those anyway.
Looking at https://math.stackexchange.com/a/3162684/365424 we get that we can invert a softmax function like so:
$x_{i} = \ln(S_{i}) + \ln(\sum_{i} \exp(x_{i}))$
with the logarithm of the sum being constant but not determined. So if you use the log of class frequencies you should end up with something that works.
In this example a bias of [-0.22, -0.22, -2.3].
But if you have applied class weights such that each [1, 0, 0] contributes 8 times as much to the loss as each [0, 0, 1] and so on, then you would want [0.333, 0.333, 0.333] in the first forward pass and leave the bias initialization alone. Since your loss is now balanced.
If your classes are only partially balanced then I don't think I can help you.


Multiple Dir serving is not working

Question: Any mistakes in below code? Multiple directory serving is not working from the below code. When I access the localhost:9090/ide, the server will return 404 error.
package main

import (
    "log"
    "net/http"
)

func serveIDE(w http.ResponseWriter, r *http.Request) {
    http.FileServer(http.Dir("/home/user/ide")).ServeHTTP(w, r)
}

func serveConsole(w http.ResponseWriter, r *http.Request) {
    http.FileServer(http.Dir("/home/user/console")).ServeHTTP(w, r)
}

func main() {
    http.HandleFunc("/ide", serveIDE)
    http.HandleFunc("/console", serveConsole)
    err := http.ListenAndServe(":9090", nil)
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}

When I change the code like this,
http.HandleFunc("/", serveIDE)

It will work as I expected.
Answer: One of the issues with using http.FileServer is that the request path is used to build the file name, so if you're serving from anywhere but the root you need to strip the route prefix to that handler.
The standard library includes a helpful tool for that http.StripPrefix, but that only works on http.Handlers, not http.HandleFuncs, so to use it you need to adapt your HandleFunc to a Handler.
Here is a working version that should do what you want. Note that wHandler is just an adapter from your HttpFunc methods to Hander interface:
package main

import (
        "log"
        "net/http"
)

func serveIDE(w http.ResponseWriter, r *http.Request) {
        http.FileServer(http.Dir("/home/user/ide")).ServeHTTP(w, r)
}

func serveConsole(w http.ResponseWriter, r *http.Request) {
        http.FileServer(http.Dir("/home/user/console")).ServeHTTP(w, r)
}

type wHandler struct {
        fn http.HandlerFunc
}

func (h *wHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
        log.Printf("Handle request: %s %s", r.Method, r.RequestURI)
        defer log.Printf("Done with request: %s %s", r.Method, r.RequestURI)
        h.fn(w, r)
}

func main() {
        http.Handle("/ide", http.StripPrefix("/ide", &wHandler{fn: serveIDE}))
        http.Handle("/console", http.StripPrefix("/console", &wHandler{fn: serveConsole}))
        err := http.ListenAndServe(":9090", nil)
        if err != nil {
                log.Fatal("ListenAndServe: ", err)
        }
}

Multiple Dir serving is not working


Retrieve all installed packages and their versions from nodes

Question: I use puppet to manage package installations on a number of nodes. These nodes are used as software testing environments. It happens that packages are uninstalled during software tests or their version might change, depending on the test scenario.
Is it possible to retrieve a list of all currently installed packages on each of my nodes? A "snapshot" of the whole testing environment, so to say.
Thanks!
Answer: With Facter 2, you can create a custom fact that hands a hash structure to the master, e.g. package-name => package-version.
With PuppetDB, you can store all those fact values and retrieve them via the API.
Comment: I, actually, implemented such a "fact" here -- but it is limited to versions of the explicitly "white-listed" packages only.
Comment: I was thinking about it, but the sheer size of this hash scares me a little. A CentOS-7 box can easily have over a 1000 packages installed, for example. Is that not a concern -- both for the node and for the Puppet-master receiving facter-data from hundreds of such nodes?
Comment: @MikhailT. Yes, there will be performance implications. If possible, try it outside of production first. If you don't want it to hamper Puppet's daily business, setting up a distinct master (including DB) for this might still be easier than rolling your own data warehouse solution.


Concatenar array de checkboxes selecionados para usar como filtro de busca

Question: Tenho uma busca com diversos checkboxes que podem ser selecionados e adicionados dinamicamente pelo usuário. Como não sei a quantidade, estava pensando em fazer o seguinte: percorrer todos eles e ir concatenando com AND e usar isso na condição lá na busca.
O problema é que do jeito que fiz acaba ficando um AND sozinho no final da busca. Segue meu código:
$Busca = $_POST['txtbusca'];
$arrayFiltro = $_POST['chkDisciplina'];

for ($i=0; $i < count($arrayFiltro); $i++) {
    echo $arrayFiltro[$i]. "AND";
}

Existe uma maneira melhor?
Comment: Poste sua SQL que deve ser gerada com esse filtro de busca?
Answer: A função implode() foi feita para isso:
$separador = ' AND ';
$array = array( 'nome', 'email', 'fone' );
$string = implode( $separador, $array );
var_dump( $string );

Resulta em:

string(28) "nome AND email AND fone"
Comment: E, pra complementar, se preferir pode usar também o join()[http://www.php.net/manual/pt_BR/function.join.php], que é um apelido para o implode();
Comment: @LeoFelipe, confira a [formatação de comentários](http://pt.stackoverflow.com/editing-help#comment-formatting)
Comment: O link que pus no comentário acima ficou com o "]" no link, então segue sem: http://www.php.net/manual/pt_BR/function.join.php
Comment: Vlw @brasofilo. Nas próximas estarão com marcação correta!
Answer: Meio que gambiarra, mas tenta isso, você verifica, caso a variável de controle $i seja menor que o tamanho do array, você pode ir adicionando o AND no final, caso a variável seja igual ao tamanho do vetor, significa que é o último elemento, então não precisa de AND, então cai dentro do else.
$Busca = $_POST['txtbusca'];
$arrayFiltro = $_POST['chkDisciplina'];
$sql = "SELECT * suatabelela WHERE = ";
for ($i=0; $i < count($arrayFiltro); $i++) {
    if($i<count($arrayFiltro) {
          $sqlAND .= $arrayFiltro[$i]. "AND";
    } else {
    $sqlAND .= $arrayFiltro[$i];
    }
}


PHP_Flag and PHP_Value Command Not Found Issue

Question: We currently have a dedicated server with one company that is running apache, php, mysql etc.  It currently has whm/cpanel installed.  We are migrating to a new server with cpanel/whm.  Everything migrated over fine but now one of my sites has some php_flag and php_value lines in the .htaccess file.  When I go to the site on this new server I am getting 500 errors that read Invalid command 'php_flag', perhaps misspelled or defined by a module not included in the server configuration.
I am not sure what I need to do to get these to work so any help would be greatly appreciated.
Answer: Putting php_flag etc in .htaccess is only possible when you are using mod_php.  With CGI/FCGI, Apache settings cannot be used to configure PHP since it is not running within Apache.
Using CGI, if you need a site with a custom php.ini, the exact details would depend on how exactly you're running the PHP (CGI, mod_fastcgi (with or without php-fpm), mod_fcgid).  For basic CGI you will need to create an alternate Action for php files in that site that executes a wrapper script containing something like /usr/bin/php5-cgi -c /some/alternate/php.ini


Find the area of the part of the plane $x+y+z=a$ limited by the cylinder $x^2+y^2=b^2$

Question:
Find the area of the part of the plane $x+y+z=a$ limited by the cylinder $x^2+y^2=b^2$

I'm having issues on how to parametrise the surface, I've tried with $\vec{r}(b,\theta)=(b\cos\theta,b\sin\theta, a-b^2)$ since it "fits" both equations perfectly, but I don't get to the right answer so I'm doubtious about that part. After parametrising it should be easy as I know the surface is $$S=\iint_S ||\vec{N}(b,\theta)||dbd\theta$$ being $\vec{N}=\frac{d\vec{r}}{db}\times \frac{d\vec{r}}{d\theta}$. So what I'm really having troube is parametrising the surface.
Comment: What is the answer that you are looking for and what do you obtain?
Comment: You parametrization is not correct $z \neq a - b^2$
Comment: @TeM what confuses me about that parametrization is that after substituting $x=u\cos v, y=u\sin v$ in $x^2+y^2=b^2$ the equation isn't "true" since you get $u^2=b^2$, like I'd imagine that after substituting, I'd always get $b^2=b^2$. But I imagine that using $\mathbf{r}(b,v)=\dots$ isn't really valid since $b$ is a constant unlike $u$
Comment: Can't you use the formula $\int\int_D \sqrt{1+f_{x}^2+f_{y}^2}dxdy$?
Answer: Since the surface has support:
$$
\color{red}{\Sigma} := \left\{(x,y,z) \in \mathbb{R}^3 : x+y+z=a, \; x^2+y^2 \le b^2\right\}
$$
$\quad\quad\quad\quad\quad\quad\quad\quad\quad$
then a natural parameterization is the following:
$$
\mathbf{r}(u,v) = \left(u\cos v,\,u\sin v,\,a-u\cos v-u\sin v\right)
\quad \quad \text{with} \; (u,v) \in D := [0,b] \times [0,2\pi)
$$
from which, simply:
$$
||\color{red}{\Sigma}|| := \iint\limits_{\color{red}{\Sigma}} 1\,\text{d}S = \iint\limits_D ||\mathbf{r}_u(u,v) \land \mathbf{r}_v(u,v)||\,\text{d}u\,\text{d}v = \int_0^{2\pi} \text{d}v \int_0^b \sqrt{3}\,u\,\text{d}u = \boxed{\sqrt{3}\,\pi\,b^2}.
$$

Equivalently, it could have been observed that:
$$
z = f(x,y) = a-x-y
\quad \quad \Rightarrow \quad \quad
||\nabla f||^2 = (-1)^2 + (-1)^2 = \color{magenta}{2}
$$
from which:
$$
||\color{red}{\Sigma}|| := \iint\limits_{\color{red}{\Sigma}} 1\,\text{d}S = \iint\limits_{x^2+y^2 \le b^2} \sqrt{1+\color{magenta}{2}}\,\text{d}x\,\text{d}y = \sqrt{3}\iint\limits_{x^2+y^2 \le b^2} 1\,\text{d}x\,\text{d}y = \boxed{\sqrt{3}\,\pi\,b^2}.
$$
Answer: Note that the cutout of the plane by the cylinder is an ellipse with semi-minor axis $b$. To find the semi-major axis, calculate the angle $\theta$ between the normal vector of the plane $(1,1,1)$ and the $z$-axis
$$\cos\theta = \frac{(0,0,1)\cdot(1,1,1)}{\sqrt3}=\frac1{\sqrt3}$$
Thus, the semi-major axis is $\frac b{\cos\theta}=\sqrt3b$ and the area of the ellipse is $$A= \pi\cdot b\cdot \sqrt3b=\sqrt3\pi b^2$$


get information of web request in android

Question: Is it possible to obtain all the information of web requests in android without changing the program? I mean whether we can, in android, write a program and get type, time or server IP of a web request from the browser.
I am appreciated of any help.
Comment: what kind of information do you want? information about a web request your application does to a remote server?
Comment: almost, does that have security problem?
Comment: if your application makes the web request, then you are free to examine it all you want. On the other hand, if you want information about web requests from the browser, you are spying on the user.
Comment: Axarydax, thank you for your reply, I just wonder how Onavo manage to work and consider it may examine the web request from a application and access the server instead
Answer:
I mean whether we can, in android, write a program and get type, time or server IP of a web request from the browser.

Theoretically and by documentations: NO
in Practice : Yes, (but  I wont tell how). So keep in mind this when you want some security stuff
Comment: matheszabi, thank you for your reply, I just wonder how Onavo manage to work and consider it may examine the web request from a application and access the server instead
Answer: If you are trying to measure data usage (based on reference to Onavo),
you have to query the network interfaces (pdp0,rmnet0,pdp0,eth0,bnep0,tiwlan0 etc) - see class NetworkInterface, then check TrafficStats class for retrieving data from it.
Also look in this question, it deals with traffic stats.


Subdomains using apache and FileNotFound Error

Question: I am trying to setup subdomains using apache VirtualHosts. What I got so far is:
<code>NameVirtualHost *:80

<VirtualHost *:80>
    ServerName  www.domain.aa
    DocumentRoot    /var/www/html
</VirtualHost>

<VirtualHost *:80>
    ServerName  wiki.domain.aa
    DocumentRoot    /var/www/html/wiki
</VirtualHost>
</code>
This config works quite well, the subdomain shows up when typing wiki.domain.aa in the browser. Yet, only the first page shows up. Whenever the browser tries to load an url backed by the subdomain (for exmaple wiki.domain.aa/style.css) I get a file not found error ...
Has anyone got an idea what this is about?
Thank you very much in advance.
Matthias
Answer: Depends on the wiki software you are using. Most wikis require additional configuration like mod_rewrite to function. You need to supply more of the configuration & what tools you are using.
Comment: +1 Check .htaccess for possible URL rewriting rules. Otherwise, what is given above looks OK, providing there is a file located at `/var/www/html/wiki/style.css` (and the URL is not being rewritten).


In Html5 we can use "div" inside the "section" tag?

Question: Can one use div inside the section block like below?

Text

Comment: Yes you can use a `div` inside a `section`.
Comment: we use section when we want separate elements (this same category or similar). First tag inside section should be header (h). Example: one page in newspaper is a section, article is article and on a top this side we have header. More information you can find on this webpage http://html5doctor.com/the-section-element/ If you want have semantic website you can use other element - better.
Comment: Is it fine to use div as a wrapper for section content? I want to style everything inside. Then header would be also inside the div, not as a section first element
Answer: Yes you can use a div inside a section.
if you want know much more about div and section difference then you can refer below link.
explanation of div and section
i hop it will helpful to you.
Answer: yes of course
check div element can be nested inside the next HTML elements:
for any doubts check out the place in page section of each element; the list of nested elements is provided there
Comment: Those links are now dead


Transfering the form data to more than one page using php

Question: I have created one textfield and one dropdownlist and a button in my "index.php" page as follows:
    <form value="indexform" action="" method="post">
    Number:<input type="text" name="number"/>

    Network:
    <select name="network">
    <option selected="">please...</option>
    <option value="1">Bsnl</option>
    <option value="2">Idea</option>
    </select>
    <input type="submit" name="proceed" value="submit">
    </form>

and i have used the php code as follows for the above form:
    <?php
    if(isset($_POST['network']) && isset($_POST['number']))
    {
    $number = $_POST['number'];
    $network = $_POST['network'];
    }
    if(!empty($_POST['network']))
    {
    switch($network)
    {
    case "1":header("Location:Bsnl.php");break;
    case "2":header("Location:Idea.php");break;
    default:exit();
    }
    ?>

and i have crated two pages "Bsnl.php" and "Idea.php" Based on the selection taken in the dropdownlist the page will be redirected into either Bsnl/Idea.php
I have created the Bsnl/Idea.php page containg one textfield and submit button the code is as follows:
    <form value="Bsnlform action="default.php" method="post">
    Amount:<input type="text" name="amount"/>

    <input type="submit" value="submit">
    </form>

php code is as follows:
    <?php
    if(!empty($_POST['amount']))
    {
    $amount = $_POST['amount'];
    }
    ?>

atlast i want to print the entire form details(indexform as well as Bsnl/idea form) on the default.php page can any one help me how to do to print the values on default.php upto now i have tried the php code as follows:
    <?php
    echo $amount;
    echo $network;
    echo $number;
    ?>

Answer: First off, you need to enable session_start();
and change to this like so....
    <?php
    //Enable session first
    session_start();

    //Flush any existing session variables, you can choose where/if you wanna do this
    session_unset();

    if(isset($_POST['network']) && isset($_POST['number']))
    {
    $_SESSION['number'] = $_POST['number'];
    $_SESSION['network'] = $_POST['network'];
    }
    if(!empty($_POST['network']))
    {
    switch($_SESSION['network'])
    {
    case "1":header("Location:Bsnl.php");break;
    case "2":header("Location:Idea.php");break;
    default:exit();
    }
    ?>

Then change this to this....
<?php
//Session enable again
session_start();

if(!empty($_POST['amount']))
{
$_SESSION['amount'] = $_POST['amount'];
}
?>

Then in your next file....
<?php
session_start();

echo $_SESSION['amount'];
echo $_SESSION['network'];
echo $_SESSION['number'];
?>

Of course on your other page you wont echo $_SESSION['amount'], because it wont be set yet...
Comment: not working for the above given code!!!   because in index.php page the form containg action attribute is filled with bsnl.php any changes i want to do
Comment: Im not sure I understand what you mean??  as you have it now the first form really goes nowhere, I assumed that was just a typo on your part, but you have action=""...anyway.....whats the problem?
Comment: the data which i have entered into the fields was not transferring into third page
Comment: Ok in my example above, I have 3 blocks, Im assuming the second block in the middle is the 'processor' for after you hit submit on either Bsn1.php and Idea.php?  No?  It should be working unless you weren't clear on your files....


Block p2p downloading in my office?

Question: Well, I'm not sure how ethical this is, but I already posted this question to superuser and a poster suggested I move it over here. Very sorry if I'm breaking anybody's heart.
Anyway, here's the question:
I work in an education office in a third world country. We pay for internet by the megabyte (no other choice) and have lately been using an incredible amount of bandwidth. This is because the office staff have found out about p2p sharing. As far as I know, Limewire is the only program they're using, but I'm sure it's just a matter of time before they discover the more general world of bittorrent.
Using only a linksys router (that I could flash), is there any way for me prevent the office from destroying our bandwidth cap by downloading personal items (against policy).
Even semi-fixes would be better than nothing.
A few notes that became relevant after getting some answers on superuser:
1) I don't have access to everyone's computer.
2) Welcome to bureaucracy! Nobody can be fired. Realistic threats can't be made. This goes much deeper than stopping p2p, but hey. What can you do? Also, nobody has internet at home (expensive!) so they're fairly bloodthirsty.
3) Any solution has to be more-or-less automated. In about 8 months, I will leave and the office will still want to stop downloads.
4) One solution that seemed really appealing (on the suggestion of user skuzzy-delta) was using Tomato firmware to severly de-prioritize downloads. Unfortunately, my linksys wrt54g is too new for the firmware... but could pfsense or ddwrt do something similar? Would this be a good tactic?
For what it's worth, here's the link to my question on superuser: https://superuser.com/questions/66027/block-p2p-downloading-in-my-office
UPDATE:
1) Can't buy anything. That means I cannot set up a dedicated server.
2) My linksys is wrt54g cdfe.... v7... can't run ddwrt :-(
Answer: First, I don't think you are going to be able to do a good job of this on a broadband router.  You probably need to look at setting up a Linux box to act as a proxy firewall router.  Plus, if you do this on a computer you can run a cache which will save you bandwidth since pages visited by many users will only need to be downloaded once.
Blocking P2P tends to get very difficult.  Most protocols these days tend to be very good at getting around the firewall.

Setup a firewall that by default denies any outgoing requests.  Yes, this is very harsh, but if you really want block things this is a cheap way to start

you will need to probably explicitly add rules for any servers that are hosted within your network.

Setup an HTTP proxy (e.g. squid), and all the browsers to use the proxy server.
Subscribe to a blacklist (e.g. 1, 2) service and make sure you prohibit any proxies.
Setup something like srg or sarg to produce reports per user/computer about who is visiting what, and how much bandwidth they are using.  Give the administration the ability to view this information.
Use the controls inside your proxy server to throttle computers (squid delay_pools)
Setup a procedure for trusted users to get around the default deny firewall policy.  (But still keep logs)

I know the above is very heavy-handed, but it will block almost all P2P traffic, and isn't particularly difficult to implement.
Please see these related questions:

Using Linux IPTables, How to block torrents or any P2P protocols?
block Torrent through firewall
How can I block LimeWire on my corporate network?
Comment: this is a very comprehensive solution. I would really recommend finding a computer to use. a Linux server doesnt require very much power, any CPU and 256MB of RAM should do. you can probably salvage something like that out of the garbage.
Answer: I would recommend OpenDNS.  You can prevent people from bypassing OpenDNS by blocking TCP and UDP requests on port 53.
We use it here and it's very good at stopping P2P, social networking and other "Forbidden" sites.
As a plus, it won't require any changes to your router's firmware.
Comment: +1 for OpenDNS. Great for this stuff. I should've mentioned it on my response as well.
Answer: DD-WRT will work on newer versions of Linksys routers that Tomato doesn't support.  A quick search of the DD-WRT router database will tell you if your router is compatible or not.  There is an option on the access restrictions page of DD-WRT to block known p2p protocols, it's as simple as clicking a check box.
Answer: If you can get your hands on an older PC with two network cards I'd suggest a look at Untangle. I've found it to work great for issues like yours.
If you can't get a PC to use but have a windows machine on the network you could look at Untangle for Windows. I've never tried it but it seems like it could work for you.
Comment: also, in addition to Untangle, there are other options like Smoothwall and IPCop .
Answer: I think the stock firmware should have enough port blocking protection to only allow the needed ports.
Answer: This is a challenge...
It's really a shame you cannot use Tomato as it already has ipp2p iptables module nicely integrated.
My suggestions:

(if you can get a computer with 2 network cards) setup a Linux (or Windows as some people already suggested) box with iptables and ipp2p module to deprioritize or block P2P traffic completely;
talk to your internet provider - maybe they can help you block P2P traffic;
Use wireshark to monitor P2P connections and send RST packets to router/computer :)
Answer: As bizarre as it sounds, you probably won't want to block it, you want to give it a severely restricted bandwidth. Most P2P apps are pretty clever at avoiding blocks, so if all you do is slap a block on the standard ports, it'll poke around until it finds unblocked ports and use those.
But providing a suitablu narrow channel (32 kbps, 64 kbps, whatever), the evasion mechanisms do not kick in while still restricting the damage P2P downloading can do.
Answer: This might be a bit overkill, but you could put a Squid proxy in front of your router.  Then configure a white list of allowed protocols - Http, Https, SSL etc..  A side affect is you may be able to reduce some of your bandwidth by having the Squid serve up cached content.
The most restrictive is to place a non-transparent internet proxy in front of your users.  This requires them to point their browsers to your internal proxy server.  The advantage of this is most authenticated proxy servers happily report usage by user and the top sites they visit.  Just posting the names of the people who use the most internet may be enough to police people from downloading things against policy.
Answer: Can you try somehow and justify the cost of buying a small amount of cheap hardware to fix this problem properly, considering there will then be a considerable saving in bandwidth costs?
And those bandwidth cost savings will be continual per month/year, with only a one-off hardware cost.

Block p2p downloading in my office?


Handling mobile images in responsive theme

Question: Sorry for the open-handed nature of the question, but I don't know where else to get an answer to this. I'm deciding whether or not go full-force into a responsive Drupal 7 theme, probably the Omega framework.
One issue that keeps nagging at me is that the mobile devices have to download all the large images (not to mention everything else...).
Is there an easy way to serve up smaller images for mobile devices?
Answer: There are many modules to handle responsive images, including;

Responsive Images
Client-side adaptive image
Adaptive Image Styles (ais)
Adaptive Image
Borealis
Comment: Great, I'll try some of these out!
Comment: The one that I got working properly, with support for Reverse Proxys was Client-Side Adaptive Image. Thanks!
Answer: Use different imagecache presets immediately comes to mind, eg, a set of them for the main, desktop theme, and another parallel set that creates smaller versions for the mobile theme, or if in the same theme, sets that toggle based upon the user agent of the user's browser.
Comment: Interesting. What is the best way to call the preset on each theme? Like, large for desktop, and thumbnail for mobile?
Comment: Off the cuff I was thinking inside the node templates, before displaying/rendering an image, check the user agent, and if mobile, display them one way, otherwise, display them another.  Probably lots of work, but also precise.
Answer: I had been searching for a proper way to get adaptive images. Finally Client-Side Adaptive Image worked. You just have to make a few image styles. Then if you select image formatter as adaptive image then you can assign an image style for every breakpoint. You can even configure the no. of break points you want. Great module! Great Solution!


Creating music on specific key

Question: I want to know that in most DAWs we have tendency to make everything to create every note on C5 as DAWs like FL Studio create everything on C unless you change it manually or create it in piano roll.
Suppose i create a melody on D Scale now, should all instruments be created within the scale even if they sound ok ok Default C?
Comment: I don't think any of the DAWs I've used have any overall concept of the key the piece is in, or have any tendency to only create things in a certain key. Are you asking about Fruity Loops specifically?
Comment: Not specifically Fruity loops, let's suppose, i am creating a melody which is in a scale that doesn't have C in it. Now for the rest of instruments, including bassline, should i create them within the scale (not on C) even if they sound ok on C.
Answer: FL Studio does not force you to use C scale. If you look at the piano roll you have full chromatic keyboard with all the notes. C notes are marked just for convenience as in the music C is usually used as point to which everything else relates. (BTW in piano roll menu in the top left corner there's useful Stamp tool that makes using scales much easier and you can start from any note).
It's hard to answer your question for 100% because it's very broad. I don't know what instruments/synths/samples you are using. Especially with samples the piano roll can be a bit confusing - for example you can use recorded sample of the G4 sound on the piano, but when the sample is loaded it is as default treated as C5 note. So, when you put D5 on piano roll it will be really the A4 sound on the piano.
Synths also have the possibility to be detuned (in EDM music detuning by less than semitone is often used to create "fat" sounds), so you cannot assume that playing note within the same scale on different intruments will sound well when played together.
Treat theory and scales as tool, not as the strict GO/NO GO rules, if something sounds OK for you then go for it.
Comment: Now this is what i was looking for. Thanks for explanation my answer was in last 3 sentences of your answer.

Creating music on specific key


css class names meaning in react-big-calendar [using it with Selenium]

Question: I'm using selenium in javascript over a page that has the react-big-calendar plugin;
since I'm trying to do several selects and choosing the right day (today, the day current selected, the month current displaying, etc.) I'm trying to figure out some css-classes meaning:

the rbc-now class i thought it was the current day but it's not, since if i select an appointment this class has been applied to it too;
the rbc-current class is applied to ALL the day numbers like today, e.g. if today is the 18th day of the month, all the 18th of jan.,feb.,mar.,... have this class applied (is it right?)
the rbc-today class which I couldn't figure out what is.

I tried to search also in reactiflux discord like suggested in the last row of the above link but with no clue.
Does anyone knows what exactly indicates those classes?
Answer: Ok, i think I've managed it. I'll take as example the monthly view.

rbc-today: is the class used for the big div that corresponds to the first nearest appointment happening from today: this class gives the pale blue color to the day. It is assigned to a div that already has rbc-day-bg class:

            [...]

    <---HERE

This div block represents the entire day.

rbc-now: this class put bold to the day number of the month (e.g. 28). Indicates the number of the month of the first nearest appointment happening from today. It is assigned to divs that already have an rbc-date-cell class and they are in the first rbc-row class under rbc-row-content:

            [...]

                    26

                    27

    <---HERE
                    28

rbc-current: gives no style, acts exactly as rbc-now, but is assigned to every single number of the day of the month which is equal to the day of the month of the appointment, from that day onwards:
e.g. if you put an appointment to march,28,2021, rbc-current will be applied to 28 of april, 28th may, 28th june...etc, but also 28 of jan 2022, 28 feb 2022...etc.

            [...]

                    26

                    27

    <---HERE
                    28

Hope this will be useful for future reference.