How to check if a point is inside a rectangle?

Question: There is a point $(x,y)$, and a rectangle $a(x_1,y_1),b(x_2,y_2),c(x_3,y_3),d(x_4,y_4)$, how can one check if the point inside the rectangle?
Comment: Similar to http://stackoverflow.com/questions/2752725/finding-whether-a-point-lies-inside-a-rectangle-or-not
Comment: I have just read some of the answers and created some images and Python code for it: http://martin-thoma.com/how-to-check-if-a-point-is-inside-a-rectangle/
Comment: sorry, I can't find proper tags for this question, please help me to improve it
Answer: $M$ of coordinates $(x,y)$ is inside the rectangle iff
$$(0<\textbf{AM}\cdot \textbf{AB}<\textbf{AB}\cdot \textbf{AB}) \land (0<\textbf{AM}\cdot \textbf{AD}<\textbf{AD}\cdot \textbf{AD})$$
(scalar products of vectors, $\land$ stands for logical AND).
Comment: Far more efficient than any of the triangle methods.  Why aren't these getting more votes?
Comment: Needs more explanation in the answer (not comments). Took me a while to decipher this.
Comment: Shortly yes @bgoers. We impose the perpendicular projection of $\textbf{M}$ on $\textbf{AB}\;$ to be between $\textbf{A}$ and $\textbf{B}$ and the perpendicular projection of $\textbf{M}$ on $\textbf{AD}\;$ to be between $\textbf{A}$ and $\textbf{D}$. The result will follow from the condition that $\textbf{AB}\;$ and $\textbf{AD}\;$ are perpendicular. This condition is thus required for this method to work as well as accurate positions (floating points values instead of nearest integers) for the positions. Fine continuation,
Comment: @Erick: Probably because I added it late (and I don't know why this straightforward method was not proposed earlier here...)
Comment: @SuperUberDuper: well this is a mathematical answer and was the shortest I could think at but I didn't implement it. Perhaps that this linked [SO thread](http://stackoverflow.com/questions/2752725/finding-whether-a-point-lies-inside-a-rectangle-or-not) will help you more (I noticed that the same method appeared there with some code...).
Comment: Thanks. I wrote it up in javascript here: http://stackoverflow.com/a/37865332/276093
Comment: (instead of my $(0<\textbf{AM}\cdot \textbf{AB}<\textbf{AB}\cdot \textbf{AB})\:$ Jonas Elfström used the equivalent $\;(0<\textbf{AM}\cdot \textbf{AB})$ and $(\textbf{BM}\cdot \textbf{AB}<0)$. they are the same since $[\textbf{AM}\cdot \textbf{AB}-\textbf{AB}\cdot \textbf{AB}=(\textbf{AM}-\textbf{AB})\cdot \textbf{AB}]<0$)
Comment: @user599310: yes and note that for a (perfect) cuboid the $3$ normal vectors are simply the $3$ orthogonal vectors (cuboid edges) starting from a corner!
Comment: Thanks @user1783444 ! I tried to provide something mathematically simple (other solutions may be better in practice...).
Comment: I'm not great with math - does this hold true for any rectangle orientation, with any order of rectangle vertices so long as they are clockwise/counterclockwise (my intuition says yes, but I'd like to know for sure)?
Comment: I'm confused by all the answers, is this the best way to do it in JavaScript?
Comment: Glad the link helped @matt burns. Thanks for your answer and excellent continuation!
Comment: @RaymondManzoni Sorry I am not good at solving maths but the answer you referred to in the comment on Dec 29,2015 and the one @matt burns wrote use both `AM` and `BM` but your answer only uses`AM`. But do they yield the same result? And are these the same method? I am so confused.
Comment: @newguy: Well if $\,\textbf{AB}\;$ and $\,\textbf{DC}\;$ are parallel as well as $\,\textbf{AD}\;$ and $\,\textbf{BC}\;$ then the results should be the same (remember that this is a mathematical answer!). From my comment dated jun 10 '15 they simply chose to project $\,\textbf{M}\,$ on the other side of the rectangle (on $\,\textbf{BC}\;$ instead of $\,\textbf{AD}\,$) so that the methods are nearly the same with only some small differences for a not perfect rectangle. Note that Jonas Elfström's (possibly quicker) answer corresponds to mine. Cheers,
Comment: @RaymondManzoni Thanks for clearing this up.Your answer and other comments under this answer help me big time.
Comment: @RaymondManzoni shouldn't this bet greater than or equals?
Comment: @PentaKon: I considered $(x,y)$ *inside* the rectangle and so the (strict for english speaking people...) inequalities but you may of course adapt the tests to your specific needs.
Comment: @RaymondManzoni And this of course generalizes to 3D, correctt? In this case, instead of projecting on sides, we should project on vectors normal to the faces right?
Answer: Let $P(x,y)$, and rectangle $A(x_1,y_1),B(x_2,y_2),C(x_3,y_3),D(x_4,y_4)$
Calculate the sum of areas of $\triangle APD, \triangle DPC, \triangle CPB, \triangle PBA$.

If this sum is greater than the area of the rectangle,  then $P(x,y)$ is outside  the rectangle.
Else if this sum is equal to the area of the rectangle (observe that this sum cannot be less than the latter),

if area of any of the triangles is $0$, then  $P(x,y)$ is on the rectangle (in fact on that line corresponding to the triangle of area$=0$). Observe that the equality of the sum is necessary; it is not sufficient that area$=0$),
else $P(x,y)$ is is inside the rectangle.

Acceptably this approach needs substantial amount of computation. This approach can be employed to any irregular polygon, too.

Another  way is to calculate the perpendicular distances of $P(x,y)$ from all the 4 lines $AB,CD, AD,BC$
To be inside the rectangle,
   the perpendicular distances from  $AB, P_{AB}$(say) and from $CD, P_{CD}$(say) must be less than $|AD|=|BC|$  and the perpendicular distances from  $AD, P_{AD}$(say) and from $BC, P_{BC}$(say) must be less than $|CD|=|AB|$.
   Here , the areas of each of the four triangles < $\frac{1}{2}$the area of the rectangle.

If one of  the perpendicular distances is greater than the respective length, then $P(x,y)$ is outside  the rectangle.
This essentially implies and is implied by the statement : the area of the respective triangle > $\frac{1}{2}$the area of the rectangle (as commented by Ben Voigt) as $\triangle APD=\frac{1}{2}AD\cdot P_{AD}$.
Else if $ P_{AB}=0$ and $P_{CD}=|AD|$ , then  $P(x,y)$ is on AB . So, $\triangle PBA=0$ and $\triangle PCD=\frac{1}{2}$the area of the rectangle.
Observe that in this case, the remaining two perpendicular distances $P_{AD}, P_{BC}$ must be ≤ $|AB|=|CD|$, $P_{BC}=|AB|\implies P(x,y)$ is lies on AD i.e, P coincides with A as it is already on AB .
Comment: Wouldn't it be simpler, potentially fewer computations, and equally correct to test if the area of any triangle is greater than half the area of the rectangle?
Comment: -1  I know that this can be only a symbolic action. There is a
simple solution (http://math.stackexchange.com/questions/190111/how-to-check-if-a-point-is-inside-a-rectangle/190373#190373) for this simple problem. By accepting this solution and giving it so many votes a stutdent or programmer that is searching this forum for a solution of this simple problem will be pointed in the wrong direction.
Comment: Perpendicular distances involve at least one suqre root operation, which I think is avoidable.
Comment: @Hagen: The squared perpendicular distance is good enough.
Comment: @BenVoigt, who'll dare to disagree?
Comment: @lab: Areas are cross products, so you're just computing four vector products: no more, really, than any of the other answers. (except those who can get away with 2 vector products)
Comment: Also if the area of each 4 triangles are less than half of the area of the rectangle,   the point is inside. If $ \triangle APD=0$ and $2\triangle BPC=$ area of the rectangle and the area of the rest two triangle $<\frac{1}{2}$area of the rectangle,  the  point is on AD.
Comment: It was awesome to read this post if only to get why This is a correct but unusable algorithm: infinite precision comparison is required for iterated operators (sqrt) and it is costly. Use the alternative for rectangles, or search ray casting algorithms for point in polygon problems.
Comment: For a polygon this method would require triangle area per each point which may be impractical and it would theoretically require infinite precision computation to determine the case. Better
Comment: @labbhattacharjee, sorry for replying in such an old thread. I was trying to implement the approach in your post to concave polygons(not just rectangles), and it seems that this area-method only works for the convex case. Or is there any way to adjust the approach for concave polygons? Thanks!
Answer: I would use a "point-in-convex-polygon" function; this works by checking whether the point is "to the left of" each of the four lines.
Comment: Or else on the same side as the center (mean) of the polygon.
Comment: Or else same side as any of the other vertices?
Answer: For example, if all the triangles $ABP$, $BCP$, $CDP$, $DAP$ are positively oriented; for $ABP$ this can be tested by checking the sign of  $(x-x_1)\cdot(y-y_2)-(y-y_1)\cdot(x-x_2)$. This method generalizes to convex polygons.
Alternatively, find a transformation that makes the rectangle parallel to the axes. Apply the same transformation to your point at the test is simple. This is especially helpful if you want to test many points against the same rectangle.
Comment: I didn't understand what we're concluding by checking the sign of that expression, and how it relates to the point being inside the polygon. Could you please explain?
Comment: @arya_stark You can find if two points lie on the same side of a line by substituting the co-ordinates of the point in the line equation and checking their signs' agreement.
Answer: Given how much attention this post has gotten and how long ago it was asked, I'm surprised that no one here mentioned the following method.
A rectangle is the image of the unit square under an affine map. Simply apply the inverse of this affine map to the point in question, and then check if the result is in the unit square or not.
To make things clear, consider the following image,

where the vectors in the pictures are $\mathbf{u} = c - d$, $\mathbf{v} = a - d$, and $\mathbf{w} = d$.
Since the legs of a rectangle are perpendicular, the matrix $\begin{bmatrix}\mathbf{u} & \mathbf{v}\end{bmatrix}$ is orthogonal and so we even have a simple formula for the inverse:
$$\begin{bmatrix}\mathbf{u} & \mathbf{v}\end{bmatrix}^{-1} = \begin{bmatrix}\mathbf{u}^T/||u||^2 \\ \mathbf{v}^T/||v||^2\end{bmatrix}.$$
If you want to check many points for the same rectangle, this matrix can be easily precomputed and stored, so that you perform the (typically more expensive) division operations only once at the start. Then you only need to do a few multiplications, additions, and subtractions for each point you are testing.
This method also applies more generally to checking whether a point is in a parallelogram, though in the parallelogram case the matrix inverse does not take such a simple form.
Comment: Thanks Nick, came here and wanted to see this exact reply
Comment: I'm confused why isn't this post upvoted the most
Comment: @Amira I think because I posted this answer several years after the question was asked. By the way, this matrix formula, if you write it out and perform some algebraic manipulations, can be transformed into the mysterious formula in the highest upvoted answer by Raymond Manzoni.
Answer:
The point is inside the rectangle.

The point is outside the rectangle.
Let us define:
A: area of the rectangle
Ai: areas of the triangles shown in the pictures. (i = 1, 2, 3, 4)
ai: lengths of the edges shown in the pictures. (i = 1, 2, 3, 4)
bi: lengths of the line segments connecting the point and the corners. (i = 1, 2, 3, 4)
If the point is inside the rectangle, the following equation holds:
$ \mathbf{A = A_1 + A_2 + A_3 + A_4} $
If the point is outside the rectangle, the following inequality holds:
$ \mathbf{A > A_1 + A_2 + A_3 + A_4} $
How do we calculate A, A1, A2, A3, A4, a1, a2, a3, a4, b1, b2, b3 and b4?
First we calculate the edge lengths:
$
a_1 = \sqrt{(x_1 - x_2)^2 + (y_1 - y_2)^2} \\
a_2 = \sqrt{(x_2 - x_3)^2 + (y_2 - y_3)^2} \\
a_3 = \sqrt{(x_3 - x_4)^2 + (y_3 - y_4)^2} \\
a_4 = \sqrt{(x_4 - x_1)^2 + (y_4 - y_1)^2}
$
Next we calculate the lengths of the line segments:
$
b_1 = \sqrt{(x_1 - x)^2 + (y_1 - y)^2} \\
b_2 = \sqrt{(x_2 - x)^2 + (y_2 - y)^2} \\
b_3 = \sqrt{(x_3 - x)^2 + (y_3 - y)^2} \\
b_4 = \sqrt{(x_4 - x)^2 + (y_4 - y)^2}
$
Then we calculate the areas using Heron's Formula:
$
A \,\,\, = a_1a_2 = a_2a_3 = a_3a_4 = a_4a_1 \\
u_1 = \frac{a_1 + b_1 + b_2}{2} \\
u_2 = \frac{a_2 + b_2 + b_3}{2} \\
u_3 = \frac{a_3 + b_3 + b_4}{2} \\
u_4 = \frac{a_4 + b_4 + b_1}{2} \\
A_1 = \sqrt{u_1(u_1 - a_1)(u_1 - b_1)(u_1 - b_2)} \\
A_2 = \sqrt{u_2(u_2 - a_2)(u_2 - b_2)(u_2 - b_3)} \\
A_3 = \sqrt{u_3(u_3 - a_3)(u_3 - b_3)(u_3 - b_4)} \\
A_4 = \sqrt{u_4(u_4 - a_4)(u_4 - b_4)(u_4 - b_1)}
$
Finally you can do the area test to check if the point is inside or outside the rectangle.
Comment: what is A=area is smaller than the right hand side?  I am getting that now in Matlab
Comment: @mLstudent33 That is not possible. You must have done a typo in your equations.
Comment: it works now after I checked that float values are within a tolerance.
Answer: One of the simplest algorithms of coordinate plane geometry is a method of "Is the vector $\vec{w}$ clockwise or counterclockwise from the vector $\vec{v}$?"
The algorithm is to compute the cross product $\vec{v} \times \vec{w}$. If the sign is positive, then $\vec{w}$ is counter-clockwise from $\vec{v}$. If negative, it is clockwise.
This method gives an algorithm for answering the question "Which side of a line is a point on?"
e.g. consider the left line of your box, line $da$, directed from $d$ to $a$. The point $p=(x,y)$ is on the right side of this line if and only if the vector $dp$ is clockwise from $da$. So we can simply compute the cross product to learn if $p$ is on the correct side of $da$ or not.
Do this with all four lines, and you have your test.

If you're using the same four points a lot, we can get away with half as much work. We can use the dot product to compute "How long is one vector in the direction another is pointing?"
We can compute the dot product of $da$ with $dp$. If this number is greater than the dot product of $da$ with itself, then your point is too far up to be in the box. If this number is negative, the point is too far down to be in the box.
Because this checks two boundaries at once, we only have to do this twice: once with $da$ to get the up-down location, and once with $dc$ to get the left-right location.

EDIT: One of the general ideas at play is to try and make as much use of the dot product and cross product as you can, as they are computationally efficient ways of computing geometric information related to things like length, angle, and area.
So a common strategy for a problem of computational geometry is to try and phrase the problem in terms of things that can be answered with dot and cross products. If that's not immediately obvious, phrase it in terms of (directed) lengths, angles, and areas, and try to rephrase those in terms of dot and cross products.
My approach to the question was to express "which side of a line?" as a directed angle, allowing use of cross product.
Also, I used the dot product to compute distance along a direction parallel to one of the sides of the rectangle. You could compute the same thing as "perpendicular distance" from an adjacent side, which would let you use the cross product.
Some of the other answers express things in terms of the areas of triangles -- these are naturally computed cross products. One answer summed their magnitudes and compared with the area of the rectangle. Another looked at the direction of the areas instead (i.e. whether the triangles were positively oriented).
Answer: You can use complex analysis to check (which is really overkill and probably not computationally efficient but still neat and generalizes to all polygons without any difficulty). Specifically, identify the point $(a,b)$ with the complex number $a+bi$. Let $\gamma$ parametrize the rectangle by going around once counterclockwise. By Cauchy integral formula we know that
$\displaystyle \frac{1}{2 \pi i}\int_\gamma \frac{1}{z-x-iy}dz = \left\{
     \begin{array}{lr}
       1 \mbox{ if (x,y) is in the rectangle} \\
       0 \mbox{ if (x,y) is outside the rectangle}
     \end{array}
   \right.$
and is not defined if (x,y) is on any of the four boundary segments.
The integral is over 4 strait line segments. On the strait line segment from $(x_2,y_2)$ to $(x_1,y_1)$, the integral is just
$\displaystyle \int_0^1 \frac{x_1-x_2+i(y_1-y_2)}{t(x_1-x_2+i(y_1-y_2))+x_2-x+i(y_2-y)} dt = \int_0^1 \frac{1}{t-w_1}$
where $w_1= \frac{x_2-x+i(y_2-y)}{x_2-x_1+i(y_2-y_1)}$. This integral can be done so long as $w_1 \not \in [0,1]$, which corresponds to (x,y) on the segment. The result is $\log(1-w_1)-\log(-w_1)$. Note that this is a holomorphic function of $w_1$ on $\mathbb{C} - [0,1]$, where we have adopted the branch cut for $\log$ as $\log(r e^i \theta)= \ln(r) + i \theta$ for $\theta \in (-\pi, \pi]$.
Summing over the four edges gives the left hand side above as $\frac{1}{2 \pi i}\displaystyle \sum_{j=1}^4 \log(1-w_j)- \log(w_j)$ where $w_2,w_3$, and $w_4$ are defined analogously to $w_1$. You only need compute this sum to sufficient precision to rule out it equaling either 0 or 1. As I said before this isn't usually a good way in practice, partially because logs are pretty computationally expensive, but it is a way to do this.
Comment: If you take the exponential of the sum, you get a product that can be evaluated without logs, it isn't *too* bad.
Answer: How can there be no vector math solutions to this yet?
Let $(x',y')=(x-x_1,y-y_1)$ so that the point $(x_1,y_1)$ is the origin..  Then get the height and width of the rectangle

$w = \sqrt{(x_2-x_1)^2 + (y_2-y_1)^2}$
$h = \sqrt{(x_4-x_1)^2 + (y_4-y_1)^2}$

And then see whether $(x',y')$ is within that rectangle

$0 \leq x'{(x_2-x_1) \over w} + y'{(y_2-y_1) \over h} \leq w$
$0 \leq x'{(x_4-x_1) \over w} + y'{(y_4-y_1) \over h} \leq h$

Done!  Way easier than the triangle methods--those are for generic convex polygons and are awesome if you have a convex polygon, but are overkill for a rectangle.
(It's even shorter to use the vector forms.  If your coordinates are $\vec{p},\dots,\vec{p_4}$ then subtract $\vec{p_1}$ from everyone to get $\vec{p'}, \vec{p_2'}, \vec{p_4'}$.  Then you're in the rectangle iff $0 \leq \vec{p'}\cdot\hat{p_2'} \leq p_2'$ and $0 \leq \vec{p'}\cdot\hat{p_4'} \leq p_4'$.)
Answer: It is very easy.
Just divide Rectangle in 2 triangle
i.e.
1) a(x1,y1),b(x2,y2),c(x3,y3)
2) a(x1,y1),d(x4,y4),c(x3,y3)

Then, point is in Rectangle, if and only if point is in at least 1
  triangle.

Following is code for checking point in triangle :
float sign(fPoint p1, fPoint p2, fPoint p3)
{
  return (p1.x - p3.x) * (p2.y - p3.y) - (p2.x - p3.x) * (p1.y - p3.y);
}

bool PointInTriangle(fPoint pt, fPoint v1, fPoint v2, fPoint v3)
{
  bool b1, b2, b3;

  b1 = sign(pt, v1, v2) < 0.0f;
  b2 = sign(pt, v2, v3) < 0.0f;
  b3 = sign(pt, v3, v1) < 0.0f;

  return ((b1 == b2) && (b2 == b3));
}

Answer: For me, the basic tool to use answers the question "are two points on the same side of a line?"
If the equation of the line is $ax+by+c = 0$
and the points are $(x_i, y_i)$ for $i = 1, 2$,
compute $d_i = a x_i + b y_i + c$ for each $i$.
If the two $d_i$ have the same sign
(both $> 0$ or $< 0$ to avoid problems about being on the line), they are
on the same side of the line.
We now use this. Compute the point that is the average of the
four vertices. We know that this is inside the rectangle - this will work for a triangle also, where this problem more commonly occurs.
For each line making up the rectangle,
do the "two points on the same side of a line" test
using the average point and your test point.
If the average point and your test are on the same side
for each line (though they may be on different sides for different lines),
the point is inside the rectangle.
Doing it this way, there are no worries about orientation or
traversing the vertices of the rectangle in a certain order.
Comment: Instead of the average of the vertices why cant we just use any of the other vertices?
Comment: This guarantees that the point is inside.
Answer: Consider the rectangle as defining a coordinate system with origin $A$ and basis vectors $v_1 = B-A$ and $v_2 = D-A$. We can find the point $p = (x,y)$ in terms of this coordinate system as $\left(\frac{(p - A)·v_1}{v_1·v_1}, \frac{(p - A)·v_2}{v_2·v_2}\right)$. The coordinates of this transformed point are within the range 0 to 1 if and only if the point is within the rectangle.
This is equivalent to Raymond Manzoni's answer, but I thought it worth deriving in this fashion.
Answer: This is intutition at work, but what if you found the distances from the vertices to the point and added them all up?
Your min would be the distances to the center of the rectangle and your max is the distances if your point was on one of the vertices.
For example, for a 3x4 triangle, you min would be 10 (two times your diagonal) and your max would be 12 (if your point was on a vertex). This is your range: the point is inside the rectangle, if your distances from the vertices to the point are within the range 10 to 12 (for a 3x4 rectangle).
Answer: I had this observation and it may be useful (but may be wrong too, as I have not proved it formally, so this text is proposed as a comment rather than a formal answer).
A rectangle can be divided into four inner rectangles with no gaps and as a result, there would be $1$ point that is common to all resulting 4 inner rectangles. Let that point be $p1$ in the picture below.
$p1$, has the following property: We could draw 2 lines intersecting at $p1$ such that each of the lines going through p1 is perpendicular on 1 of the rectangle sides. For example, Line $DC$ is perpendicular on line segment $v1v2$ and Line $AB$ is perpendicular on line segment $v4v1$.
The above property of $p1$ can't be satisfied by any point outside the rectangle.
Now, given a point $p1$, and 4 points that represent the rectangle corners, we may apply the above property to determine if p1 lies within the rectangle or not.
Answer: Check if your point is inside triangle a,b,c or inside triangle a,c,d. There are several methods for doing this. See e.g. http://www.blackpawn.com/texts/pointinpoly/default.html or https://stackoverflow.com/questions/2049582/how-to-determine-a-point-in-a-triangle
Answer: My first thought was to divide rectangle to two triangles and apply some optimized method twice. It seemed to be more effective than @lab bhattacharjee's answer to me.
http://www.blackpawn.com/texts/pointinpoly/default.html
Answer: Rotate the rectangle 4 boundary points and detection point so that the bottom left corner of the rectangle becomes the origin. Change the coordinates of the point relative to the bottom left of the rectangle. Do simple boundary check for x and y axes. Done.
Answer: First of all, we have to choose 2 adjacent sides of the rectangle and then form the equations that contains them. The second step is to create 2 equations that contains the 2 slopes of the equations of the 2 adjacent sides and the critical point. Now we'll equate the equation that contains a side of a rectangle with slope m to one equation that contains the critical point and the slope -1/m, and then will equate the left equations. We'll also take into account that each solution has to respect the inequalities that can be easily deduced by checking the coordinates of the 2 adjacent sides. If we get 2 intersection points that respect the inequalities, then the critical point is inside the rectangle.
Q.E.D.
Answer: You could use a different coordinate system, and reduce the problem to the case when one of the rectangle's legs is on the x axis and the others parallel to the y. In this case, you just see if the x and y inequalities for the rectangle are satisfied by your point. By a change of coordinate system, I mean simply choosing one of the vertices of the rectangle to be the origin, and using two perpendicular unit vectors for each of the adjacent sides (to the corner). Then, since you know the length of the sides of the rectangle, you can easily deduce the necessary rectangle inequalities.
NB by rectangle inequalities I mean the necessary and sufficient inequalities that must be satisfied in order for a point to lie in a rectangle in the first case.
Answer: Calculate $\perp$ distances of point $P$ from all sides of rectangle and check if any of the distances of point from opposite sides is greater than the distance between them (one of the side length of rectangle). If it is greater than it is outside otherwise inside.
Answer: let pi, xi, yi be the coordinate of p, x and y in the ith dimension
for i=1 to n
    if polarity(pi-xi, pi-yi) != -1 return false;
return true;

bool polarity(z){
    // z == 0 needs to be filtered out
    if (z > 0) return 1;
    if (z < 0) return -1;
}

bool polarity(px, py) {
    if (px == py) return -1;    // only happens when x = p = y
    if (px == 0) return -1;
    if (py == 0) return -1;
    return polarity(px) * polarity(py);
}

Possible to replace multiplication with bool function.
Comment: You're assuming we have a specific rectangle. The OP seems to be asking about the general question where we don't know the values of $x_1, y_1,$ etc.
Comment: If you can figure out the sequence of triangles APD,...., it would be even simpler to determine the diagonals.  Also, you can try all combinations of corners and if you get a single combination correct, you've solved it.
Answer: Let $(1,2,3,4)$ be the numbering of vertices in common Cartesian coordinates $(x,y)$.
For a triangle we define local (so-called isoparametric) coordinates $(\xi,\eta)$ as:
$$
\Delta = (x_2-x_1)(y_3-y_1)-(x_3-x_1)(y_2-y_1) \\
\xi  = [(y_3-y_1)(x-x_1)-(x_3-x_1)(y-y_1)]/\Delta \\
\eta = [(x_2-x_1)(y-y_1)-(y_2-y_1)(x-x_1)]/\Delta
$$
And the Inside-Outside function as:
$$
\operatorname{IO}(x,y) = \min(\xi,\eta,1-\xi-\eta)
$$
Then we have that a pont $(x,y)$ is inside the triangle if $\,\operatorname{IO}(x,y)\gt 0\,$,
it is outside the triangle if $\,\operatorname{IO}(x,y)\lt 0\,$ and it is on the boundary if
$\,\operatorname{IO}(x,y) = 0\,$.
More information and a useful application is found at:

2-D and 3-D Point Probes

From the following reference we have the details below.

Quadrilateral Interpolation

Analogously to a triangle we have for the quadrilateral, in local / isoparametric coordinates $(\xi,\eta)$:
$$
N_1(\xi,\eta) = \frac{1}{4}(1-\xi)(1-\eta) = \frac{1}{4}(1-\xi-\eta+\xi\eta)\\
N_2(\xi,\eta) = \frac{1}{4}(1+\xi)(1-\eta) = \frac{1}{4}(1+\xi-\eta-\xi\eta)\\
N_3(\xi,\eta) = \frac{1}{4}(1-\xi)(1+\eta) = \frac{1}{4}(1-\xi+\eta-\xi\eta)\\
N_4(\xi,\eta) = \frac{1}{4}(1+\xi)(1+\eta) = \frac{1}{4}(1+\xi+\eta+\xi\eta)
$$
The global (common Cartesian) coordinates $(x,y)$ are calculated herefrom:
$$
\begin{cases}
x = N_1(\xi,\eta)x_1 + N_2(\xi,\eta)x_2 + N_3(\xi,\eta)x_3 + N_4(\xi,\eta)x_4 \\
y = N_1(\xi,\eta)y_1 + N_2(\xi,\eta)y_2 + N_3(\xi,\eta)y_3 + N_4(\xi,\eta)y_4
\end{cases}
$$
It is trivial that the vertices are given by:
$$
(\xi,\eta)=(-1,-1) \;\rightarrow\; (x,y)=(x_1,y_1) \\
(\xi,\eta)=(+1,-1) \;\rightarrow\; (x,y)=(x_2,y_2) \\
(\xi,\eta)=(-1,+1) \;\rightarrow\; (x,y)=(x_3,y_3) \\
(\xi,\eta)=(+1,+1) \;\rightarrow\; (x,y)=(x_4,y_4)
$$
Using abbreviations $(A,B,C,D)$ may be helpful.
$$
\begin{cases}
x = A_x + B_x\xi + C_x\eta + D_x\xi\eta \\
y = A_y + B_y\xi + C_y\eta + D_y\xi\eta
\end{cases}
$$
It's easy to see that the constants are given by:
$$
A_x = \frac{1}{4}(+x_1+x_2+x_3+x_4) \quad ; \quad A_y = \frac{1}{4}(+y_1+y_2+y_3+y_4) \\
B_x = \frac{1}{4}(-x_1+x_2-x_3+x_4) \quad ; \quad B_y = \frac{1}{4}(-y_1+y_2-y_3+y_4) \\
C_x = \frac{1}{4}(-x_1-x_2+x_3+x_4) \quad ; \quad C_y = \frac{1}{4}(-y_1-y_2+y_3+y_4) \\
D_x = \frac{1}{4}(+x_1-x_2-x_3+x_4) \quad ; \quad D_y = \frac{1}{4}(+y_1-y_2-y_3+y_4)
$$
In general, calculating the local coordinates from the global ones is a highly non-trivial exercise.
But it seems that we are lucky: the rectangle in the question is a parallelogram. In that case,
Wikipedia teaches us that
The diagonals bisect each other:
$$
\frac{1}{2} \left(\begin{bmatrix} x_1 \\ y_1 \end{bmatrix} + \begin{bmatrix} x_4 \\ y_4 \end{bmatrix}\right) =
\frac{1}{2} \left(\begin{bmatrix} x_2 \\ y_3 \end{bmatrix} + \begin{bmatrix} x_2 \\ y_3 \end{bmatrix}\right)
$$
Consequently, for a parallelogram, the non-linear $\,\xi\eta\,$ factors drop out. So our equations become:
$$
\begin{cases}
B_x\xi + C_x\eta = x-A_x \\
B_y\xi + C_y\eta = y-A_y
\end{cases}
$$
Two linear equations in two unknowns which can be easily solved with Cramer's rule:
$$
\xi = \frac{B_x(y-A_y)-B_y(x-A_x)}{B_xC_y-B_yC_x} \\ \eta = \frac{C_y(x-A_x)-C_x(y-A_y)}{C_yB_x-C_xB_y}
$$
Now the Inside-Outside function for a general quadrilateral may be defined as:
$$
\operatorname{IO}(x,y) = \min\left[N_1(\xi,\eta),N_2(\xi,\eta),N_3(\xi,\eta),N_4(\xi,\eta)\right]
$$
Then we have that a point $(x,y)$ is inside the quadrilateral if $\,\operatorname{IO}(x,y)\gt 0\,$,
it is outside the quadrilateral if $\,\operatorname{IO}(x,y)\lt 0\,$ and it is on the boundary if
$\,\operatorname{IO}(x,y) = 0\,$. The calculations are quite feasible only for parallelograms.
Summarizing the recipe:

Calculate $(A_x,B_x,C_x)$ and $(A_y,B_y,C_y)$ from the vertex coordinates
Calculate $(\xi,\eta)$ from $(x,y)$ with the above Cramer's solution
Calculate the four shape functions $N_k(\xi,\eta) = (1\pm\xi)(1\pm\eta)/4$
Calculate the Inside-Outside function as the minimum of them
Answer: find the equations of the lines and equate the distance from the point P TO THE GIVEN TWO Pairs of lines .if the point is inside the rectangle,the distances to the pairs will be less than the distances between the line in the pair


Empirical formula- 68%, 95.5%, & 99.9% of scores

Question: I'm having trouble with some stats questions for my psychological testing paper. Have tried emailing the professor but to no avail. Given the standard deviation of 19.8,Identify the range of scores where you would expect to find 68,99.5,& 99.9% of the scores if there were a normal distribution. And then how does the distribution we obtained compare? The mean is 66 for this data set. I've been working on this paper for weeks (it's already over 20 pages long and I think my brain is just wiped out, for the life of me I can't seem to get an answer that makes since. I was sure this wasn't a normal distribution, but according to SPSS it meets the criteria.) If someone could solve it that would be amazing, I know the steps but somehow I'm lost.
Comment: Please add the `[self-study]` tag & read its
[wiki](http://stats.stackexchange.com/tags/self-study/info). Then tell us
what you understand thus far, what you've tried & where you're stuck. We'll
provide hints to help you get unstuck. Please make these changes as just
posting your homework & hoping someone will do it for you is grounds for closing.
Comment: What does the "empirical formula" you were given actually state?
Comment: I assume you're in Holden's class? I'm looking for the same answer lol.
Answer: With the mean being 66 and the standard deviation being 20, the scores on a normal distribution at 68% are 46-86; 95.5% are 26-106, and 99.9% are 6-126. Given this, I looked to see what scores our class got that fell between the scores of 46 and 86 and got 62%. Between 26 and 106, fell 99% of our scores, and 100% of our scores fell between 6 and 126 (as there were no scores below 25, or above 100). No sure if I did this correctly, but these are the answers I got.
Comment: Leaving aside the somewhat dubious benefit of this exercise, I believe that you're more or less doing the kind of calculation that was wanted.
Comment: I  converted the original to a comment, but since you edited it to respond to the question I now assume this is intended as an answer, so I have undeleted. However, I have removed the part that's in the earlier comment (since that's already under the question).


Symfony2 : use translator in a twig filter extension

Question: I'm trying to use translation in a custom twig filter like this
public function formatTime($timestamp)
{
    $str = date('j %\m%',$timestamp);
    $str = str_replace($str, '%m%', $this->get('translator')->trans('month'.date('m', $timestamp) ) );
    return $str;
}

offcourse get is unknown function.
Should I make my Extension aware of the environment or simply request translation class to make it available ?
Answer: You can inject a translator service into your class:
<service id="acme.extension" class="Acme\Twig\Extensions\FormatterExtension">
    <tag name="twig.extension"/>
    <argument type="service" id="translator"/>
</service>

And then store an instance of translator in the protected field and use it later:
public function formatTime($timestamp)
{
    $str = date('j %\m%',$timestamp);
    $str = str_replace($str, '%m%', $this->translator->trans('month'.date('m', $timestamp) ) );
    return $str;
}

UPD1: configuration for YAML service definition:
acme.extension:
    class: Acme\Twig\Extensions\FormatterExtension
    arguments: [@translator]
    tags:
        - name: twig.extension

Comment: Dependency Injection tag is `@translator.default` by Symfony 2.6, the `@translator` tag refers to LoggingTranslator now.
Comment: My service is defined in a yml configuration file, I assume it should like this :

    twig.extension.rc_extension:
      class: Acme\Twig\Extensions\FormatterExtension
      arguments:
        - { type: service, id: translator }
      tags:
        - { name: twig.extension }
Answer: I would define your class as a service using the service container. You can then pass in the translator service as an argument like this:
in services.yml:
services:
    your.class.identification.key:
       class: \your\class\name
       arguments: [@translator]

afterwards, the translator will be available via the code  you provided above.
Comment: Dependency Injection tag is `@translator.default` by Symfony 2.6, the `@translator` tag refers to LoggingTranslator now.
Answer: Just to update @Alexander answer. Don't forget to put
private $translator;
public function __construct(TranslatorInterface $translator) {
   $this->translator = $translator;
}

Answer: Inside the controller layer $this->get() calls the get method from the translator service.
In order to mimic this behavior, you can set dependency injection and have the dependency container injected to your constructor. Once you've done this, you can get the translator by using something like this: $this->container->get('translator').


Comando "find" eclipse

Question:
Sempre quando abro uma janela, todo editor fica "ofuscado" dificultando a leitura, alguém já passou por isso e consegue me ajudar?
Comment: está utilizando o ubuntu?
Comment: Sim, utilizo ubuntu
Comment: isso aí provavelmente não é relacionado ao eclipse não, utilizo aqui no windows e não acontece, alguns temas do linux deixam esse fundo branco, é só alterar
Comment: é isso mesmo, muito obrigado, posta isso como resposta amigo!
Answer: Conforme comentado, alguns temas do Ubuntu dão esse efeito de blur no fundo, não sendo diretamente ligado ao Eclipse, sendo necessário apenas alterá-lo.
Comment: Muito obrigado! Era esse o problema.

Comando "find" eclipse


A question on differentiable functions on manifolds and the so-called "Hadamard's Lemma"

Question: I've been trying to prove Hadamard's lemma for smooth functions:
"For any smooth function $F:\mathbb{R}^{n}\rightarrow\mathbb{R}$ and any $a=(a^{1},\ldots,a^{n})\in\mathbb{R}^{n}$ there exist $C^{\infty}$ functions $H_{\mu}$ such that for all $x=(x^{1},\ldots,x^{n})\in\mathbb{R}^{n}$
$$F(x)=F(a)+\sum_{\mu =1}^{n}\left(x^{\mu}-a^{\mu}\right)H_{\mu}(x)$$ Furthermore, the functions $H_{\mu}$ satisfy $$H_{\mu}(a)=\frac{\partial F}{\partial x^{\mu}}\bigg\vert_{x=a}."$$
I'm unsure whether I've proceeded correctly. Here is the start of my attempt so far.
Let $\gamma :[0,1]\rightarrow\mathbb{R}^{n}$ be a curve in $\mathbb{R}^{n}$ such that $\gamma (0)=a\in\mathbb{R}^{n}$ and $\gamma (1)=x\in\mathbb{R}^{n}$, hence a fixed value of $t\in [0,1]$ identifies a point in $\mathbb{R}^{n}$ by $\gamma (t)$. The curve $\gamma$ is such that it passes through the fixed point $a\in\mathbb{R}^{n}$ and some arbitrary point $x\in\mathbb{R}^{n}$. The coordinate representation of the curve is given by $$\gamma (t)=\left(x^{1}(t),\ldots,x^{n}(t)\right)=\gamma (0)+t\left(\gamma (1)-\gamma (0)\right)=a+t\left(x-a\right)$$ where $x^{\mu}:[0,1]\rightarrow\mathbb{R}$ are the coordinate functions that specify the coordinates of the curve $\gamma$ in $\mathbb{R}^{n}$ for each value of $t\in [0,1]$. We thus define the coordinate functions $x^{\mu}$ such that $$x^{\mu}(t)=a^{\mu}+t\left(x^{\mu}-a^{\mu}\right)$$ where $a^{\mu}, x^{\mu}\in\mathbb{R}$.
Now consider the function $h:[0,1]\rightarrow\mathbb{R}$, defined such that  $$h(t)=(F\circ\gamma)(t)=F(\gamma(t))=F(a+t(x-a))$$ where $F:\mathbb{R}^{n}\rightarrow\mathbb{R}$ is $C^{\infty}$. It follows that $$\frac{dh}{dt}=h'(t)=\frac{d}{dt}\left[(F\circ\gamma)(t)\right]=\frac{d}{dt}\left[F\left((x^{1}(t),\ldots,x^{n}(t))\right)\right]\\ \qquad=\sum_{\mu =1}^{n}\frac{\partial F}{\partial x^{\mu}}\frac{dx^{\mu}}{dt}=\sum_{\mu =1}^{n}\frac{\partial}{\partial x^{\mu}}\left[F(a+t(x-a))\right]\left(x^{\mu}-a^{\mu}\right).$$
If this first part is correct I'm fairly sure that I can complete the rest, but I'm unsure as to whether I've set it up correctly?! Any help would be much appreciated.
Comment: This seems convoluted. Did you look at the proof given on Wikipedia?
Comment: Yes, but I just wanted to justify it a bit more and check my understanding, e.g why one can write $\frac{\partial F (a+t(x-a))}{\partial x^{\mu}}$.
Answer: I'm not a mathematician, but I think you are probably on the right track.
$\gamma(t)$ links the point $a$ and $x$. You've found nice expressions for $H_{\mu}(x)$, for integrating your last eq. for $h^{'}(t)$ from $0$ to $1$, you will get $F(x) - F(a) = \int_0^1 d t \frac{\partial}{\partial x^{\mu}} \left[ F(a+t(x-a)) \right] (x^{\mu} - a^{\mu})$; thus, $H^{\mu}(x) = \int_0^1 d t \frac{\partial}{\partial x^{\mu}} \left[ F(a+t(x-a)) \right]$.
The only other thing that remains to be proved is that $H^{\mu}(x)$ is smooth. I'm no mathematician, but I think all you need to show is that all partial derivatives of $H^{\mu}(x)$ with respect to $x$ exist and are continuous. This follows from the fact that $F(x)$ is smooth, and I think it's legitimate (?; in doubt) to exchange the operation of integration and partial differentiation. For example, $\frac{\partial}{\partial x^{nu}} \int_0^1 d t \frac{\partial}{\partial x^{\mu}} \left[ F(a+t(x-a)) \right] = \int_0^1 d t \frac{\partial^2}{\partial x^{\mu} x^{\nu}} \left[ F(a+t(x-a)) \right]$
Comment: Thanks for taking a look. The main bit that I'm unsure about is whether this part is valid: $\gamma (t)=\left(x^{1}(t),\ldots,x^{n}(t)\right)=\gamma (0)+t\left(\gamma (1)-\gamma (0)\right)=a+t\left(x-a\right)$? Can one assume this and still claim a general result?
Comment: $x$ is from $R^n$. $\gamma(t)$ is just a straight line connecting $a$ and $x$. I think this operation is valid (in $R^n$).
Comment: That's what I thought, but then I showed it to someone else, and they said it wasn't valid as the expression for $\gamma$ (as I gave it) could only ever (at best) be an approximation of a curve?! I though it was satisfactory as it satisfies the required boundary conditions?!
Comment: What do you mean by "could only ever (at best) be an approximation of a curve"? A straight line is a curve.
Comment: Yeah, I know. I don't know whether he just misunderstood what I was trying to convey, or whether he was trying to say that one couldn't use such a straight line to prove that the case is true in general?!
Comment: Then you have to ask him where does the proof goes wrong. Probably exchanging the operation of integration and partial differentiation is a bit dangerous. But I think for nice functions it's possible.
Comment: You're right, I'll have to ask him. Personally, I thought it was fine, but then again, I'm not a pure mathematician.


Named Pipes Server exits without warning

Question: Im trying to setup a named pipes connection between a server-software and a client.
This is my server code:
class Program
{
    private static NamedPipeServerStream server = new NamedPipeServerStream("p", PipeDirection.InOut);
    static void Main(string[] args)
    {
        Action<NamedPipeServerStream> a = callBack;
        a.BeginInvoke(server, ar => { }, null);
    }

    private static void callBack(NamedPipeServerStream pipe)
    {
        pipe.WaitForConnection();
        var line = "";
        while (line != "exit")
        {
            try
            {
                StreamReader reader = new StreamReader(pipe);
                while (line != "exit")
                {
                    line = reader.ReadLine();
                    switch (line)
                    {
                        default:
                            foo();
                            break;
                    }
                }
                break;
            }
            catch (IOException)
            {
                pipe.Disconnect();
                continue;
            }
        }
    }
}

But when I try to run this application it exits directly after the start.
I have used the debugger to reach the WaitForConnection-line and then it exits without an error or an exception. And there is nothing running but the server.
It quits without getting handled by the catch-part. Am I missing anything?
Answer: The execution is blocked on WaitForConnection and will not continue until a NamedPipeClientStream object establishes a connection to the NamedPipeServerStream object.
Please have a look here (The example should help you out): https://msdn.microsoft.com/en-us/library/system.io.pipes.namedpipeclientstream(v=vs.110).aspx
EDIT: I misunderstood the problem and originally thought that the question had to do with the execution blocking from the WaitForConnection method. The code below is the addition to the actual quesiton as well as my explanation.
The problem is the way you invoke your action. As you are calling BeginInvoke it is invoked asynchronously, on a threadpool thread. Therefor you need to check if the action has finished or not otherwise the main thread keeps running and reaches the end. I have updated my answer on how you can do this very easily
Hopefully this code helps you understand why it exists! :)
        Action<NamedPipeServerStream> a = callBack;
        var result = a.BeginInvoke(server,ar => { },null);

        while (!result.IsCompleted)
        {

        }

Comment: I know that the execution will be blocked normally. But in this case the whole programm quits.
Comment: @Snickbrack Ahh okay, appologies. I thought you meant, by saying "And there is nothing running but the server", that it kept running but did not go futher in the code. I'll have a closer look and get back to you
Comment: @Snickbrack The problem is the way you invoke your action. As you are calling BeginInvoke it is invoked asynchronously, on a threadpool thread. Therefor you need to check if the action has finished or not otherwise the main thread keeps running and reaches the end. I have updated my answer on how you can do this very easily


@Autowired annotation not working

Question: I'm trying to test the Autowire option like this:
@ContextConfiguration(locations = { "classpath:applnContext.xml" })
public class Foo {
    @Autowired
    private Bar bar;

    public Bar getBar() {
        return bar;
    }

    public void setBar(final Bar bar) {
        this.bar = bar;
    }

    public static void main(final String[] args) {
        final Foo f = new Foo();
        System.out.println(f.getBar());
    }
}

and the config file :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <bean id="bar" class="entity.Bar"></bean>
    <context:annotation-config />

</beans>

But the Bar object is not getting injected. Am I missing anything here or doing something wrong?
Note that I'm specifying the applicationContext file using annotation on the class.
Answer: If this is a unit-test, as it seems, add
@RunWith(SpringJUnit4ClassRunner.class)

And in your applicationContext.xml don't forget this (although in this case it is not the problem)
<context:component-scan base="org.basepackage" />

Answer: The @ContextConfiguration attribute is part of the org.springframework.test package, so isn't going to work in the manner you've attempted to use it.  See this post on the Spring forums for more details.

@Autowired annotation not working


mysql group_concat distinct with joins very slow horrible performance

Question: I have the following query which produces the results I need but it's horrible as far as performance on large DB/tables.. can somebody please point out why it's so slow and show me another way of writing this so it's fast.  I takes over an hour to finish!  Plenty of ram.. dedicated server not much else going on it.
UPDATE feed.product fp
LEFT JOIN ( SELECT  p.date_upd, p.id_product, GROUP_CONCAT(DISTINCT(CONCAT ('https://www.example.com/', pi.`id_image`,'-x_shop/',pl.link_rewrite,'.jpg')) SEPARATOR ",")  AS images
    FROM db.products p
      LEFT JOIN db.image pi ON (p.id_product = pi.id_product)
      LEFT JOIN db.product_lang pl ON (p.id_product = pl.id_product)
     GROUP BY p.id_product
   ) s ON fp.id_product = s.id_product
SET fp.images = s.images
WHERE fp.image_updated = 1;

Answer: You might find this better with a correlated subquery:
UPDATE feed.product fp
    SET fp.images = (SELECT GROUP_CONCAT(DISTINCT(CONCAT ('https://www.example.com/', pi.`id_image`,'-x_shop/',pl.link_rewrite,'.jpg')) SEPARATOR ",")  AS images
                     FROM db.image pi JOIN
                          db.product_lang pl
                          ON pi.id_product = pl.id_product
                     WHERE fp.id_product = pi.id_product
                    )
    WHERE fp.image_updated = 1;

This will be particularly helpful if only a minority of rows in fp are being updated.
Comment: @Jake . . . For performance, you need the right indexes on the right columns.
Comment: Hi.. thanks for the suggestion.. I will test it and post back.. can you also please describe to me why it's so slow?  I'm looking for a solution and also to learn as to why it's performing that way.   Also you mentioned if there's minor updates.. sometimes there's lots of rows that needs to get updated.


Ocultar um radio button quando clicar em outro radio button

Question: Bom dia pessoal, estou com uma dúvida nos radio button, não faço ideia do que fazer.. sou um pouco novo no php / javascript e queria entender como posso fazer isso funcionar.
Eu tenho uma grade de cursos, nessa grade preciso que o aluno preencha sua preferência com 5 tópicos, então o que eu fiz, criei uma div onde separa os radio buttons lado a lado, ficando assim.
(3) Web Design
(5) Montagem e manutenção
(4) Rotinas de escritório
(2) Hotelaria
(1) Atendimento ao cliente
Basicamente preciso que o usuário clique em qual ele prefere de 1 a 5, como acho que o modo mais fácil de exibir isso e facilitar seria com radio button, gostaria que assim, se o usuário clicar em Web Design com a opção 1, o campo Web Design oculte para que não clique mais e decida as próximas sequencialmente.
Answer: Se você quer permitir várias seleções, não deve usar o Radio Button pois a ideia dele é que se escolha apenas uma.
Sugiro que use Checkboxes para isso. Também sugiro que não esconda o elemento, mas desabilite-o. Lembre-se que uma vez desabilitado, o usuário não irá conseguir desmarcar, com isso, você precisa garantir alguma maneira de recomeçar a seleção.
Veja o exemplo abaixo:

checkboxes = document.querySelectorAll(".ck-preferencias");
prioridades = document.getElementById("prioridades");
btLimpar = document.getElementById("limpar");

checkboxes.forEach(function(checkbox){
  checkbox.addEventListener('click', function(){
    pai = checkbox.closest("li");
    escolhido = document.createElement("li");
    escolhido.name="prioridades[]";
    escolhido.innerHTML = pai.innerText;
    checkbox.disabled = true;
    checkbox.checked = false;
    prioridades.appendChild(escolhido);
  });
});

btLimpar.addEventListener('click', function(){
  prioridades.innerHTML = "";
  checkboxes.forEach(function(checkbox){
    checkbox.disabled = false;
  });
});

<input class="ck-preferencias" type="checkbox" value="web-design" />Web design

<input class="ck-preferencias" type="checkbox" value="manutencao" />Manutenção

<input class="ck-preferencias" type="checkbox" value="rotinas" />Rotinas de Escritório

<input class="ck-preferencias" type="checkbox" value="hotelaria" />Hotelaria

<input class="ck-preferencias" type="checkbox" value="atendimento" />Atendimento ao cliente

<button id="limpar">Limpar seleção</button>
Comment: Muito obrigado! Isso vai ajudar muito, estava a um bom tempo sem saber como prosseguir '-', obrigado mesmo pela força!
Comment: Disponha, estamos aqui para ajudar.
Comment: Amigo aqui funciona perfeitamente, porém por que quando encaminho o mesmo código pro Atom e executo no meu sistema não funciona? desculpe sou meio leigo em programação ainda


Numbers too large for my calculator, probability. Old calculator or should it be done another way?

Question: It's basic binomial probability, the problem is that the numbers are to large for my calculator. Is this the point of the task, to force me to use another method? It doesn't seem lightly, because n over r is a must anyways. An example would be 1000 over 180.
Note that on the exam it self I am allowed to use my laptop (mac), but not the net. So if you can think of any programs that can deal with this size of numbers I'd appreciate it.
Comment: You should explain more about *what the task is*. How are we supposed to figure out what the goal of the assignment was without knowing what was assigned?
Comment: Is the problem you are solving related to the binomial distribution? If so, there is the normal approximation(http://en.wikipedia.org/wiki/Binomial_distribution#Normal_approximation) and the Poisson approximation (http://en.wikipedia.org/wiki/Binomial_distribution#Poisson_approximation).  I am suggesting this in a comment because it doesn't directly answer your question as stated.
Comment: The problem applies to a lot of different tasks where the numbers are to big, so it really is in general.
Answer: You can use Stirling's approximation to get the logs of the factorials.  So if $$x_k={1000\choose k}0.2^k0.8^{1000-k}=\frac{1000!}{k!(1000-k)!}0.2^k0.8^{1000-k}$$ you have $$\log x_k\approx (1000+\frac{1}{2})\log 1000-(k+\frac{1}{2}) \log k - (1000-k+\frac{1}{2})\log (1000-k)$$    $$ -\frac{1}{2}\log 2\pi+k \log 0.2 + (1000-k) \log 0.8$$
Answer: Since I'm allowed to use my computer the bcd function on my casio can be done in excel with the following line: =BINOMDIST(180,1000,0.2,TRUE). The true part is because we want the probability for at most 180 people/success.
Comment: Well, problems like this are the reason, why the books and courses teach about the normal approximation! Frankly, it is hard to believe that the teacher would want you to compute all 181 terms by frantically punching a calculator. I suggest that for preparatory problems you: 1) try more realistic numbers, 2) learn about the normal approximation. Presumably you can use a table or something to produce the cdf of a normally distributed random variable?
Comment: But you probably *can* (in a way) do it with your calculator by starting with a term $x_k={1000\choose k}0.2^k0.8^{1000-k}$ that your calculator can do accurately (relatively small $k$). Then you can use the formula $x_{k+1}=x_k*(1000-k)*0.2/(0.8*(k+1))$. And then in the end sum $x_0+x_1+\cdots+x_{180}$. But I really don't think that you want to do that, and numerical inaccuracies are bound to make this doubtful anyway.
Comment: I got in contact with the author and we are allowed to use laptops on the exam. Problem solved.


Node content not available to anonymous users

Question: I'm having some trouble with viewing my nodes as an anonymous user. When not logged in as admin, I am still able to access the URL of the node, but the content (other than the title) is blank. I've spent a lot of time looking around the permissions, but I can't seem to resolve this issue. The problem exists when accessing the node directly or through a view.
The below example uses nodes with the Link field type, but I'm also having the same problem with my text and file fieldtypes.
This is what displays in a particular view as anonymous:

The same view, logged in as admin:

Hopefully an easy fix, any recommendations would be great!
Comment: As an anonymous user, open the page, active the firebug and check if the `DIV` of the fields are created or not, and if yes, check what is inside it. it would be better of you display its screenshot in your question.
Comment: Are you using the [field permissions](http://www.drupal.org/project/field_permissions) module?
Comment: Field Permissions is not installed on my site.
Answer: Try rebuilding site content permissions. Every now again that has tripped me. In D7 you can find it @ /admin/reports/status/rebuild.
Answer: In this case, it was the Organic Groups Field Access module causing the problems. Disabling the module allowed anonymous users to view the full node properly.


Multiple Imputation methods

Question: Suppose that a variable $Y_j$ has missing values. We can use regression to impute the data using the nonmissing observations:
$$Y_j = \beta_0+\beta_{1}Y_{1}+\beta_{2}Y_{2} + \dots + \beta_{(j-1)} Y_{(j-1)}$$
What are the disadvantages of this? When would it be better to impute the data from a distribution? For example, if a variable <code> age </code> has missing values, when would it be better to randomly sample from the overall distribution of the non-missing values of <code> age </code>?
Answer: True multiple-imputation methods return several sets of "complete" data, effectively imputing a distribution rather than a single estimate for each missing value. Your regression equation, in contrast, would provide only a single imputed value for each missing data point.
Downstream analysis of multiply-imputed data involves analyzing each of the data sets and pooling the results across the imputations, providing information about the variability arising from the imputation process. This approach is thus considered superior to simply examining a single set of imputations. This page provides a useful introduction to the concepts and links to software that implement the process.
You must, however, determine whether the necessary assumptions are met in your data. In particular, if the probability of a data point being missing depends on the value of the data point, then imputation will not be reliable.

Multiple Imputation methods


Anyone else have a noise issue with thicker (~9mm) picks?

Question: I watched a video from Rob Scallon on Purple Plectrums, and in his video they looked and sounded great. However, I purchased one of theirs, a 9mm model and I was very confused. I loved the feel of it, and it sounded great at first, but as I kept playing I noticed there was a very noticeable "plinking" noise whenever I hit notes in quick succession. I tried on two different guitars, I tried playing in different positions between both pickups, and I made sure I was picking at the very thinnest part of the edge that I possibly could, but the issue still persisted. I Googled the issue and found absolutely nothing. So I contacted Purple Plectrum (with an audio clip of what it sounded like) and they said they had never heard of anything like that happening, so they sent me a new, upgraded hand-made one. This one feels even better, but the same exact issue persists. I contacted them again, and they said I might just not understand how to play it/it might not be the right pick for me, and they linked the exact Rob Scallion that made me want it in the first place! It's not like I'm even hitting the strings in very quick succession either, I'm playing at a pretty reasonable speed, probably no faster than Rob plays in the very video, yet I hear nothing like it in his video. So does anyone have any experience with Purple Plectrums and thick picks, or have a similar experience with picks making a noise when you repeatedly hit a string? I spent $30 and I really like the feel of it so I want to be able to use it.
Edit: I should mention the String Gauge is Ernie Ball Regular .010-.046 and the strings are raised about 2.75mm above the 14th fret.
Comment: Is everybody missing out on a decimal point here? 9mm is nearly the thickness of your finger.
Comment: @ToddWilcox here's a link to the sound https://soundcloud.com/connor-gette/string-plinking-sound/s-Mne00
Comment: To me a bit of a harder attack is normal with less flexible picks, and part of the attraction of using them...
Comment: Btw do you hear this noise through the amp, or just acoustically?
Comment: @Tetsujin They really are 9mm. And they come with a 5-year warranty. https://www.purpleplectrums.com/collections/mid-tech/products/scallon-1
Comment: Wow! Totally bizarre! ;) Warranty aside, I have a Jim Dunlop .60mm I've had since the late 70s ;)
Comment: Can you add a link to the same audio file that you sent to the pick makers?
Comment: Sure, do I need to upload it privately on soundcloud then link it or something? I'll do it when I get home from work.
Comment: @Tetsujin they're really 9mm. not the tip you play with obviously but the part you hold. And they feel great.
Comment: It is possible that your picking technique needs improvement.  When you change gear (and picks are gear) you need to adjust to the new feel.  Now all your muscle memory is set to give a good attack with another pick.  New thickness, material, flexion, etc will require an adjustment period.  I use very thick picks (though not as thick as yours).  I have noticed similar issues when switching pick style and string gauge.  But with some practice it clears up.
Comment: @ggcg I understand, and I hope you're correct, however I don't understand how I could possibly play it any differently. Unless I stop hitting the same string in succession, which would seriously limit how I play.
Comment: I'm not suggesting that but there are subtle changes that can make a difference.
Comment: What would you suggest?
Comment: The frequency of the plinky sound suggests that it is the part of the string between the bridge and the pick vibrating. Either the pick is in contact with the string too long before the actual pluck, or maybe you're hitting the string next to it. Can you change the pitch of the plinky sound by playing closer to or further away from the bridge?
Comment: @YourUncleBob if I play very close to the bridge, then the plinking sound almost disappears. Obviously I can't just play there all the time, so I'm not sure what the issue is.
Answer: It would be easier to diagnose with a video of your picking so we can see what your hand is doing, but from listening I have a couple of suggestions you can try.
It sounds like the pick may be noticeably stopping the vibration of the string as you bring it down for the next attack, with the string vibrating against the mass of the bigger pick. Try bringing the pick in at a slightly off angle from the string, making sure you are not picking with the face of the pick in parallel to the string. The Purple is practically a four faced pick, so you may have a little trouble not causing the problem with the other side, but try to get one edge of the pick to hit the string first.
It sounds like you are picking in all down pick motion. I know that's a style with a specific sound, but if the music doesn't call for it you could try using a down up down up picking and see if a softer attack clears it up.
You could also try picking in a more circular motion to the string. Instead of picking down and in to the next string, come up and away from the string and circle over the top to start your next down stroke, keeping your wrist as flexible and relaxed as possible.
A combination of a different angle of attack and a lighter away stroke may help keep the pick from catching the string vibration on your next attack.
Comment: Thanks, this is a really helpful comment. I'll try your suggestions, and if the issue persists I guess I'll use my webcam to record myself while I play, as I have no friends.


How to put description on top of the input box, for a new field added to comment form?

Question: I have added a new field to my comment form and this is how my comment form look liks:

So you can see it does not look nice, I want to have the description on top of the input box, where I say: Which paragraph do you want to put comment on?(Enter 0 if you ant to put comment on the whole article). So How can I do it?
This is the function that I have used to add the new field to comment form:
<code>  function Annotations_form_comment_form_alter(&$form, &$form_state, $form_id) {
$form['paragraph_id'] = array(
    '#type' => 'textfield',
    '#title' => t('Which paragraph you want to put comment on?(Enter 0 if you want to put comment on the whole article.)') . "<br>",
    '#required' => TRUE,
    '#size' => 10,
    '#maxlength' => 2,
    '#default_value' => !empty($form['#entity']->paragraph_id) ? $form['#entity']->paragraph_id : NULL, // set the default value to the current paragraph value
    '#weight' => $form['subject']['#weight'] + 1, // place after the subject field by setting the weight to +1 of subject weight
);

$form['#validate'][] = 'annotations_form_comment_form_validate';
$form['#submit'][] = 'annotations_form_comment_form_submit';
</code>
}
Answer: You need to add a description field to your array:
<code>$form['paragraph_id'] = array(
    '#type' => 'textfield',
    '#title' => t('Your Title'),
    '#description' => t('The paragraph you would like to put a comment on (enter 0 if you want to put the comment on the entire article'),
    ...
);
</code>
This way the explanation will show up under the field.
Comment: Thank you, it worked, So what if I want to have the field under the description?@Klaus Sonnenleiter
Comment: I think that's a matter of how your theme will arrange things on the page. Without getting too deep into it, and since theming is quite a large field to get familiar with, it's probably easiest, if you simply download a couple of themes and see how they change your look and feel.

Once you're comfortable with changing templates, look for "*.tpl.php" files in your theme's folder.
Comment: thanks, so what about comment part? You can see that the "Comment" is on one line, and under it is the comment input box. How can I have something like that?
Comment: This is done in the "Manage Display" section of your content type. I think what you want is to set the label to "inline" instead of "above".


Can some proof that $\det(A) \ne 0$ be checked faster than matrix multiplication?

Question: We can compute a determinant of an $n \times n$ matrix in $O(n^3)$ operations in several ways, for example by LU decomposition. It's also known (see, e.g., Wikipedia) that if we can multiply two $n \times n$ matrices in $M(n)$ steps, then we can compute the determinant in $O(M(n))$ steps as well.
However (and this is the motivating observation here), as in this question, if $\det(A) = 0$, then I can find a vector $\mathbf x$ such that $A \mathbf x = \mathbf 0$, and tell you: "$A$ is a singular matrix. Here is a vector $\mathbf x$ such that $A \mathbf x = \mathbf 0$". I might have done lots of work to find $\mathbf x$, but you can check my work in only $O(n^2)$ steps by computing $A \mathbf x$: faster than you could compute $\det(A)$ without help.
Is it possible, in a similar way, for me to take a matrix $A$ with $\det(A) \ne 0$, and write a proof of this fact which you can also check faster than computing $\det(A)$? (A perfect solution would check the proof in $O(n^2)$ steps; this is best possible, since we need that many steps to even read $A$.)

Observations:

A probabilistic argument exists based on Freivalds's algorithm: I give you $A^{-1}$, and leave you to check that $AA^{-1} = I$. As far as we know, this still needs $O(M(n))$ time to do deterministically, but a probabilistic algorithm can take $O(n^2)$ steps to achieve a one-sided error rate of $\frac12$: if $A^{-1}$ is correct, it will always say "yes", and if $A^{-1}$ is wrong, it will say "no" with probability at most $\frac12$. As a result, you can take $O(n^2\log n)$ steps to achieve  one-sided error rate of $n^{-k}$ for any $k$.
More generally, we could ask for a proof that $\det(A) = x$ for any specific nonzero value of $x$. This was the original question, but there's no hope of solving that for general $x$ if we can't even solve the $\det(A) \ne 0$ case. (After all, a proof that $\det(A)$ has a specific nonzero value $x$ is in particular a proof that $\det(A)$ has some nonzero value.)
Comment: This is a stupid idea, but it might inspire something better. Let the given data be a list of the eigenvectors and their eigenvalues. Then check them probabilistically by taking a random subset $I$ of the eigenvectors and verifying that $A\sum_{i\in I}v_i=\sum_{i\in I}\lambda_iv_i$. This takes $O(n^2)$ time. Repeat this $\log(n)$ times and you can be pretty sure every eigenvalue is correct.
Comment: Do you even know of a fast way to prove that a matrix is invertible? Otherwise, it seems appropriate to ask that as a question, since you need to be able to do that efficiently to do this efficiently. Though to be honest, that in itself requires observing $n$ dimensions' worth of matrix-vector products (so you can verify the output dimension), but that itself implies matrix multiplication, so I would be surprised if it's possible to do it faster at all. (But I'm not a mathematician...)
Comment: I guess it is not too surprising that a probabilistic algorithm exists. (Similarly, we could use $\log n$ iterations of [Freivalds's algorithm](https://en.wikipedia.org/wiki/Freivalds%27_algorithm) to check the LU decomposition in $O(n^2 \log n)$ time to the same standard of "pretty sure".) I would be happier with a deterministic solution, though.
Comment: @Mehrdad That's a good point - I don't, and that is a good place to start. (Do you think I should edit this question, or ask a separate one?)
Comment: @MishaLavrov: If it were me I would probably just edit this question, but I'm actually not sure what's appropriate here.
Comment: Certainly, for some special cases, there are proofs that are checkable in $O(n^2)$ time - for example, if the proof is "the matrix is upper triangular with nonzero diagonal entries".
Comment: In numerical linear algebra algorithms for finding the smallest eigenvalues, without finding all of the eigenvalues, are important, both for dense and sparse matrices. Performing a literature search in that area may provide some interesting results.
Comment: If we were $n$-dimensional beings, then simply by looking at $n$ vectors it would be blindingly obvious whether or not they are collinear. It's interesting to see that this cannot be turned into an easy mathematical verification.
Comment: Checking that $n$ vectors are eigenvectors takes $O(n^3)$ time.
Answer: Just to share another possible alternative, a randomised algorithm expanded from Weidemann provides a method to sample solution from the solution (affine) subspace $Ax =b$ where $A$ is a square matrix and $b$ is in the column space of $A$. So in this case, one can choose $b = 0$ and the algorithm should sample uniformly from the nullspace of $A$ for finite fields. The idea is to run the algorithm a few times for the same input $A$ and let $b= 0$. It will return you some $x$ and if $x$ is not a zero vector for any of those trails, then we know that $A$ is not invertible.
The situation on infinite fields is not so transparent; but it should yield relatively comparable results if you choose a large enough sampling set.
This algorithm claims to take $O(n^2 \log n \log \log n)$ computations in the base field and it requires the base field to be sufficiently large, else, take a field extension. The success probability of this algorithm is quite high so with only finite repetition, I think it is possible to determine whether the matrix is invertible quicker than $O(n^3)$
Edit: Another alternative is to consider the minimal polynomial of the linearly recurrent sequence $\{u^\top A^i b\}$. (A sequence $s_i$ in a $F$ -vsp is linearly reccurent if there exists $n \in \mathbb{N}$ and $a_0,\dots,a_{n-1} \in F$ such that $\sum_{i=0}^{n-1} a_is_{j+i}$ for all $j \in \mathbb{N}$. An example of a linearly recurrent sequence would be the sequence $A^i$ where $A$ is a $n\times n$ matrix, and it is not difficult to see why $\{u^\top A^ib\}$ is also linearly recurrent. The minimal polynomial of a linearly recurrent sequence is just the polynomial $\sum_{i=0}^{n-1} a_ix^i$.)
Now, another result in the paper by Kaltofen and Saunders (which is the paper above) is that one can 'guess' the minimal polynomial of $A$ well enough using the minimal polynomial of the sequence $u^\top A^i b$ by choosing $u$ and $b$ randomly, provided that the base field is sufficiently large. (But in fact, one would always get a factor of the polynomial of $A$).
One may ask why is even is the sequence $u^\top A^i b$ relevant. This is because it is easy to find the minimal polynomial of this sequence of elements in the base field via a dynamic algorithm, the Berlekamp - Massey algorithm. One can just pick randomly sample $u,b$ and find the minimal polynomial of the sequence $u^\top A^i b$.
But now the issue is that one requires a sequence of length $2d$ where $d$ is the degree of the minimal polynomial of $A$, which is unknown and reasonable guess is $d = n$. I am doubting if this method is even sub-$O(n^3)$ since the algorithm relies on Berlekamp Massey.
Comment: Interesting! I think we want it the other way around: we get a probabilistic proof that $\det(A)\ne0$ by trying to solve $Ax=0$ many times and getting $x=0$ every time. Still, this beats the previous probabilistic argument, because we didn't even need any "advice" about $A$.
Comment: If I recall the details of the paper correctly, we can bypass solving the linear system. Note that the sequence $\{u^\top A^i b\}$ is linearly recurrent and one can write a minimal polynomial $f$ for this sequence. In fact $f$ divides the minimal polynomial of $A$. Now, by choosing $u$ and $b$ randomly, we can in fact guess the minimal polynomial of $A$ with high probability (again, given that our field is large enough) and in fact, a factor that has zero constant term will suffice. The  minimal polynomial can be easily found via the Berlekamp Massey algorithm.
Comment: Right, by "trying to solve" I meant "using the algorithm to randomly sample a solution", I was just using sloppy wording.
Comment: Hmm... after some thinking, the algorithm uses relies heavily on Berlekamp - Massey algorithm and that requires $2n$ vector-matrix and vector-vector multiplication, so I am not quite sure if this still works faster than matrix multiplication. Perhaps it would be only ideal for very sparse matrices.


Alternative to fputcsv

Question: I have an array that I want to export to a CSV file, now I know that there is a fputcsv function but I am using version 5.0.4 of PHP so this isn't an option for me.
Is there an alternative method I can use?
Comment: Do have have raw csv (≠ array)? then a normal file_put_contents is good...
Answer: You can use a polyfill for this. write your code as if you where on a system that supports fputcsv From comments within the php block (with some slight framing code) but include this
(copied and slightly modified from http://www.php.net/manual/en/function.fputcsv.php#56827)
<?php
if (!function_exists(fputcsv)){
 function fputcsv($filePointer,$dataArray,$delimiter,$enclosure)
  {
  // Write a line to a file
  // $filePointer = the file resource to write to
  // $dataArray = the data to write out
  // $delimeter = the field separator

  // Build the string
  $string = "";

  // No leading delimiter
  $writeDelimiter = FALSE;
  foreach($dataArray as $dataElement)
   {
    // Replaces a double quote with two double quotes
    $dataElement=str_replace("\"", "\"\"", $dataElement);

    // Adds a delimiter before each field (except the first)
    if($writeDelimiter) $string .= $delimiter;

    // Encloses each field with $enclosure and adds it to the string
    $string .= $enclosure . $dataElement . $enclosure;

    // Delimiters are used every time except the first.
    $writeDelimiter = TRUE;
   } // end foreach($dataArray as $dataElement)

  // Append new line
  $string .= "\n";

  // Write the string to the file
  fwrite($filePointer,$string);
  }
}
?>

Answer: Assuming you have a $Data array, which contains individual arrays for each registry (or line), you may try this:
$Delimiter = '"';
$Separator = ','
foreach($Data as $Line)
{
 fwrite($File, $Delimiter.
        implode($Delimiter.$Separator.$Delimiter, $Line).$Delimiter."\n");
}

Where $File is the handle for your file. Put in $Delimiter, the character you want to put around each field, and in $Separator, the character to use between fields.
Answer: I took the solution from @Orangepill and refactored / simplified it in a couple of ways. This may also become handy if you want every field to be enclosed which is not the case in the default php implementation.
function fputcsv_custom($handle, $fields, $delimiter = ",", $enclosure = '"', $escape_char = "\\") {
    $field_arr = [];

    foreach($fields as $field) {
        $field_arr[] = $enclosure . str_replace($enclosure, $escape_char . $enclosure, $field) . $enclosure;
    }

    fwrite($handle, implode($delimiter, $field_arr) . "\n");
}

Alternative to fputcsv


How to check the url in a WebBrowser in windows phone?

Question: In my application,i'm using WEB BROWSER. what i want is when a particular web page(url) is loaded, i just want to do an action how can i accompolish this one?
Thanks in advance!
Comment: you mean you're using integrated WebBrowser control in the application??
Comment: Yes i'm using Web Browser control
Answer: as you're using WebBrowser control in you application you can add event handler in WebBrowser tag in xaml like:
<phone:WebBrowser Name="customBrowser" Height="758" Width="480" Navigated="navigatedUri" />

you can also use attribute Navigating
right click on navigatedUri and then click Navigate to Event Handler
it will look like,
private void navigatedUri(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
    //add your logic here
}

you want some action to be done after some Uri is loaded, you can check for particular Uri using e.Uri.Tostring(), as follows:
private void navigatedUri(object sender, System.Windows.Navigation.NavigationEventArgs
{
    if(e.Uri.ToString().Equals("www.google.co.in")
    {
         //perform desired action
    }
}

Hope this helps. Ask if you have any query. Thanks.
EDIT:
Sometimes you check for Uri having "http" but it loads "https" so condition is false. In that case you can check Uri on mobile's Internet Explorer and as per that add check conditions. Also you can perform string's Contains method i.e. e.Uri.ToString().Contains("www.google.co.in"). This is totally depends on your requirement, how you want it, how you want to deal with it!
Answer: you can use this javascript code, for example:
if(userAgent.test(navigator.userAgent) ) { // Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i
 // your code..
}


Automatically setup Exchange on Windows Mobile 6

Question: First of i know this question kind of both fitt this page and stackoverflow, but il post it here and if a moderator thinks otherwise please tell me il repost it ( If moving is not easy ).
My problem is this:
We have many different windows mobile phones ( Mostly HTC ) and i need to setup the ability syncing email against our Exchange 2003 server ( In roaming mode , if that mathers ). Since we have many types of windows mobile phones it is annoying to have to dig in the menus to do this every time. So i was wondering is there a solution to do this automaticly?
Phones will be running either Windows mobile 6 or 6.1. If no solution to automaticly do this ( IE some sort of installer either from a windows machine or on the phone itself ) are the registry settings for setting up exchange easly documented?
At the end of the day the company is not that big, so i cannot invest unlimted amount of time into this either. Im fairly compitent in C# so any soltuion that involves code is fine
Comment: How many users are you talking about?
Comment: We are talking about hundreds of users, and then a protion of those will have phone access.
Answer: what you are looking for is called System Center Mobile Device Manager.
Answer: If you don't want to use (and pay for) SCMDM then you can build your own custom configs using the Configuration Service Provider interfaces - I've used these to configure a broad range of WinMo devices in the past with a single fairly lightweight app that builds the XML dynamically and then calls the relvant API - you can do this tethered using RAPICONFIG (part of the Windows Mobile SDK). For WinMo 5 and newer you will probably have to write a small wrapper app to allow provisioning, and for OEM\provider locked devices you will need some form of unlocker but XDADevelopers is your friend for all of this.
The newer OMA Provisioning stuff is much better but harder to implement, the older CSP XML's are simpler but more restricted. Despite that you can use them to set E-Mail accounts, sync preferences, WiFi profiles, Browser setup, Proxies, modify registry settings, security policies import certificates and a lot more. Best of all once you've made the changes you can lock them down and enforce local policies that only allow code signed by you to be installed\run in future.
Works for both SmartPhone (non touch screen) and Pro variants - although the security defaults on the SmartPhone class of devices are higher so it's a bit trickier.
Broadly speaking though - if you use these interfaces you will find that WinMo devices are very easy to work with in general than pretty much any other vendors offerings.
Comment: Of course in the US using an unlocker is likely to get your business support contract voided.
Comment: This is true but many providers will actually give them to you if you ask. In my case we wrapped up some from AT&T\Cingular and Verizon IIRC. And even with about 6000 devices in total (about half in the US) I don't ever recall having needed the service providers support for anything to do with the actual devices - contracts yes, service yes, billing issues of course but hardware issues we dealt with by replacing the devices not trying to troubleshoot one off end point problems beyond completely wiping and re-provisioning.
Answer: I was going to add this as a comment to the above answer but my reputation hasn't yet been established.  SCMDM is neither easy nor cheap.  For a small shop with limited resources, it's unlikely to be an appropriate solution.
For now, your best bet is to continue manual configuration.  For hundreds of users (as opposed to many thousands), it will be cheaper and less time consuming to just do the configuration yourself rather than try to work with SCMDM.
Of course, if you are growing your Windows Mobile presence, SCMDM offers many additional features, such as transparent VPN, domain enrollment, and group policy management.
Answer: I don't know of any specific utility that already exists to do this.  Unfortunately, most WinMo phones have elaborate changes to the UI and shell, even though they run the same host OS.  This makes it difficult to streamline an install like you're asking.
Ultimately, you might look at something like Blackberry (most Blackberry Enterprise Servers can be subsidized through a telephony provider).  The make deploying phones and email so easy it makes Windows Mobile look like an analog device.


What is the correlation between these two time series which I post here?

Question: Here is the figure of the two time series $A_t$ and $B_t$ for a panel data. We can see that the silent time (value equals to zero) are the same and one of time series whatevter $A_t$ or $B_t$ somehow excites another time series, meaning that if the value of $A_t$ or $B_t$ is not equal to zero then another time series is not zero too. Basically I want to use one series to predict another, so at the very begining I was searching the method of causality testing like Granger causality. But every example I saw in the internet is a .. I think it's a normal time series without such a long silent time, thus I am not sure whether Granger causality testing would work well nor not. Is there any option to model this phenomenon?
Thanks a lot!
Answer: Dynamic Time Warping might be a good choice if you are explicitly trying to use one time series to predict another.
This method works by means of determining similarity between two sequences which vary, typically in either time or speed.
From looking at your time series, it would not appear (at least visually) that there is a lag between the two time series, but this would need to be investigated further. Calculating the cross-correlation between the two time series would also be advised.
There is quite an interesting paper in which the author uses DTW to predict US recessions using Treasury term spread data. It may prove useful in informing what you are trying to accomplish.
You can find that here:
Predicting US Recessions: A Dynamic Time Warping Exercise in Economics


What are the feelings & emotions behind chords?

Question: I studied some different books on Music Theory and all were too much scientific and definitely very helpful to some point.
Now that I have started writing some songs, I feel I need to know more about emotions and feelings behind chords.

There must have been some research or studies done about emotions and feelings that chords give us. As an example the feeling I get by hearing C, Cm, Cm6, C7, etc. is totally different and in my mind they're only feelings and I can't share my feelings and speak to somebody about how I feel about different chords. Is there any books or resources that can help me?
Is the feeling you get by hearing a single chords different regarding the type of music? For example, can a C major chord convey a happy feeling and sad feeling in two different songs?
Answer: Context is important -- what else happens around the chord.
Let's just take the C major chord for starters.  Listen to these examples:

The first two measures of Mozart's sonata "for beginners" in C major.  A nice, pleasant chord.  Happy music.
The opening of Mozart's Jupiter Symphony.  This has a much more energetic and heroic sound.
The opening of the fourth movement of Beethoven's Fifth Symphony just after the transition from the previous movement.  A feeling of triumph and accomplishment, and a lot of that feeling is because of what was happening just before.
The point in Alban Berg's opera Wozzeck where Wozzeck gives his wife the money he earned from the doctor.  The whole opera is atonal, except at this one point Wozzeck is accompanied by a very plain C major chord.
Exactly midway through Bartok's "Bluebeard's Castle" when Judith opens door number five.  I won't even describe it.  Listen to the whole thing starting from the beginning.  You'll know when it happens.

Can a song that uses only the notes C, E and G and ends on C be a sad song?  Can it make grown men cry?  I don't know.  Go to the cemetery on Memorial Day and listen to the bugler play "Taps", and you tell me.
Answer: Pursuant to Mark Lutton's excellent answer, I'd like to make the point that Chords don't give us feelings, we give chords feelings.
The feeling you get after hearing a chord is not inherent in that chord--the only thing inherent in any chord is the physics of the harmonic series. (There is something to be said for consonance vs. dissonance within the context of the harmonic series, but that's a very different topic that has been expanded upon in other questions.)
When you hear a chord, your brain automatically associates it with all of the other contexts you've ever heard that chord in. This means that the feeling you get from hearing a chord is almost entirely socially constructed and relative to your sociocultural upbringing.
Now, this doesn't make these feelings useless; in fact, Stefon Harris is working on a musicianship textbook that attempts to teach theory and aural skills almost exclusively through this function of associating feelings with chord structures--and even down to the level of scale degrees. This is all from within the context of modern jazz, however.
Now, assuming I'm understanding your first question correctly:
There may well be studies out there that show what the current popular feeling associations are for a set of chords, but I believe that having this available to you will not help you write better music. If you want to write music that conveys a particular feeling, then you just figure out which note, or chord, or scale, or harmonic landscape matches that feeling most closely in your own mind. This technique is predicated on you writing music for consumption in the culture and context you are familiar with.
Now, in theory, such a resource could be useful to someone writing music for consumption in a culture they are not familiar with. I would personally find that very disingenuous; almost like cheating, in a way. Composers do like to write music outside of their own culture, but they usually do this by exposing themselves to that culture and learning how it works largely through intuitive immersion. (See also: The Beatles' trip to India, Darius Milhaud's time in Brazil.)
This is also true for composers and different styles. Simply put: if you want to write music outside of your own cultural and stylistic reference, you should do yourself the service of immersing yourself in that style and learning how it ticks for yourself. YouTube is great for this--thousands of different styles of music at your fingertips, with a built-in recommendation system to keep you pushing your limits.
Comment: *"the feeling you get from hearing a chord is almost entirely socially constructed and relative to your sociocultural upbringing"* This is only a hypothesis or doctrine, not an iron-clad truth. We can easily cast doubt on it by interviewing children which are just barely old enough to speak to identify various chord sounds as "happy" or "sad".
Comment: The problem that children old enough to speak have already undergone as much as two years of sociocultural immersion does not bode well for either side of the argument. Here is another problem: people from the same society are nevertheless diverse. Liberals, conservatives, hedonists, stoics, god believers, atheists, mystics, realists, pessimist, optimists ... yet a minor triad is melancholy.
Comment: +1 as well. as someone who went to art school, not music school: if someone sits there with a list and says "green means jealosy" and "triangles make you feel grounded" they are BULLSHITTING YOU find another teacher.
Comment: @Kaz Children old enough to speak have already undergone two years of sociocultural immersion. This is a topic heavily researched and studied by ethnomusicologists. I'm happy to entertain doubt, and I myself am not an ethnomusicologist, but know that there's a complete field of study devoted to this kind of thing. :)
Comment: @Kaz We can talk about this in Chat if you want; comments aren't the place for extended discussion.
Answer: The feelings and emotions associated with chords are completely subjective, influenced by a combination of nature and nurture. This is why I might go into raptures over a piece of music that leaves you cold, and vice versa.
Absolute pitch
In This is Spinal Tap, the character Nigel Tufnel says that for him D minor is "the saddest of all keys, I find". Most musicians, I sense, consider that ridiculous, because if you transpose a tune up or down, it seems to be the same tune and therefore no happier or sadder than before.
Yet, some people have perfect pitch, and if they can identify an absolute pitch, it follows that some of them will ascribe different emotions to different pitches. It also follows that the rest of us may to the same to some extent, in a less precise manner.
What's more, very few instruments have completely even intonation -- not even a piano -- so the first step of a D minor scale is a very slightly different interval to the first step of an E minor scale; this may have some almost imperceptible effect on the sensations triggered by the music, for the very sensitive listener.
Relative pitch
However, I firmly believe that relative pitch is a much greater emotional trigger. Think not of the chord, but the chord change.
So for example, The Beatles' Something, played in C major, moves from an F to a D7 for the second line, in a moment that for me is very uplifting. If you transpose it up 5 semitones to A, that chord change becomes D -> B7, but it is no less uplifting.
So it is not the D7 or the B7 that themselves are imbued with emotion: it is those chords compared with the notes that came before -- and of course, in combination with the instrumentation and lyrics that go alongside them.
Key changes
A very common tactic employed by arrangers is the key change. This is where, towards the end of the song, often at the start of a repeat of the chorus, everything shifts up by a tone. The effect is one of exhilaration; it feels like a more joyous key than the one they were singing in just now. Yet the effect fades after a few bars.
Some arrangements have multiple key changes, so as to get that "lift" effect again and again.
Comment: The absolute pitch example is true, but only when using equal temperament. If you instead choose a meantone tuning you'll get quite a different sound and feeling as you tranpose a tune.
Answer: Victor Zuckerkandl, Sound And Symbol
Sound and Symbol is part of Princeton's "Bollingen series". Bollingen is the name of the estate of Carl Jung; hence the whole series represents the "Jungian side" of the sciences.
Sound and Symbol is a "symbolist" approach to musical philosophy. It draws from the Spanish symbolists (who split from the Cubists  who split from the Dadaists who spilt from the Fauvists who split from the Expressionists who split from the Impressionists, IIRC). He draws from the metaphysics of Kant and the pragmatics of Henri Bergson. The thesis is that since you are part of the universe, the pulse of the universe vibrates within you. You already know how rhythm and pitch function in music because you have the entire apparatus already in your cells. (As Plato might suggest, you have but to "remember" it.) You have but to "realize" what you know (inately) and draw attention to some of the finer details of what each aspect really means.
Every tone has a direction that it wants to go (in due time) in order to continue a suspension, depart further from "home", or resolve to a simpler ratio. This process mirrors the movement of electrons among the orbits as an atom gives and receives photonic energy. Both systems are based on the notion of the Octave.
The scale represents a pitch-framework, a One-Dimensional space of integers (whole numbers). With phrasing, additional voices, and dynamics, you can suggest additional spatial dimensions. This is mother earth.
The rhythms represent, of course, dimensions of time. Sequence, Repetition, Termination. This is father time. Also the three weird sisters: Spinning, Weaving, and Cutting the threads of the Minkowski world-lines).
There are pitches and rhythms constantly resounding within the tissues of your own body. The pulse of the blood, the rush of transmitters at the synapse and the oscillations and circuits of the electrical discharges in the neurons.
The suggestion here is that tones and feeling-tones have a similar genetic makeup.
There are of course extremes to which this kind of thinking can be taken (eg. this ebook ), but Zuckerkandl is safely on "this side" of the line. If the power of music truly was as "subjective" as the other answerers are suggesting, it wouldn't be possible to communicate at all (without telling everyone how to feel (shaking the steak in front of Pavlov's dog)). The fact that music has the power to convey emotional content makes a universal basis (an "objective" significance) somwhere between appealing and necessary.


Why if $\rho(I_{\mathfrak{X}} - YA)<1$ then $YA$ is invertible on the $R(YA)$?

Question: I am reading an article where I am stucked at one point. Below is my problem.
Given that $\mathfrak{X}$ and $\mathfrak{Y}$ are Banach spaces.
$A:\mathfrak{X} \to \mathfrak{Y}$ and  $Y:\mathfrak{Y}\to \mathfrak{X}$ are linear bounded operators.
At one step it is written that if $\rho(I_{\mathfrak{X}} - YA)<1$ then $YA$ is invertible on the $R(YA)$, where $\rho$ stands for the spectral radious and $R(A)$ denotes the range space of the operator $A$.  I am not able to  understand  why  operator $YA$ is invertible on the $R(YA)$? Why not on its whole domain $\mathfrak{X}$ ?
Could anyone help me to clear my doubt. I would be very much thankful.
Thanks
Answer: If $T$ is a linear operator on a vector space, $I - T$ is not invertible iff $1$ is in the spectrum of $T$, and that implies the spectral radius of $T$ is at least $1$.  Take $T = I - YA$.
So if $\rho(I-YA) < 1$, $YA$ is invertible on $\mathfrak X$, and this is $R(YA)$ when
$YA$ is invertible.
Comment: Thank you very much. Pleas correct me if I am wrong. Since $YA: \cal{X}\to \cal{X}$ and so invertibility of $YA$ on $X$ implies that $YA$ must be onto hence $R(YA) = \cal{X}$. Thanks again.


How do I launch unicorn_rails as a startup script with rvm installed on my ubuntu 12.04 machine?

Question: I have a rails app on my server. I have a script startup.sh which launches unicorn_rails and then nginx.
In order to get my server to launch on system boot, I've added a line to call my startup script to /etc/rc.local
However, this doesn't work. I added some checks to make sure the script is being called and it is. It's the call to unicorn_rails which I think is failing. Does anyone have experience with this?
Answer: I ran into the same problem and I was able to resolve my issue by creating an init.d script for unicorn_rails and then enabling it on startup with chkconfig.
<code>chmod +x /etc/init.d/unicorn
chkconfig unicorn on
</code>
Example unicorn_rails init.d script.  https://github.com/wayneeseguin/rvm/blob/master/contrib/unicorn_init.sh
The only major change I made in my script was to add nginx service calls to the action blocks.  This way when you start/stop/restart or run status on unicorn_rails nginx follows suit.
Answer: This turned out to be a user-permission issue. Unicorn, ruby and rails were installed as my regular login while the script was being launched as the root user. This created issues with the gems installed not being visible to the root user. I solved the problem by calling a second script with 'su' as my regular non-root user.