How to check whether one's current User Points are negative with the Rules module?

Question: My question is pretty straightforward: how can I check whether a user's current amount of User Points is negative with the Rules module? I'd like to create an action that should be activated when the user is granted User Points. The event is set, but I don't know how I can set the condition.
Edit: I enabled the PHP filter module in order to get the 'Execute custom PHP code' option in my Rule's conditions. (I didn't know that I had to do this before...) I used this code to check whether the user's User Points are negative:
global $user;
$num_pts = userpoints_get_current_points($user->uid, 'all');
$neg_pts = $num_pts < 0;

Unfortunately, it's always evaluated as 'false', even when the amount of User Points is negative. I've also tried this:
$num_pts = userpoints_get_current_points([userpoints-transaction:user]->uid, 'all');
$neg_pts = $num_pts < 0;

But that didn't work either (same reason). I don't get any error messages in both cases.
Are these code snippets wrong? How does the correct one look like?
Answer: global $user;
$num_pts = userpoints_get_current_points($user->uid, 'all');
$neg_pts = $num_pts < 0;

Comment: When you're working with a Contributed module, it's always a good idea to quickly look thru all of the functions that the author defines in their module. In this case, the author left lots of awesome utility functions that make it easy to integrate your modules with the User Points module.
Comment: Where should I paste this code?
Comment: Almost wherever you want. If you've got the PHP Filter installed, you could create a Page, set the Text Format to PHP, and then drop this code in. You could also write your own custom Block, which would allow you to make something like a red/green flag if the user has negative/positive user points, then display that wherever you want.
Comment: Also, if you want to toy with the code to test its effectiveness or the other things you can do, I'd suggest getting the Devel module and adding the "Execute PHP" block somewhere to your site -- then you can enter this code and hit "Execute" and see what it does!
Comment: Sounds cool, but how can I use it with the Rules module? Is there an extra data selector going to be provided?
Comment: Ah shit, man. I didn't read your entire question - my bad. To clarify, you need to make a Rule that runs some action any time anyone is given User Points? BC that module is actually integrated with Rules already, so there are two events called "User Awarded User Points" and "User will be Awarded User Points," which you can use. I don't know how you'd do it as a condition, though...
Comment: Yes, indeed. The event is set, but I don't know how I can set the condition. Thanks anyway for your code snippet. Maybe it can be handy in the future! :)
Comment: I've updated my question. I tried to use your code, but it doesn't work for some reason. Any ideas why?
Comment: Are you printing out what $num_pts evaluates to? Have you tried a DPM of your $user object? It seems like the most likely case is that you're not getting your User's ID. Just FYI, I believe [site:current-user] is the user's username, not a user object. Are you seeing any other error output? Also I didn't know you could execute custom PHP code in the conditions -- thanks for the tip :D
Comment: I didn't know one could do that either... ;) I actually don't know anything about PHP, so I just tried something. I don't get any error messages in both cases.
Comment: It turned out that your code snippet was handy after all! I had to adapt it a little bit, but I couldn't have found the correct answer without your help, so I upvoted your answer. :)
Answer: Have a look at this Rules example (in Rules export format):
{ "rules_display_userpoints_after_updating_content" : {
    "LABEL" : "Display userpoints after updating content",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "userpoints_rules", "rules", "rules_conditional" ],
    "ON" : { "node_update" : [] },
    "DO" : [
      { "userpoints_rules_get_current_points" : {
          "USING" : { "user" : [ "site:current-user" ], "tid" : "all" },
          "PROVIDE" : { "loaded_points" : { "total_points" : "Number of points in all categories together" } }
        }
      },
      { "drupal_message" : { "message" : "You now have [total-points:value] points" } },
      { "CONDITIONAL" : [
          {
            "IF" : { "NOT data_is" : { "data" : [ "total-points" ], "op" : "\u003C", "value" : "20" } },
            "DO" : [
              { "drupal_message" : { "message" : "You have sufficient points (you still have [total-points:value] ...)." } }
            ]
          },
          { "ELSE" : [
              { "drupal_message" : { "message" : "You DO NOT have sufficient points (you only have [total-points:value] ...)." } }
            ]
          }
        ]
      }
    ]
  }
}

It does retrieve, as the very first Rules Action (not Rules Condition!) the current amount of user points of a user. If the amount is at least 20, it will display a message starting with "You have sufficient points ...", otherwise the message starts with "You DO NOT have sufficient points ...".
So you do not need custom PHP code (in your Rules Condition) to get this to work. And you don't need to enable the PHP filter for this ...). Any time you can avoid enabling the PHP filter you should take it (have a look at "What are the downsides of using PHP Filter code in blocks, nodes, views-args, etc?" to understand why).
In this example I'm using the Conditional Rules module, though you could also rework the Rules Action to performing Rules Components (in which you add the appropriate Rules Conditions), so that you don't need this extra module. For more details on that, refer to the answer to "What's the alternative to using the Conditional Rules module?".
The clue to make this rule work is the very first Rules Action "Load user points of a user". Refer to my answer to "How to access current amount of earned userpoints in a Rules Condition?" for more details on this.
Answer: I found the correct code, based on @tigerrussell's answer:
global $user;
$num_pts = userpoints_get_current_points($user->uid, 'all');
if ($num_pts < 0) {return TRUE;}

Just use this snippet in an Execute custom PHP code condition. It's as simple as that! However, it is recommanded to avoid PHP code in Rules. Therefore, I would suggest to install the Conditional Rules module, as explained in Pierre's answer.


Explanation for p-value inequality

Question: I was trying to go over this paper by Dudoit, Shaffer and Boldric when I came across this statement on page 78 (under section 2.4: Control of family-wise error rate):
$P(P_j\leq x \vert H_j)\leq x,$ for any $x\in[0,1] $
where
$P_j$ are the p-values and $H_j$ are true null hypotheses for $j=1,...,m_0$.
I'm still new in statistics and as simple as the inequality seems, I can't seem to wrap my head around it.  Can someone explain this inqeuality in plain words?
In addition, I'm currently doing a project in multiple hypotheses testing correction on dependent variables and it would be helpful if there are any good papers you can recommend that I read.
Answer: It looks like the inequality is presuming there are $m_0$ tests you want to run, and in every case, the null hypothesis is true. Then the inequality states that for each test, and for any real number $x ∈ [0, 1]$, the chance of getting a $p$-value less than or equal to $x$ is itself $x$. So, for example, the chance of getting $p \leq .05$ is $.05$. This is equivalent to saying that under the null hypothesis, $p$ is uniformly distributed on $[0, 1]$, as is typically desired.

Explanation for p-value inequality


What is the intuition behind conditional Gaussian distributions?

Question: Suppose that $\mathbf{X} \sim N_{2}(\mathbf{\mu}, \mathbf{\Sigma})$. Then the conditional distribution of $X_1$ given that $X_2 = x_2$ is multivariate normally distributed with mean:
$$ E[P(X_1 | X_2 = x_2)] = \mu_1+\frac{\sigma_{12}}{\sigma_{22}}(x_2-\mu_2)$$
and variance: $${\rm Var}[P(X_1 | X_2 = x_2)] = \sigma_{11}-\frac{\sigma_{12}^{2}}{\sigma_{22}}$$
It makes sense that the variance would decrease since we have more information. But what is the intuition behind the mean formula? How does the covariance between $X_1$ and $X_2$ factor into the conditional mean?
Comment: In natural ("standardized") units we write $X_i=\mu_1+\sigma_iZ_i$ where $\sigma_i=\sqrt{\sigma_{ii}}$. In these terms the conditional distribution is Normal with $\mathbb{E}(Z_1|Z_2)=\rho Z_2$ and $\rho=\sigma_{12}/(\sigma_1\sigma_2).$ The fact that $|\rho|\le 1$ is called "mean reversion" or ["regression to the mean"](http://en.wikipedia.org/wiki/Regression_toward_the_mean): there is an extensive technical and popular literature on this going back 130 years.
Comment: Is your question simply 'why isn't the mean of the conditional distribution = $\mu_1$'?
Comment: @gung: This is true if $x_2 = \mu_2$. But why are $\sigma_{11}$ and $\sigma_{22}$ involved?
Answer: Synopsis
Every statement in the question can be understood as a property of ellipses.  The only property particular to the bivariate Normal distribution that is needed is the fact that in a standard bivariate Normal distribution of $X,Y$--for which $X$ and $Y$ are uncorrelated--the conditional variance of $Y$ does not depend on $X$. (This in turn is an immediate consequence of the fact that lack of correlation implies independence for jointly Normal variables.)
The following analysis shows precisely what property of ellipses is involved and derives all the equations of the question using elementary ideas and the simplest possible arithmetic, in a way intended to be easily remembered.

Circularly symmetric distributions
The distribution of the question is a member of the family of bivariate Normal distributions.  They are all derived from a basic member, the standard bivariate Normal, which describes two uncorrelated standard Normal distributions (forming its two coordinates).

The left side is a relief plot of the standard bivariate normal density.  The right side shows the same in pseudo-3D, with the front part sliced away.
This is an example of a circularly symmetric distribution: the density varies with distance from a central point but not with the direction away from that point.  Thus, the contours of its graph (at the right) are circles.
Most other bivariate Normal distributions are not circularly symmetric, however: their cross-sections are ellipses.  These ellipses model the characteristic shape of many bivariate point clouds.

These are portraits of the bivariate Normal distribution with covariance matrix $\Sigma = \left(\begin{array}{cc} 1 & -\frac{2}{3} \\ -\frac{2}{3} & 1 \\\end{array}\right).$  It is a model for data with correlation coefficient $-2/3$.

How to Create Ellipses
An ellipse--according to its oldest definition--is a conic section, which is a circle distorted by a projection onto another plane.  By considering the nature of projection, just as visual artists do, we may decompose it into a sequence of distortions that are easy to understand and calculate with.
First, stretch (or, if necessary, squeeze) the circle along what will become the long axis of the ellipse until it is the correct length:

Next, squeeze (or stretch) this ellipse along its minor axis:

Third, rotate it around its center into its final orientation:

Finally, shift it to the desired location:

These are all affine transformations.  (In fact, the first three are linear transformations; the final shift makes it affine.)  Because a composition of affine transformations is (by definition) still affine, the net distortion from the circle to the final ellipse is an affine transformation.  But it can be somewhat complicated:

Notice what happened to the ellipse's (natural) axes: after they were created by the shift and squeeze, they (of course) rotated and shifted along with the axis itself.  We easily see these axes even when they are not drawn, because they are axes of symmetry of the ellipse itself.
We would like to apply our understanding of ellipses to understanding distorted circularly symmetric distributions, like the bivariate Normal family.  Unfortunately, there is a problem with these distortions: they do not respect the distinction between the $x$ and $y$ axes.  The rotation at step 3 ruins that.  Look at the faint coordinate grids in the backgrounds: these show what happens to a grid (of mesh $1/2$ in both directions) when it is distorted.  In the first image the spacing between the original vertical lines (shown solid) is doubled.  In the second image the spacing between the original horizontal lines (shown dashed) is shrunk by a third.  In the third image the grid spacings are not changed, but all the lines are rotated.  They shift up and to the right in the fourth image.  The final image, showing the net result, displays this stretched, squeezed, rotated, shifted grid.  The original solid lines of constant $x$ coordinate no longer are vertical.
The key idea--one might venture to say it is the crux of regression--is that there is a way in which the circle can be distorted into an ellipse without rotating the vertical lines.  Because the rotation was the culprit, let's cut to the chase and show how to created a rotated ellipse without actually appearing to rotate anything!

This is a skew transformation.  It does two things at once:

It squeezes in the $y$ direction (by an amount $\lambda$, say).  This leaves the $x$-axis alone.

It lifts any resulting point $(x,\lambda y)$ by an amount directly proportional to $x$.  Writing that constant of proportionality as $\rho$, this sends $(x,\lambda y)$ to $(x, \lambda y+\rho x)$.

The second step lifts the $x$-axis into the line $y=\rho x$, shown in the previous figure.  As shown in that figure, I want to work with a special skew transformation, one that effectively rotates the ellipse by 45 degrees and inscribes it into the unit square.
The major axis of this ellipse is the line $y=x$.  It is visually evident that $|\rho| \le 1$.  (Negative values of $\rho$ tilt the ellipse down to the right rather than up to the right.)  This is the geometric explanation of "regression to the mean."
Choosing an angle of 45 degrees makes the ellipse symmetric around the square's diagonal (part of the line $y=x$).  To figure out the parameters of this skew transformation, observe:

The lifting by $\rho x$ moves the point $(1,0)$ to $(1,\rho)$.

The symmetry around the main diagonal then implies the point $(\rho, 1)$ also lies on the ellipse.

Where did this point start out?

The original (upper) point on the unit circle (having implicit equation $x^2+y^2=1$) with $x$ coordinate $\rho$ was $(\rho, \sqrt{1-\rho^2})$.

Any point of the form $(\rho, y)$ first got squeezed to $(\rho, \lambda y)$ and then lifted to $(\rho, \lambda y + \rho\times\rho)$.

The unique solution to the equation $(\rho, \lambda \sqrt{1-\rho^2} + \rho^2) = (\rho, 1)$ is $\lambda = \sqrt{1-\rho^2}$.  That is the amount by which all distances in the vertical direction must be squeezed in order to create an ellipse at a 45 degree angle when it is skewed vertically by $\rho$.
To firm up these ideas, here is a tableau showing how a circularly symmetric distribution is distorted into distributions with elliptical contours by means of these skew transformations.  The panels show values of $\rho$ equal to $0,$ $3/10,$ $6/10,$ and $9/10,$ from left to right.

The leftmost figure shows a set of starting points around one of the circular contours as well as part of the horizontal axis.  Subsequent figures use arrows to show how those points are moved.  The image of the horizontal axis appears as a slanted line segment (with slope $\rho$).  (The colors represent different amounts of density in the different figures.)

Application
We are ready to do regression.  A standard, elegant (yet simple) method to perform regression is first to express the original variables in new units of measurement: we center them at their means and use their standard deviations as the units.  This moves the center of the distribution to the origin and makes all its elliptical contours slant 45 degrees (up or down).
When these standardized data form a circular point cloud, the regression is easy: the means conditional on $x$ are all $0$, forming a line passing through the origin.  (Circular symmetry implies symmetry with respect to the $x$ axis, showing that all conditional distributions are symmetric, whence they have $0$ means.)  As we have seen, we may view the standardized distribution as arising from this basic simple situation in two steps: first, all the (standardized) $y$ values are multiplied by $\sqrt{1-\rho^2}$ for some value of $\rho$; next, all values with $x$-coordinates are vertically skewed by $\rho x$.  What did these distortions do to the regression line (which plots the conditional means against $x$)?

The shrinking of $y$ coordinates multiplied all vertical deviations by a constant.  This merely changed the vertical scale and left all conditional means unaltered at $0$.

The vertical skew transformation added $\rho x$ to all conditional values at $x$, thereby adding $\rho x$ to their conditional mean: the curve $y=\rho x$ is the regression curve, which turns out to be a line.

Similarly, we may verify that because the $x$-axis is the least squares fit to the circularly symmetric distribution, the least squares fit to the transformed distribution also is the line $y=\rho x$: the least-squares line coincides with the regression line.
These beautiful results are a consequence of the fact that the vertical skew transformation does not change any $x$ coordinates.
We can easily say more:

The first bullet (about shrinking) shows that when $(X,Y)$ has any circularly symmetric distribution, the conditional variance of $Y|X$ was multiplied by $\left(\sqrt{1-\rho^2}\right)^2 = 1 - \rho^2$.

More generally: the vertical skew transformation rescales each conditional distribution by $\sqrt{1-\rho^2}$ and then recenters it by $\rho x$.

For the standard bivariate Normal distribution, the conditional variance is a constant (equal to $1$), independent of $x$.  We immediately conclude that after applying this skew transformation, the conditional variance of the vertical deviations is still a constant and equals $1-\rho^2$.  Because the conditional distributions of a bivariate Normal are themselves Normal, now that we know their means and variances, we have full information about them.
Finally, we need to relate $\rho$ to the original covariance matrix $\Sigma$.  For this, recall that the (nicest) definition of the correlation coefficient between two standardized variables $X$ and $Y$ is the expectation of their product $XY$.  (The correlation of $X$ and $Y$ is simply declared to be the correlation of their standardized versions.)  Therefore, when $(X,Y)$ follows any circularly symmetric distribution and we apply the skew transformation to the variables, we may write
$$\varepsilon = Y - \rho X$$
for the vertical deviations from the regression line and notice that $\varepsilon$ must have a symmetric distribution around $0$.  Why?  Because before the skew transformation was applied, $Y$ had a symmetric distribution around $0$ and then we (a) squeezed it and (b) lifted it by $\rho X$.  The former did not change its symmetry while the latter recentered it at $\rho X$, QED.  The next figure illustrates this.

The black lines trace out heights proportional to the conditional densities at various regularly-spaced values of $x$.  The thick white line is the regression line, which passes through the center of symmetry of each conditional curve.  This plot shows the case $\rho = -1/2$ in standardized coordinates.
Consequently
$$\mathbb{E}(XY) = \mathbb{E}\left(X(\rho X + \varepsilon)\right) = \rho\mathbb{E}(X^2) + \mathbb{E}(X\varepsilon) = \rho(1) + 0=\rho.$$
The final equality is due to two facts: (1) because $X$ has been standardized, the expectation of its square is its standardized variance, equal to $1$ by construction; and (2) the expectation of $X\varepsilon$ equals the expectation of $X(-\varepsilon)$ by virtue of the symmetry of $\varepsilon$. Because the latter is the negative of the former, both must equal $0$: this term drops out.
We have identified the parameter of the skew transformation, $\rho$, as being the correlation coefficient of $X$ and $Y$.

Conclusions
By observing that any ellipse may be produced by distorting a circle with a vertical skew transformation that preserves the $x$ coordinate, we have arrived at an understanding of the contours of any distribution of random variables $(X,Y)$ that is obtained from a circularly symmetric one by means of stretches, squeezes, rotations, and shifts (that is, any affine transformation).  By re-expressing the results in terms of the original units of $x$ and $y$--which amount to adding back their means, $\mu_x$ and $\mu_y$, after multiplying by their standard deviations $\sigma_x$ and $\sigma_y$--we find that:

The least-squares line and the regression curve both pass through the origin of the standardized variables, which corresponds to the "point of averages" $(\mu_x,\mu_y)$ in original coordinates.

The regression curve, which is defined to be  the locus of conditional means, $\{(x, \rho x)\},$  coincides with the least-squares line.

The slope of the regression line in standardized coordinates is the correlation coefficient $\rho$; in the original units it therefore equals $\sigma_y \rho / \sigma_x$.

Consequently the equation of the regression line is
$$y = \frac{\sigma_y\rho}{\sigma_x}\left(x - \mu_x\right) + \mu_y.$$

The conditional variance of $Y|X$ is $\sigma_y^2(1-\rho^2)$ times the conditional variance of $Y'|X'$ where $(X',Y')$ has a standard distribution (circularly symmetric with unit variances in both coordinates), $X'=(X-\mu_X)/\sigma_x$, and $Y'=(Y-\mu_Y)/\sigma_Y$.

None of these results is a particular property of bivariate Normal distributions!    For the bivariate Normal family, the conditional variance of $Y'|X'$ is constant (and equal to $1$): this fact makes that family particularly simple to work with.  In particular:

Because in the covariance matrix $\Sigma$ the coefficients are $\sigma_{11}=\sigma_x^2,$ $\sigma_{12}=\sigma_{21}=\rho\sigma_x\sigma_y,$ and $\sigma_{22}=\sigma_y^2,$ the conditional variance of $Y|X$ for a bivariate Normal distribution is

$$\sigma_y^2(1-\rho^2)=\sigma_{22}\left(1-\left(\frac{\sigma_{12}}{\sqrt{\sigma_{11}\sigma_{22}}}\right)^2\right)=\sigma_{22} - \frac{\sigma_{12}^2}{\sigma_{11}}.$$

Technical Notes
The key idea can be stated in terms of matrices describing the linear transformations.  It comes down to finding a suitable "square root" of the correlation matrix for which $y$ is an eigenvector.  Thus:
$$\left(\begin{array}{cc} 1 & \rho \\ \rho  & 1 \\\end{array}\right) = \mathbb{A}\mathbb{A}'$$
where
$$\mathbb{A} = \left(\begin{array}{cc} 1 & 0 \\ \rho & \sqrt{1-\rho^2} \\\end{array}\right).$$
A much better known square root is the one initially described (involving a rotation instead of a skew transformation); it is the one produced by a singular value decomposition and it plays a prominent role in principal components analysis (PCA):
$$\left(\begin{array}{cc} 1 & \rho \\ \rho  & 1 \\\end{array}\right) = \mathbb{B}\mathbb{B}';$$
$$\mathbb{B} = \mathbb{Q} \left(
\begin{array}{cc}
 \sqrt{\rho +1} & 0 \\
 0 & \sqrt{1-\rho } \\
\end{array}
\right)\mathbb{Q}'$$
where $\mathbb{Q} = \left(
\begin{array}{cc}
 \frac{1}{\sqrt{2}} & -\frac{1}{\sqrt{2}} \\
 \frac{1}{\sqrt{2}} & \frac{1}{\sqrt{2}} \\
\end{array}
\right)$ is the rotation matrix for a $45$ degree rotation.
Thus, the distinction between PCA and regression comes down to the difference between two special square roots of the correlation matrix.
Comment: That's really interesting.  Thanks for taking the time to write it up.
Comment: Sometimes I wish there was a button that is stronger than an up-vote (+1).
Comment: Beautiful pictures and great descriptions. There were a few sentences in the update that were left incomplete (like you knew basically what you were going to say, but hadn't settled on the final wording).
Comment: @Cardinal Thanks. I will be re-reading this and looking for such things, as well as for the inevitable typos. You are too kind to point out other things which you surely noticed, such as some gaps in the exposition. The biggest is that I did not actually show that these ellipses are at 45 degree angles (equivalently, inscribed in the unit square); I simply assumed that. I am still looking for a simple demonstration. The other is that one might worry the skew transformation could produce a *different* distribution than the original stretch-squeeze-rotate-shift--but it's easy to show it doesn't.
Comment: @Logan The subtraction undoes the "lifting" and the conditional variance is the "squeezing." Both now occur in multiple dimensions, but I think the geometric intuition afforded by the 2D picture is a good one. I don't think of the regression as being "amount that variables ... covary," because that's a *very* special feature of multivariate Normals. Instead, regression supposes the conditional mean is a linear function of the explanatory variables (a line, plane, *etc.*). That the conditional variance does not change with the explanatory variables is also special: it's false for many GLMs, eg.
Comment: @whuber when you start with unit circle (standardized sample set), you say correlation is 0, so I imagine, we get a circle something like $f(X,Y)=e^{\frac{1}{2}{(x^2 + y^2)}}$. But how 0 correlation means independence? (because $f(X,Y)$ is obtained by $f(X)f(Y)$ as we see. It is usually not true right? Even dependent variables could produce 0 correlation?
Comment: @ParthibanRajendran Zero correlation implies independence for jointly *Normal* variables.
Comment: In 1st paragraph of applications it's written that: "we center them at their means and use their standard deviations as the units. This moves the center of the distribution to the origin and makes all its elliptical contours slant 45 degrees", but I don't understand how centering the variables at their means move their centers to origin and align them to 45 degree?
Comment: Great answer! Can you please look at my related question: https://stats.stackexchange.com/questions/553307/how-difficult-is-it-to-determine-the-conditional-distribution-of-a-non-normal-di thank you!
Comment: @whuber This was masterful. I have just spent a week trying to decipher/understand the geometry of conditional gaussians and this helped a ton! There is still one thing I am unsure of, could you explain the geometry of the conditional variance a bit more? The way I intepret the conditional mean is that we're essentially performing a regression, i.e. fix $x$, project onto the regression line, then project onto $y$. Is there a similar analogy for the conditional variance, where does the $\sigma^2_y(1-\rho^2)$ factor come from?
Comment: @whuber I'm looking for geometric intuition for the multivariate conditional where
$\Sigma_{Y|X} = \Sigma_{YY} - \Sigma_{YX}\Sigma_{XX}^{-1}\Sigma_{XY}$. Could it be interpretted as saying: take the the amount that variables 1 & 2 covary ($\Sigma_{XY}$), project it onto the regression line ($\Sigma_{YX}\Sigma_{XX}^{-1}$), and then subtract from the marginal ($\Sigma_{YY}$). It kind of makes sense, but I'm unsure as to why this wouldn't depend on the conditional value, and where the subtraction comes from. Any insights would be greatly appreciated!!
Answer: This is essentially linear (OLS) regression.  In that case, you are finding the conditional distribution of $Y$ given that $X=x_i$.  (Strictly speaking, OLS regression does not make assumptions about the distribution of $X$, whereas your example is a multivariate normal, but we will ignore these things.)  Now, if the covariance between $X_1$ and $X_2$ is not $0$, then the mean of the conditional distribution of $X_2$ has to shift as you change the value of $x_1$ where you are 'slicing through' the multivariate distribution.  Consider the figure below:

Here we see that the marginal distributions are both normal, with a positive correlation between $X_1$ and $X_2$.  If you look at the conditional distribution of $X_2$ at any point on $X_1$, the distribution is a univariate normal.  However, because of the positive correlation (i.e., the non-zero covariance), the mean of those conditional distributions shifts up as you move from left to right.  For example, the figure shows that $\mu_{X_2|X_1=25}\ne\mu_{X_2|X_1=45}$.
(For any future readers who might be confused by the symbols, I want to state that, e.g., $\sigma_{22}$ is an element of the covariance matrix $\Sigma$.  Thus, it is the variance of $X_2$, even though people will typically think of a variance as $\sigma^2$, and $\sigma$ as a standard deviation.)
Your equation for the mean is directly connected to the equation for estimating the slope in OLS regression (and remember that in regression $\hat y_i$ is the conditional mean):
$$
\hat\beta_1=\frac{\text{Cov}(x,y)}{\text{Var}(x)}
$$
In your equation, $^{\sigma_{12}}/_{\sigma_{22}}$ is the covariance over the variance; that is, it is the slope, just as above.  Thus, your equation for the mean is just sliding your conditional mean, $\mu_{X_2|X_1=x_i}$, up or down from its unconditional mean, $\mu_{X_2}$, based on how far away from $\mu_{X_2}$ $x_{2i}$ is and the slope of the relationship between $X_1$ and $X_2$.
Comment: @kerkejnrke, if you model the distribution of $Y$ conditional on some specific level of a set of variables $\bf X$, you are doing *multiple regression*. This is a little more complicated, but ultimately the same thing. The mean would be: $\hat y_i=\bf X_i \boldsymbol{\hat\beta}$, where $\boldsymbol{\hat\beta}=(\bf X^TX)^{-1}X^TY$.
Comment: @mpiktas, I can't imagine my code should ever be described as "awesome"... The normal curves are drawn w/ `dnorm(y)`. I simply add the output to `25` & `45`, & use as `x`.
Comment: What happens if you condition on more variables? You would just add and subtract extra terms from the mean and variance?
Comment: What did you use to produce the graph? Mathematica?
Comment: @mpiktas, my graph or whuber's? I believe his are Mathematica, but I made the one above w/ R. (Ugly code though...)
Comment: Yes I was asking about yours. If this is R, then yeah the code might look ugly, but should be awesome. I suspect the normal curves are rotated viewports? Or did you draw them "by hand"?
Answer: Gung's answer is good (+1).  There is another way of looking at it, though.  Imagine that the covariance between $X_1$ and $X_2$ were to be positive.  What does it mean for $\sigma_{1,2}>0$?  Well, it means that when $X_2$ is above $X_2$'s mean, $X_1$ tends to be above $X_1$'s mean, and vice versa.
Now suppose I told you that $X_2=\mathit{x}_2>\mu_2$.  That is, suppose I told you that $X_2$ is above its mean.  Wouldn't you conclude that $X_1$ is likely above its mean (since you know $\sigma_{1,2}>0$ and you know what covariance means)?  So, now, if you take the mean of $X_1$, knowing that $X_2$ is above $X_2$'s mean, you are going to get a number above $X_1$'s mean.  That is what the formula says:
\begin{equation}
E\{X_1 | X_2=\mathit{x}_2\} = \mu_1 + \frac{\sigma_{1,2}}{\sigma_{2,2}}\left( \mathit{x}_2-\mu_2\right)
\end{equation}
If the covariance is positive and $X_2$ is above its mean, then $E\{X_1 | X_2=\mathit{x}_2\} > \mu_1$.
The conditional expectation takes the form above for the normal distribution, not for all distributions.  This seems a little strange given that the reasoning in the paragraph above seems pretty compelling.  However, (almost) no matter what the distributions of $X_1$ and $X_2$ this formula is right:
\begin{equation}
BLP\{X_1 | X_2=\mathit{x}_2\} = \mu_1 + \frac{\sigma_{1,2}}{\sigma_{2,2}}\left( \mathit{x}_2-\mu_2\right)
\end{equation}
Where $BLP$ means best linear predictor.  The normal distribution is special in that conditional expectation and best linear predictor are the same thing.
Comment: "Intuitive" does not imply "non-quantitative": the two can go together.  It is often difficult to find an intuitive argument that gives quantitative results, but frequently it can be done and the process of finding such an argument is always illuminating.
Comment: @whuber  Yeah, and it's even worse than that.  It's not particularly hard to cook up an example with non-normal distributions where, for some value of $\mathit{x}_2>\mu_2$, $E(X_1|X_2=\mathit{x}_2)<\mu_1$ even though $\sigma_{1,2}>0$.  The "tends to be" and "likely to be" parts of my discussion are slushy.  Perhaps one could lead with the BLP formula (maybe deriving it?), but the question asked for intuition rather than proof.
Comment: There does not seem to be any element of this argument which actually shows the coefficient of $x_2-\mu_2$ should equal the ratio of the covariances $\sigma_{12}/\sigma_{22}$. Why not the cube of that ratio? Or its sine? Or some other measure of association, such as the KL divergence (which has little to do with covariance)? Such formulas would qualitatively reproduce the behavior you describe. Given such vagueness in the reasoning, it should be no surprise that your formula applies only to a particular form of bivariate distribution and not to just any distribution.
Comment: Re the last paragraph: I have found out that the normal distribution is not so special: families created by affine transformations of *circularly symmetric* distributions are the special ones (of which there are very many).
Comment: @whuber  That's pretty interesting.  Do you have a link or cite?
Comment: Yes: my answer in this thread. :-)


Well formed formulas and functions in set theory

Question: In set theory, a function $f:A \to B$ is defined as a subset $f \subseteq A \times B$ such that $$\forall x \in A(\exists!y \in B((x,y)\in f)).$$ Consider the example $f:\mathbf{R} \to \mathbf{R}, x \mapsto 2x^2+3$ which is just an arbitrarily chosen example. To show that this is a function, one has to show that $f$ defines a set that satisfies the property above. As far as I know, sets in set theory are always of the form $$\{a \ | \ \text{some property of a}\}.$$ Hence I think one can write $f$ as $$\{z \ | \ \exists x(\exists y(x \in \mathbf{R} \wedge y \in \mathbf{R} \wedge y=2x^2+3 \wedge z=(x,y)))\}$$ is this correct? Could one also express this as $$\{z \ | \ \exists x(x \in \mathbf{R}) \wedge \exists y(y \in \mathbf{R} \wedge y=2x^2+3) \wedge z=(x,y)\}?$$ If this is the case, I should not be able to write it as a set by "commuting" the introduction of $x$ and $y$, since $y$ depends on $x$, right? What I mean by that can be seen here: $$\{z \ | \ \exists y(y \in \mathbf{R} \wedge y=2x^2+3) \wedge \exists x(x \in \mathbf{R}) \wedge z=(x,y)\}?$$ Since $y$ depends on $x$ it seems weird to me if this would be possible.
Since I try to formalize things in my spare time (I am just starting) I wondered how the statement $$\forall x \in X \forall y \in Y \forall z \in Y(((x,y) \in R \wedge (x,z) \in R) \implies y=z)$$ can be formalized, where $X,Y$ denote some sets and $R \subseteq X \times Y$ denotes a relation. I know that well formed formulas allow for the part "$\forall x \in X \forall y \in Y \forall z \in Y$" followed by a formula. However, I am not sure how to express an according formula. This statement can be found in https://en.wikipedia.org/wiki/Function_(mathematics).
Answer: Not a complete answer.
Firstly, it is not generally true that $\{ a \mid \text{some property of } a \}$ is a set: what if the property is $a \not\in a$? If then $b = \{ a \mid a \not\in a \}$ then is $b \in b$ true? This is called Russell's paradox. What is true (in some axiomatisations of set theory, for instance ZF) is that if $c$ is a set then $\{ a \in c \mid \text{some property of } a \}$ is a set (this is called the axiom of separation, or comprehension).
Your first formalisation of the set describing the function $f \colon x \mapsto 2x^2 + 3$ is correct; the second one is not. The quantifier $\exists x$ only binds instances of $x$ in the next "rank" of the formula: $\exists x (\varphi(x))$ is fine, but $\exists x(\varphi(x)) \land \psi(x)$ is not; the instance of $x$ in $\psi(x)$ is free, i.e. not bound. In fact, since variables can be relabelled, the formulas $$\exists x(\varphi(x)) \land \psi(x)$$ and $$\exists x(\varphi(x)) \land \psi(t)$$ are logically equivalent.
I am not certain what you mean by "formalising" that last statement; it is, after all, already expressed in the formal language. I'll update this once OP clarifies.
Comment: Thanks. What I meant though was that every set is of this form, not that everything of this form is a set, which should be correct, shouldn't it? What I meant by formalising was stating the formula as formally as possible, for example by defining predicates accordingly.
Answer: A long comment:

In set theory, a function $f:A \to B$ is defined as a subset
$f\subseteq A \times B$ such that $\forall x \in A(\exists!y \in B((x,y)\in f))$

Another commonly used definition of a function in mathematics:
Suppose $A$, $B$ and $G$ are sets such that

$G\subset A\times B $
$\forall x\in A: \exists!y\in B: (x,y)\in G$

Then we can define a function $f$ such that
$\forall x,y: [x\in A \land y\in B \implies [y=f(x) \iff (x,y)\in G]] $
Here, $G$ is called the graph of $f$.
This form of the definition has the advantage that it cannot be applied for elements outside the domain $(A)$ of the function $f$ here. For those elements, we say that $f$ is undefined.
Why is this important? Consider the reciprocal function on the real numbers. We need to distinguish between, for example, $1/2=3$ being false and the truth value of $1/ 0 =3$ being undefined on the real numbers. The definition of the reciprocal function on the reals simply cannot be used to determine its truth value of $1/0=3$ since $0$ is not in its domain.


JavaScript ES6 in super function stop sub function

Question: So I was wondering if this is possible.  I want the super() function to stop the sub() from continuing.
class Parent(){
   foo(){
        //Stop command that stops the code here.
   }
}

class Child extends Parent{
   foo(){
        super().foo();
        //this code should not run
   }
}

I know I can have the parent return false and test for it, but then all my children would have to test for it.  One of the reasons to use inheritance is to move common code to the parents.  I don't think this is possible (or even advised) but I was just wondering.
Comment: Throw an exception?
Comment: Please specify your use case. If you want to stop execution on errors, just throwing an exception should do the trick. Otherwise, probably you are using a bad coding pattern.
Comment: What if you pass the Child logic as a parameter to the Parent? Then you could do the checking inside the parent class and determine if/when to run the child code? Example: `foo(func) => { ... }` called like `super.foo(() => { ..child logic..});`
Answer: why you are not call direct parent class method using __proto__
class Parent{
   foo(){
        //Stop command that stops the code here.
   }
}

class Child extends Parent{
   foo(){
        super.foo();
        //this code should not run
   }
}

var c = new Child();
c.__proto__.__proto__.foo();

Comment: a) because `__proto__` is deprecated b) because that doesn't call a method on the `c` instance


Spring JPA repository locking confusion

Question: I have some confusion on the way the locking on Spring JPA repository works and needs some clarification on same.
So, I have a Spring boot service in which i am using hibernate to interact with database.
In one of the service i have an Entity like this :-
    @Entity
    @Table(name="JUNIPER_SCH_CURRENT_JOB_DETAIL", schema="juniperx")
    public class JuniperSchCurrentJobDetail {

    private int currentJobSequence;

        ......

    @Id
    @GeneratedValue(strategy=GenerationType.SEQUENCE)
    @Column(name="CURRENT_JOB_SEQUENCE")
    public int getCurrentJobSequence() {
    return currentJobSequence;
    }
    public void setCurrentJobSequence(int currentJobSequence) {
    this.currentJobSequence = currentJobSequence;
    }
    .......

Now i have a repository on top of this marked as @Repository and extending JPARepository as below :
   @Repository
   public interface JuniperSchCurrentJobDetailRepository extends
   JpaRepository<JuniperSchCurrentJobDetail, String> {

   @Query
   public List<Object[]> findLastRunJobDetail(@Param("projectId")
    String projectId);

So the confusion is that one of my colleague told me not to use @Repository and @Entity for this table as the table being referred to has very high rate of inserts and updates from other application. And using JPA repository will lock this table and cause issue.
So my query is :-
1) In this microservice i am using only select queries on this table, So will the select query also lock this table?
2) From what i read if i use optimistic lock it will enable a lock only when committing a transaction but since this microservice is only reading the data will it still effect other services which are making inserts and updates in this table?
3) In case the locking part is true is there anyway to stop the locking?
4) I am ok with reading dirty data in this microservice as it is for populating a dashboard which is not realtime, So is it ok to continue using @repository or should i change it to JDBC template to avoid locking problem?
5) Will annotating the class with @NoRepositoryBean and creating a read only repository help?
Comment: It won't help. The annotation is just completely redundant. That's why I made it a comment not an answer.
Comment: You don't need the `@Repository` annotation on the repository interface.
Comment: How will that help? Sorry but needed a bit insight.
Also will that solve the locking issue?
Answer:
will the select query also lock this table?
this microservice is only reading the data will it still effect other services which are making inserts and updates in this table?

Some databases will create locks on tables when reading from them.
This however is completely independent from JPA and highly database specific.
You'd need to look into the specific database you are using to learn how it behaves.
Writes will generally create locks, at least for the row you are writing, but also for rows that get referenced via foreign keys.
Some database might lock more rows than they actually write to.
Again this is true if you use JPA, JDBC or any SQL tool of your choice.

From what i read if i use optimistic lock it will enable a lock only when committing a transaction

No, optimistic locking won't create any additional (blocking) locks beyond the ones mentioned above.
It might though make updates fail when between reading and writing a row another update happened.
Actually the purpose of optimistic locking is to prevent lost updates without blocking writes (and possibly reads).
In summary I don't see how JPA would in its default configuration would generate more locks than using something more low level like the JdbcTemplate.
Comment: So this should not affect other application doing inserts and updates just because i am using JPARepository....?

Spring JPA repository locking confusion


Homogeneous generators of a homogeneous ideal

Question: Let $k$ be an algebraically closed field, and $I\subset k[x_0,\cdots,x_n]$ a homogeneous ideal of height $r$. If $I$ can be generated by $r$ elements, can we pick $r$ homogeneous elements in $I$ that generate $I$?
Background: Let $Y=V_+(I)$ be the corresponding closed subscheme. $Y$ is called a complete intersection if $I$ can be generated by $r$ elements. But it sounds weird to me, since it doesn't ask the generators to be homogeneous, which is not convenient to consider their corresponding hypersurfaces. So I guess we may choose $r$ homogeneous generators for $I$.
Could you provide some help?(prove it or give an counterexample) Thanks!
Comment: Dear Richard, in both this and your [other question posted recently](https://math.stackexchange.com/questions/4329123/), you've left out quite a bit of context and have posted essentially just the statement of the problem. This is a bit disappointing after you showed some good effort at avoiding this [in our previous interaction](https://math.stackexchange.com/questions/4312847/). Please make some edits to improve your posts.
Comment: @KReiser Thanks for pointing out. I have already edited them. By the way, I saw you posted an answer to this question but I havn't read it in detail since not convenient. Do you have any ideas on this problem?  I'd like to learn it if you are willing to share your ideas.
Comment: (for some $j$) $I$ (assumed to be prime) will be the homogeneization of $J$ the height $r$ ideal of $k[x_1,\ldots,x_n]$ obtained by sending $x_j$ to $1$. That $J$ is generated by $r$ polynomials, its homogeneization $I'$ is generated by $r$ homogeneous polynomials, $V(I')=V(I)$, and it remains to check that $I'$ is prime.
Comment: Thank you for improving your wishing. I've restored my answer below.
Answer: Suppose $I$ is generated by $r$ elements.
Let $\{f_s\}_{s\in S}$ be a minimal system of homogeneous generators for $I$.
Any relation $\sum g_sf_s=0$ among the $f_s$ must have $g_s\in(x_0,\cdots,x_n)$: if some $g_{s_0}$ has a nonzero constant term, then looking at the $\deg f_{s_0}$ component of the equation, we see that $f_{s_0}$ is in the ideal generated by the other $f_s$ involved.
Now define $I\to k^{\oplus S}$ by $\sum g_sf_s=(g_s(0))_{s\in S}$: this is surjective and does not depend on the representation of an element as $\sum g_sf_s$ by the previous sentence.
This implies that $k^{\oplus S}$ can be generated by $r$ elements, or $r\geq |S|$.
Since every generating set of $I$ must have at least $\operatorname{ht} Y$ elements, we see that $I$ can indeed be generated by $r$ homogeneous elements.


Diminuir colunas ChartJs Bar Chart

Question: Alguém sabe como posso trabalhar com o tamanho e largura das colunas azuis dentro do gráfico Bar Chart do Chartjs?
Segue imagem exemplo.

Gostaria de deixar as colunas mais finas e mais distantes umas das outras.....
Comment: da uma olhada aqui na documentação da configuração dele mesmo http://www.chartjs.org/docs/#bar-chart-chart-options, caso não tenha da uma olhada na configuração geral http://www.chartjs.org/docs/#getting-started-global-chart-configuration
Comment: Eu não consegui encontrar algo semelhante na documentação.. Mas obrigado por enquanto. Se alguém tiver mais alguma ideia, fico agradecido
Answer: O que foi possível que encontrei na documentação foi mexer na opção do xAxes.
<code>options: {
    scales: {
        xAxes: [{
          categoryPercentage: 0.9,
          barPercentage: 0.7
      }],
      ...
    }
</code>
como pode ser visto nesse exemplo https://jsfiddle.net/smw9949v/1/ alterando os valores entre 0 - 1.
Espero que ajude no que precisa.
Comment: Parece funcionar bem, porém, em meu gráfico não está ocorrendo com sucesso. Vou dar mais uma pesquisada, muito obrigado
Comment: qq coisa da uma olhada nesse http://jsfiddle.net/beehe4eg/ , não sei se tem a ver com versão, mas nesse caso ele usa `categorySpacing`

Diminuir colunas ChartJs Bar Chart


Math.Random always setting random number to 0

Question: Creating a program where a random number is generated using math.random which i have put into a function and called this function in the program to make things tidier but the random number that gets outputted is always what the integer secret_number is set to, and i am not sure how to fix this to create a random number. I would like to keep the math.random in the function and use parameters
package guessinggame3;
import java.util.Scanner; //imports scanner to read from keyboard
import java.util.ArrayList;

public class GuessingGame3 { //start of public class

static Scanner kboard = new Scanner(System.in); //calls scanner

public static void main(String args[]) //start of main
{

System.out.println("Welcome to the guessing game, the computer will
generate a random number that you have to guess, good luck!"); //opening
message explaining how to play

int secret_number = 0;
int number_of_guesses = 0;
int user_guess ;
ArrayList<Integer> entered_numbers = new ArrayList<Integer>();

generate_random_number(secret_number); //calls he function
generate_random_number to say the random number has been generated

for(int i=0; i<20;i++) { // start of for loop sets user attempts to 20

System.out.println("Please make your guess"); //asks user to enter make
their guess
user_guess = kboard.nextInt();
number_of_guesses++; // adds on to the counter after each user guess

if(entered_numbers.contains(user_guess)) //checks if entered number =
number stored in array
{
System.out.println("You have already entered this number"); //displays
error message if user enters same number again
continue;
}

else
{
entered_numbers.add(user_guess);
if (user_guess == secret_number)
System.out.println("Your guess is corret you win!");
}

if (user_guess < secret_number)
{
System.out.println("Guess is too low");
}

if (user_guess > secret_number)
{
System.out.println("Your guess is too high");
}

System.out.println (20 - number_of_guesses + " Guesses remaining");
//Tells the user how many guesses they have remaining

} //end of for loop

} //end of main

static void generate_random_number(int secret_number)  //start of function
generate_random_number function passing secret_number as a parameter
{
secret_number = (int)(Math.random()*100) + 1; //generates random number
between 0 and 100
System.out.println("The computer has generated it's number"); //lets the
user know that the random number has been generated
} //end of function generate_random_number

} //end of public class
Comment: Reassigning a parameter's value doesn't change its value at the call-site, Java doesn't work that way
Comment: Please lose all those useless comments.  They are clutter that makes your code harder to read without adding useful information.
Comment: The new programmer is unlikely to understand why pass by value matters here.  A better suggestion is to change the method signature to public int generateSecretNumber() { return (int) (Math.random()*100.0); }
Answer: When you pass secret_number to the function generate_random_number, secret_number is copied. Thus, when you assign secret_number to (int)(Math.random()*100) + 1 inside your function, you are just changing its copy.
Answer: You should change your methods return type to int.
Change your method like this:
static int generate_random_number(int secret_number)

And in the main function set your secret_number to the value that method returns
secret_number = generate_random_number(secret_number);

You should also add return value for your method so it should be like this:
static int generate_random_number(int secret_number){
    secret_number = (int)(Math.random()*100) + 1;
    System.out.println("The computer has generated it's number");
    return secret_number;
}

Comment: Thanks for the comment but now i get an error saying secret_number has not been initialized and the method must return a type of int?
Comment: I think you changed the wrong lines. Keep `int secret_number = 0;`  the same, change `generate_random_number(secret_number);` with `secret_number = generate_random_number(secret_number);`
Comment: And also add `return secret_number;` at the end of your `generate_random_number` method, sorry i forgot to add that
Comment: Thank you for the help this has fixed my problem :)


Git on Amazon Server

Question: I have git running on an Amazon server and up til now I have been the only one to use the server. I use my Amazon ssh key to connect and am then connected as root on the server without the need for any username and password.
Now, a second user needs access to the git repository, but I don't want this person to have root access to the machine as I have many other services running there. How can I grant them just access to the git files? Can I do it without needing to give them the ssh private key?
EDIT: After a lot of problems, I had luck generating the key on Amazon - not optimal but I need to get working: http://utkarshsengar.com/2011/01/manage-multiple-accounts-on-1-amazon-ec2-instance/
Answer: Create a new user account for them, set group membership and ownership/permissions such that they have read/write access to the repo. Have the user generate their own key pair, and then deploy their public key to the server.
Comment: Thanks. How do I associate that user to that public key so that when they login they log in as that user?
Comment: They supply their username, and you've previously added their public key to their account. These two steps are very rudimentary Linux sysadmin, and you should look for guides elsewhere if you need assistance with them.

Git on Amazon Server


Anyone know where I can download a copy of Sun Java System Active Server Pages 4.0.3 for Solaris

Question: I've contacted Sun regarding this and they have told me that the download is no longer available as Active Server Pages 4.0.3 is now End Of Life. We need to upgrade our server to 4.0.3 to acheive PCI-DSS compliance.
Anyone know of a site where I can download older copies of Sun files? Sun offer 4.0.1 and 4.0.2 to download but not 4.0.3 which is going to cause problems come October when Visa stops accepting transactions from non PCI compliant servers.
If Sun kept their naming system consistent across versions, the file would be called "sjsasp403-sol-sparc.tar". I know the real solution is to upgrade every site on the server to use a different server language, i.e. PHP, and in the long term, this is our goal but we have over 100 sites requiring upgrading and its not a viable solution to get this done before October.
Answer: Google found this: 4.0.3 Download when I searched for

sun active server pages  4.0.3 download

HTH
Comment: that's just the zipped documentation for it. cheers tho. i spoke to a guy at sun today and if i can get a copy, i'll let people know how if needed.
Answer: I've managed to source a copy of the download off a contact of mine. If anyone needs it, get in touch via my personal site.


SQL AVG Salary recursive Query

Question: in the first Query I get the staffs who leads other staff
and in the second I wanne get the avg salary of staffs who earns more than the avarage. But I wanne combine both to get the managers who earns more than twice of the salary than the avg salary of the staffs who works for them.
SELECT   c.EmpID,c.name,c.gender,c.salary,c.supervisorFK,c.branchFK,c.position
FROM     staff c  INNER JOIN staff u ON c.EmpID = u.supervisorFk
GROUP BY c.EmpID,c.name,c.gender, c.salary, c.branchFK,c.supervisorFK,c.position

select name, salary, avg_salary
from staff
join (select avg(salary) avg_salary from staff) x
  on salary > avg_salary

I tried this:
SELECT   c.EmpID,c.name,c.gender,c.salary,c.supervisorFK,c.branchFK,c.position
FROM     staff c  INNER JOIN staff u ON c.EmpID = u.supervisorFk
 join (select avg(salary) avg_salary from staff) x
  on  c.salary*2 > avg_salary
GROUP BY c.EmpID,c.name,c.gender, c.salary, c.branchFK,c.supervisorFK,c.position

I get 31 hits which cannot be. Where is the mistake?
I could not find any related questions. Some of my queries I took from other questions.
Thanks
source data:
insert into Staff values ( 1, 'Robert King'      ,'M', 143000.0,NULL, 'B002', 'Director');
insert into Staff values ( 2, 'Rafael McDonalds' ,'M',  72000.0, 1,'B001', 'Manager');
insert into Staff values ( 3, 'John White'       ,'M',  60000.0, 1,'B003', 'Manager');
insert into Staff values ( 4, 'Susan Brand'      ,'F',  55000.0, 1,'B004', 'Manager');
insert into Staff values ( 5, 'Cathy Brown'      ,'F',  32000.0, 2,'B001', 'Supervisor');
insert into Staff values ( 6, 'Claire Dujeune'   ,'F',  79000.0, 1,'B010', 'Manager');
insert into Staff values ( 7, 'Patty Summer'     ,'F',  23000.0, 2,'B001', 'Supervisor');
insert into Staff values ( 8, 'Mary Fleming'     ,'F',  43000.0, 1,'B011', 'Manager');
insert into Staff values (10, 'Anne Beech'       ,'F',  26000.0, 5,'B001', 'Assistant');
insert into Staff values (12, 'Paul Coplien'     ,'M',  27000.0, 3,'B003', 'Supervisor');
insert into Staff values (13, 'David Ford'       ,'M',  41000.0, 1,'B012', 'Manager');
insert into Staff values (14, 'Mary Howe'        ,'F',  55000.0, 1,'B005', 'Manager');
insert into Staff values (15, 'Julie Lee'        ,'F',  34000.0, 3,'B003', 'Supervisor');
insert into Staff values (16, 'Aaron Young'      ,'M',  74000.0, 1,'B013', 'Manager');
insert into Staff values (17, 'Albert Thomson'   ,'M',  25000.0,13,'B012', 'Supervisor');
insert into Staff values (21, 'Alexander Reynolds','M', 37000.0, 5,'B001', 'Assistant');
insert into Staff values (18, 'Christine McDonalds','F',38000.0, 4,'B004', 'Supervisor');
insert into Staff values (19, 'Elisa Pinkerton'  ,'F',  36000.0,16,'B013', 'Supervisor');
insert into Staff values (20, 'Eric Montgomery'  ,'M',  33000.0, 7,'B001', 'Assistant');
insert into Staff values (22, 'Edward Robinson'  ,'M',  28000.0, 7,'B001', 'Assistant');
insert into Staff values (23, 'Jesse Owens'      ,'M',  34000.0, 4,'B004', 'Supervisor');
insert into Staff values (25, 'Johnatan Hunter'  ,'M',  45000.0, 1,'B014', 'Manager');
insert into Staff values (26, 'Lenita Kennedy'   ,'F',  56000.0, 1,'B009', 'Manager');
insert into Staff values (27, 'Lisa Miller'      ,'F',  34000.0,25,'B014', 'Supervisor');
insert into Staff values (28, 'Lilly Jennings'   ,'F',  36000.0,14,'B005', 'Supervisor');
insert into Staff values (29, 'Rafaela Johnson'  ,'F',  23000.0,12,'B003', 'Assistant');
insert into Staff values (32, 'Harry Anderson'   ,'M',  40000.0,12,'B003', 'Assistant');
insert into Staff values (33, 'George Bailey'    ,'M',  73000.0, 1,'B006', 'Manager');
insert into Staff values (34, 'Salomon Beckett'  ,'M',  46000.0, 1,'B008', 'Manager');
insert into Staff values (35, 'Susan Armstrong'  ,'F',  28000.0,15,'B003', 'Assistant');
insert into Staff values (36, 'Rosa Hemingway'   ,'F',  30000.0,15,'B003', 'Assistant');
insert into Staff values (37, 'Martha McDonalds' ,'F',  31000.0,15,'B003', 'Assistant');
insert into Staff values (38, 'Anna-Isabell Green','F', 32000.0,33,'B006', 'Supervisor');
insert into Staff values (39, 'Tina Hall-Becker' ,'F',  34000.0,18,'B004', 'Assistant');
insert into Staff values (40, 'Thomas Harrison'  ,'M',  42000.0, 1,'B007', 'Manager');
insert into Staff values (42, 'Winston Hughes'   ,'M',  22000.0,40,'B007', 'Supervisor');
insert into Staff values (44, 'Walter Jefferson' ,'M',  23000.0,18,'B004', 'Assistant');
insert into Staff values (45, 'Zara Newton'      ,'F',  24000.0,23,'B004', 'Assistant');
insert into Staff values (46, 'Nina McDonalds'   ,'F',  25000.0,23,'B004', 'Assistant');
insert into Staff values (48, 'Carol Moore'      ,'M',  27000.0,40,'B007', 'Supervisor');
insert into Staff values (51, 'Alexander Porter' ,'M',  29000.0,17,'B012', 'Assistant');
insert into Staff values (52, 'Maria Quasimodo'  ,'M',  30000.0,17,'B012', 'Assistant');
insert into Staff values (53, 'Bertrand Russel'  ,'M',  31000.0,34,'B008', 'Supervisor');
insert into Staff values (54, 'Ashley Parker'    ,'M',  25500.0,28,'B005', 'Assistant');
insert into Staff values (55, 'John Stuart'      ,'M',  23500.0,28,'B005', 'Assistant');
insert into Staff values (56, 'Ruth Sanderss'    ,'F',  27700.0,19,'B013', 'Assistant');
insert into Staff values (57, 'Rafael Smith'     ,'M',  32000.0,19,'B013', 'Assistant');
insert into Staff values (58, 'Viola Rutherford' ,'F',  21000.0,27,'B014', 'Assistant');
insert into Staff values (59, 'Sammy Churchill'  ,'M',  22000.0,27,'B014', 'Assistant');
insert into Staff values (60, 'Miriam Thorne'    ,'F',  26000.0,27,'B014', 'Assistant');
insert into Staff values (61, 'Sally Thatcher'   ,'F',  36000.0,34,'B008', 'Supervisor');
insert into Staff values (62, 'Larry Escott'     ,'M',  33000.0,26,'B009', 'Supervisor');
insert into Staff values (63, 'William Spencer'  ,'M',  32000.0, 6,'B010', 'Supervisor');
insert into Staff values (64, 'Diana Ashley-Bell','F',  38000.0, 8,'B011', 'Supervisor');
insert into Staff values (65, 'Audrey Thorne'    ,'F',  25000.0,62,'B009', 'Assistant');
insert into Staff values (66, 'Paula Burns'      ,'F',  24000.0,62,'B002', 'Assistant');
insert into Staff values (67, 'Amanda Wallis'    ,'F',  23000.0,38,'B006', 'Assistant');
insert into Staff values (68, 'Patty Stokes'     ,'F',  22000.0,53,'B008', 'Assistant');
insert into Staff values (69, 'Holly Fields'     ,'F',  21500.0,53,'B008', 'Assistant');
insert into Staff values (70, 'Martha McCulloch' ,'F',  26000.0,61,'B008', 'Assistant');
insert into Staff values (71, 'Maurin Best'      ,'F',  22500.0,42,'B007', 'Assistant');
insert into Staff values (72, 'Martha McDonalds' ,'F',  23500.0,27,'B014', 'Assistant');
insert into Staff values (73, 'Barrigan' ,NULL,  23500.0,27,'B013', 'Assistant');
insert into Staff values (47, 'Naomi Campell'    ,'F',  26000.0,63,'B010', 'Assistant');
insert into Staff values (49, 'Tony McDonalds'   ,'M',  28000.0,63,'B010', 'Assistant');
insert into Staff values (50, 'Margret McElroy'  ,'F',  29000.0,64,'B011', 'Assistant');
insert into Staff values ( 9, 'Carl Maier'       ,'M',  31000.0,64,'B011', 'Assistant');

Create table STaff:
CREATE TABLE Staff (
EmpID int,
name varchar(30) NOT NULL,
gender char(1)  NULL
CHECK (gender in ('M','F')),
salary decimal(7,1) NOT NULL,
supervisorFK int NULL,
branchFK char(4) NOT NULL,
position char(10)
CHECK (position in ('Director','Manager','Supervisor','Assistant')),

PRIMARY KEY (EmpID)
);

Comment: Tag your question with the database you are using.
Comment: code to create the table would be nice
Comment: added the create table code
Answer: You are selecting the managers that earn more than half of the average.
on  c.salary*2 > avg_salary

Should be:
on  c.salary/2 > avg_salary

Or
on  c.salary > avg_salary * 2

Comment: Thanks this is great I was so busy with the query syntax just forgot to check the logic behind the query :)

SQL AVG Salary recursive Query


Can't do POST requests with Polymer's core-ajax

Question: This is what I have:

Polymer('my-element', {
  created: function() {
    this.data = {
      name: 'John Doe',
      email: 'email@example.com'
    };
  },

  handleResponse: function(e, d) {
    console.log(d.response);
  }
});
<core-ajax
           id="ajax"
           auto
           url="/test"
           method="POST"
           handleAs="json"
           body="{{data}}"
           on-core-response="{{handleResponse"}}>
</core-ajax>

And I have a server set up to return the body of the POST message when the user posts to /test.
app.post('/test', function(req, res) {
    res.json(req.body);
}

However, this is what I get as response on the console:
Object {object Object: ""}
Answer: core ajax all data you want to get with post must be sent with params attribute not body attribute.
that would make your core ajax tag look like
<core-ajax
       id="ajax"
       auto
       url="/test"
       method="POST"
       handleAs="json"
       params="{{data}}"
       on-core-response="{{handleResponse"}}>
</core-ajax>

that would allow you to catch the data like normal in node
app.post('/test', function(req, res) {
  res.json(req.body);
}

it is confusing cause in node you think of params as get data and body as post data but this doesn't matter with core ajax. all data get or post is sent with the params attribute.
Comment: Thanks for the answer! But, then, what do I use the body attribute for?
Comment: the docs say body = "Optional raw body content to send when method === "POST"." so  idk actually i have been a little confused by it myself. the data can be used when sent in body attribute. i am not sure how in node but with php you can use  $post = file_get_contents("php://input"); and get the data but you have to json_decode or parse in another manner to actually use it.
Answer: This looks like core-ajax performs the AJAX call before this.data in ready.
Try 'manuel' AJAX request initiation, i.e. ajax.go()
Do this inside:
 created: function() {
    this.data = {
       name: 'John Doe',
       email: 'firstname.lastname@example.com'
     };
    var respuesta = this.$.ajax;
    console.log(respuesta);
    respuesta.go();
},

Example Plunk


Doubt about a simple conditional probability problem

Question: I am having some trouble with this probability problem.
In a presidential election, exit polls from Washington State provided the following results:
<code>                            John        Bush
Not Employee(65%)           32%         68%
Employee(35%)               61%         39%
</code>
If a randomly selected respondent voted for John, what is the probability that this person is an employee?
I thought of it as a conditional probability, where E denotes Employee, and J denotes John's votes. So P(E|J). And I found to be P(E|J)=P(EnJ)/P(J), where P(J)= The sum of the numbers in John's column; 32%+61%=93%=0.93
So P(E|J)=0.61/0.93=0.656.
Is this a correct solution? And what did I understand wrong?
Answer: What you are given is this: E = employee, N = non-employee, and P(J/N) = .32, P(B/N) = .68, P(J/E) = .61, P(B/E) = .39, P(E) = .35, and P(N) = .65. So you are to calculate: P(E/J). We use Bayes' rule to find the answer. Namely:
P(E/J)*P(J) = P(J/E)*P(E) ===> P(E/J) = P(J/E)*P(E)/P(J) =
= P(J/E)*P(E)/(P(J/E)*P(E) + P(J/N)P(N)) = (.61)(.35)/(.61*.35 + .32*.65) = .506
Answer: You have the formula correct, but are misreading the table. Notice that the numbers in each row adds to 100%, but the numbers in the columns do not. Also, notice the percentages in the labels for Not Employees and Employees, respectively.
What you need to do is create a table that expresses the probability of each combination.
John     Bush
0.208    0.442 | 0.65 (Not Employee)
0.2135   0.1365| 0.35 (Employee)

0.4215   0.5785| 1.00
I think that is correct. Now you can do your calculation.


VBA Excel: How to jump 1 Cell to the right in my Loop?

Question: I am trying to loop trough a huge excel document. The part that matters here is shown on the picture:

in the first column we have the working hours. the second column tells me how many full working days(8.2 hours per day). the third column tells me how many hours are left from the calculation of the full working days.
Now what i have to do with my code:
I search the corresponding cell to the date in the date-column. then i fill in the working-hours per day.
Ill show you my code first:
<code>    Dim zelle_Start As String, zelle_End As String
    Dim full_Days As String, rest_hours As String
    Dim Date1 As Date
    Dim rngCell As Range, rngZelle As Range
    Dim i As Long
    Dim Destination As String

    For i = 14 To ActiveSheet.Cells(1816, 7).End(xlUp).Row
        full_Days = ActiveSheet.Cells(i, 8)
        rest_hours = ActiveSheet.Cells(i, 9)
        Date1 = ActiveSheet.Cells(i, 10)

        Set rngCell = Rows(9).Find(Date1, lookat:=xlWhole, LookIn:=xlFormulas)
        If Not rngCell Is Nothing Then
            Destination = rngCell.Address
        End If

        Destination = Replace(Destination, "9", i)

        ActiveSheet.Range(Destination).Select

        'Heres my Problem!
        For Days = 1 To full_Days
            Range(Destination).Value = "8.2"

        Next Days

    Next i
</code>
My problem is the "for loop" to fill in the working hours per day. How can i jump one cell to the right in the same line with every loop??
Basically i should look like the line where there is this red cell, its the example line(values are wrong) :)
I hope somebody has a good advice for me.
Comment: Have you looked at [the `Range.Offset` property](https://learn.microsoft.com/en-us/office/vba/api/excel.range.offset)?
Answer: The Solution was the Range.Offset Property..
Just one easy line of code does the desired jump to the right.
<code>Range(Destination).Offset(rowOffset:=0, columnOffset:=1).Select
</code>
Thanks for the hint!


$\operatorname{Hom}_A(K,A)\neq0$ iff $A=K$

Question: I can prove this result in one way that is if $A=K$. Then there exists a natural morphism from $K$ to $K$. But I have no idea how to prove the converse part. I am new to this course please help by providing a good explanation.
Here A is integral domain and K is quotient field.
Comment: That should be explicitly stated in the body of the question, not in a comment. I assume further $A$ is a subring of $K$, else you cannot speak of $Hom_A$.
Answer: Suppose that we have a non-zero $A$-module morphism $\phi : K \to A$. Notice that $\phi (1) \neq 0$ (because otherwise $\phi = 0$). We have $\phi (1) \phi (\frac{1}{\phi (1)}) = \phi (\phi (1) \cdot \frac{1}{\phi (1)}) = \phi (1)$ and therefore $\phi (\frac{1}{\phi (1)}) = 1$.
Let $0 \neq a \in A$. We want to show that $a$ has an inverse in $A$. We have $ a \phi (\frac{1}{\phi (1)a}) = \phi (a \cdot \frac{1}{\phi (1) a}) = \phi (\frac{1}{\phi (1)}) = 1$ and therefore $a$ has an inverse in $A$.


Show that $\{\alpha<\omega_1 : L_\alpha \prec L_{\omega_1}\}$ is closed unbounded in $\omega_1$.

Question: I was doing this exercise and there is a hint to consider the Skolem functions for $L_{\omega_1}$. However, I did not find any general definition of what a Skolem function may be in Kunen (1980), and I do not know how to proceed with this hint. Any help in clarification or hint in another directions would be appreciated. Thank you.
Answer: You can use Skolem functions to do this, but they're not necessary. Here's an argument I like:
First, I claim that it's enough to show unboundedness. We get this by applying two results, namely the coherence of elementary embeddings ($A\preccurlyeq C$, $B\preccurlyeq C$, and $A\subseteq B$ implies $A\preccurlyeq B$), and the nice behavior of elementary chains (if $A_i\preccurlyeq A_j\preccurlyeq C$ for $i<j<\lambda$ with $\lambda$ a limit ordinal then $A_i\preccurlyeq \bigcup_{i<\lambda}A_i\preccurlyeq C$ for all $i<\lambda$). Putting this all together we get that if $\alpha$ is  a limit of $\{\beta: L_\beta\preccurlyeq L_{\omega_1}\}$ then $\alpha$ is in fact in that set.
Moreover, unboundedness itself is really all about constructing a single example with a parameter: it's enough to show that for each $a\in L_{\omega_1}$ there is an $\alpha$ such that $a\in L_\alpha\preccurlyeq L_{\omega_1}$. (Do you see why?)
So fix $a\in L_{\omega_1}$. By downward Lowenheim-Skolem we get an $M\preccurlyeq L_{\omega_1}$ with $a\in M$. Of course $M$ probably is not a level of $L$, so we aren't done yet. Instead we're going to build a sequence of structures:

$M_0=M$.

$M_{2i+1}=L_{M_{2i}\cap \mathsf{Ord}}$.

$M_{2i+2}$ is any countable elementary substructure $N$ of $L_{\omega_1}$ such that $M_{2i+1}\subseteq N$.

Basically, at odd steps we "fill in the gaps" and at even steps we "re-attain elementarity." Crucially, the even steps require the observation that $L_\alpha$ is countable whenever $\alpha$ is; this is where this argument would break down if we tried to run it for the $V$-hierarchy instead. It's a good exercise to check that no $V_\alpha$ is a proper elementary substructure of $V_{\omega_1}$:

 Already in $V_{\omega+1}$ we have elements "coding" all the countable ordinals, so $V_{\omega_1}$ will be the first level of the $V$-hierarchy after $\omega+1$ to satisfy "every countable well-order is isomorphic to some ordinal."

Now let $M_\omega=\bigcup_{i\in\omega}M_i$. We clearly have that $M_\omega$ is a countable substructure of $L_{\omega_1}$ containing $a$ as an element; moreover, as a union of levels of $L$ it is itself a level of $L$, and as a union of elementary substructures of $L_{\omega_1}$ it is itself an elementary substructure of $L_{\omega_1}$. So we're done!
Answer: For a route more similar to what Kunen is suggesting, proceed like the proof of the reflection theorem.
Let $\alpha < \omega_1.$ For a formula $\varphi(x,\vec y)$ and $\vec y \in L_\alpha,$ let $F(\alpha, \varphi, \vec y)$ be the least ordinal $\beta >\alpha$ such that there is an $x\in L_\beta$ with $L_{\omega_1}\models \varphi(x,\vec y)$ if there is any such $x\in L_{\omega_1},$ otherwise let $F(\alpha, \varphi, \vec y)=0.$ Define $$\alpha' = \sup\{F(\alpha, \varphi,\vec y): \varphi\in Form, \vec y\in L_\alpha\}.$$ Since there are countably many $\vec y$ and $\varphi,$ we have $\alpha'<\omega_1.$
Then, given an arbitrary $\alpha< \omega_1,$ let $\alpha_0 = \alpha$ and recursively let $\alpha_{n+1}= \alpha_n'$ and $\alpha^* = \lim_n \alpha_n.$
By the Tarski-Vaught test, $L_{\alpha^*}\prec L_{\omega_1}.$ Thus, the set in question is unbounded. Closure follows easily, as Noah mentions in his answer, since an increasing union of elementary submodels is an elementary submodel.


what is the usage of PTHREAD_CREATE_JOINABLE in pthread?

Question: I read some codes as below:
void
mcachefs_file_start_thread()
{
  pthread_attr_t attrs;
  pthread_attr_init(&attrs);
  pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_JOINABLE);
  pthread_create(&mcachefs_file_threadid, &attrs, mcachefs_file_thread, NULL);
}

Here, what is the usage of setting attrs as PTHREAD_CREATE_JOINABLE? Besides, isn't it the default attribute of a thread created by pthead_create?
Answer: Yes, PTHREAD_CREATE_JOINABLE is the default attribute. The purpose is that it allows you to call pthread_join on the thread, which is a function that waits until the thread finishes, and gives you return value if its main routine.
Sometimes, when you're creating a thread to do some background work, it might be a good idea to make sure it has finished before you use its results or move to something else. That's what joinable threads are for.
Comment: +1 for being accurate, though I prefer a different explanation 'it's to allow you to easily lock up your app,  allow you to continually create/terminate/destroy threads in an uncontrolled manner, allow attempts at thread micro-management that will not work, reduce overall performance and prevent your app from shutting down promptly or, indeed, at all'.
Answer: From posix spec, the default setting of the detach state attribute in a newly initialized thread attributes object is indeed PTHREAD_CREATE_JOINABLE.
See for instance http://linux.die.net/man/3/pthread_attr_setdetachstate
So you are right: the pthread_attr_setdetachstate line of code is not necessary in your code snippet.


Custom View into a Toast - doesn't draw

Question: i'm trying to show a Toast message with a custom view i created.
the view has a bitmap on the background and i want to write some text on it.
if I assign the bitmap to an ImageView on the main code I manage to make it show up with Toast t; (...) t.show();
but when it's the onDraw() method of my class to assign the bitmap nothing shows up.
i checked, and my view has a size of (0, 0) when created the way i transcribe under.
help please.
Main.java
    Toast t = new Toast(this);
    LimitView lv = new LimitView(this);

    t.setView(lv);
    t.setDuration(Toast.LENGTH_LONG);
    t.show();

LimitView.java
public void onDraw(Canvas canvas)
{
    super.onDraw(canvas);

    canvas.save();

    canvas.setBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.limit));

    canvas.restore();
}

Comment: "but when it's the onDraw() method of my class to assign the bitmap nothing shows up". This part is not clear to me.
Comment: @Raghunandan: meaning it doesn't work as it is shown
Comment: you don't see the image
Comment: i already managed @Raghunandan. check Ȃŵåiṩ ĸîŋg solution
Answer: try this code:
Main.java
Context context = this;
Toast t = new Toast(context);
LeftBorder lv = new LimitView(context);
t.setView(lv);
t.setDuration(Toast.LENGTH_LONG);
t.show();

LimitView.java
public class LimitView extends View {
    public LimitView (Context context) {
        super(context);
    }

    protected void onDraw(Canvas canvas){
        super.onDraw(canvas);
        canvas.drawBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.button_pressed), getMatrix(), new Paint());
    }
}

Comment: what is the difference? and what is wrong with the code posted
Comment: **setBitmap** is used to draw mutable bitmap in canvas.
Comment: @Ȃŵåiṩĸîŋg i was asking why it won't work.

Babibu post cleared my doubt
Comment: ok :)
btw if you should select any one of answers as right answer.
Comment: ok... working.
as i'm using API7 getMatrix() is not available
used drawBitmap(bmp, 0.0f, 0.0f, new Paint())
Answer: There are several errors here.
BitmapFactory.decodeResource(getResources(), R.drawable.limit)

This is a heavy operation and should not be on view drawing phase.
canvas.setBitmap();

This method does not drawing bitmap on canvas but setting the canvas buffer to use this bitmap.
Try some thing like this:
public class MyView extends View{

    private Bitmap bitmap;

    public MyView(Context context) {
        super(context);
        bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.limit);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawBitmap(bitmap, 0, 0, null);
    }

}

Answer: replace this

canvas.setBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.limit));

to this:
canvas.drawBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.button_pressed),left,top, new Paint());

here left and right are the position of the screen.

Custom View into a Toast - doesn't draw


Beyond Fisher kernels

Question: For a while, it seemed like Fisher Kernels might become popular, as they seemed to be a way to construct kernels from probabilistic models. However, I've rarely seen them used in practice, and I have it on good authority that they tend not to work very well. They rely on the computation of the Fisher Information - quoting Wikipedia:

the Fisher information is the negative of the expectation of the second derivative with respect to θ of the natural logarithm of f. Information may be seen to be a measure of the "curvature" of the support curve near the maximum likelihood estimate (MLE) of θ.

As far as I can tell this means that the kernel function between two points is then the distance along this curved surface - am I right?
However this could be problematic for use in kernel methods, as

The MLE might be a very bad estimate for a given model
The curvature of the support curve around the MLE might not be any use for discriminating between instances, for example if the Likelihood surface was very peaked
This seems to throw away a lot of information about the model

If this is the case, are there any more modern ways of constructing kernels from probabilistic methods? For example, could we use a hold-out set to use MAP estimates in the same way? What other notions of distance or similarity from probabilistic methods could work to construct a (valid) kernel function?
Answer: You are right about the three issues you raise, and your interpretation is exactly right.
People have looked at other directions to build kernels from probabilistic models:

Moreno et al. propose Kullback-Leibler although when this satisfies Mercer's conditions was not well understood when I looked at this problem back when I read it.
Jebara et al. propose inner product in the space of distributions. This paper sounds a lot like what you're after: you can download it here.

I read them a while back (2008), not sure how that area has evolved the past few years.
There are also non-probabilistic ways to do so; people in Bioinformatics have looked at dynamic programming types of things in the space of strings and so on. These things are not always PSD and have problems of their own.
Comment: http://jmlr.org/papers/volume10/martins09a/martins09a.pdf develops some theory of kernels related to the KL divergence that are and aren't positive-definite.

Beyond Fisher kernels


TCL lsort not making sense for integers

Question: I am confused on what sorting algorithm lsort uses. I have a list of list (coordinate points) say:
set a { {142 250} {142 99} }

Then, lsort -uniq $a gives output: {142 250} {142 99}
and I was expecting it to be the other way round: {142 99} {142 250}
Please clear my confusion as what is going on here?
Answer: The sorting is that order because 142 250 is less than 142 99 according to the rules of string compare (the first 4 characters are the same, and the fifth is ordered that way). This is because lsort uses string comparison by default.
Your options are to either change the rule for selecting which part of each word in the list to use as the key (the default is to use the whole word) using -index, or to switch to a different comparison rule such as -dictionary or -integer.
set a { {142 250} {142 99} {142 -17} {142 0x1f} }
puts [lsort -integer -index 1 $a]
# ==> {142 -17} {142 0x1f} {142 99} {142 250}

set a { {142 250} {142 99} {142 -17} {142 0x1f} }
puts [lsort -dictionary $a]
# ==> {142 -17} {142 0x1f} {142 99} {142 250}

Be careful! Understand what these do before choosing one. (The -dictionary option is a "guess at how to sort things for people" rule that can surprise you if used for anything else. But it's brilliant for sorting things for showing to users.)
Answer: If you need to sort list by the second coordinate you can use this code
set a { {142 250} {142 99} }
lsort -integer -index 1 $a

By default, TCL see all as string. So, if need to sort as integer, you should explicitly specify it.
But if you need to sort your points by coordinates one by one (if X coordinates are equal -- sort by Y, if X and Y are equal -- sort by Z and so on), you need to use -command in lsort probably.
proc compare {a b} {
  foreach ai $a bi $b {
    if {$ai < $bi} {
        return -1
    } elseif {$ai > $bi} {
        return 1
    }
  }
  return 0
}
set a { {142 250} {153 99} {142 99}}
lsort -command compare $a
# >> {142 99} {142 250} {153 99}

set b { {142 250 12} {142 99 9} {153 99 1} {142 99 10}}
lsort -command compare $b
# >> {142 99 9} {142 99 10} {142 250 12} {153 99 1}

Answer: Tcl uses a stable sort algorithm. If you want a list of coordinate points to be sorted by their x-coordinate, and for equal x-coordinates by y-coordinate, you sort by y-coordinate first and then by x-coordinate.
You can't filter out duplicate coordinate points this way. If that is a requirement, then first perform an lsort -unique on the whole list (assuming the coordinate points are canonical lists all using the same number base). Beware that this does cause shimmering from list to string and back. So if you care about performance, you may want to remove duplicates using a different technique. This should be easy because after sorting, duplicates will be next to eachother.
set a { {142 250} {142 99} {83 250} }
puts [lsort -integer -index 0 [lsort -integer -index 1 $a]]
# ==> {83 250} {142 99} {142 250}

TCL lsort not making sense for integers


Converter um winform em webform

Question: Eu tenho uma aplicação em um winForms eu preciso transformar este projeto em um WebForm para aplicação web, estou buscando saber se é possível e existe alguma  maneira de fazer isso.
Comment: Bem-vindo ao StackOverflow em Português! Por favor explique melhor o problema, e se possível inclua um exemplo de código que reproduza o que está acontecendo (http://pt.stackoverflow.com/help/mcve), pois não está perceptível a sua pergunta. Veja na Central de Ajuda Como Perguntar (http://pt.stackoverflow.com/help/how-to-ask).
Comment: Como eu já disse, não é possível.
Comment: Ok, está editado!
Answer: Você vai precisar mudar (criar sua aplicação do zero como uma aplicação web) seguindo as regras que sua aplicação winForms tem.
Existem alguns tipos de aplicação para web como ( web Forms, mvc, "web api"), que você pode segui, muitas coisas mudam com isso, mas você pode abrir uma pergunta para cada duvida que tive em relação a isso.
Escolha o tipo de aplicação WEB que mais se encaixa com suas necessidades e siga os passos que o visual studio oferece para criação da aplicação, após isso e só seguir as regras que você tem na outra aplicação.
Não tem uma forma para converte sua aplicação WinForms para Web (que eu saiba).
Comment: pois é, acho que não tem jeito, vou ter que fazer isso mesmo, é que como eu comecei a mexer agora com c# e visual studio vai ser mais complicado, perguntei isso pra saber se tinha alguma forma mais "simples" de fazer, mas já que não tem.. mão na massa!! Valeu pela resposta!
Comment: Foi o que imaginei, veja pelo lado bom, vai aprender algumas coisas diferentes... como falei se tiver alguma duvida com algum método ou qualquer outra coisa da forma que é feito no `web forms` crie uma pergunta falando o que você tem como winforms e como ficaria em web forms. boa sorte :)
Comment: certo! Muito obrigada!

Converter um winform em webform


Loop group of U(1)

Question: The loop group of $U(1)$, $LU(1)$ is the space of maps from the circle, $S^1$ to $U(1)$. The based loop group of $U(1)$, $\Omega U(1)$ is the space of based maps from the circle, $S^1$ to $U(1)$. It is known that for a topological space X,
\begin{equation}
\pi_{n-1} (\Omega X)\cong \pi_n (X) .
\end{equation}
This implies that
\begin{equation}
\pi_{0} (\Omega U(1))\cong\pi_1 (U(1))\cong \mathbb{Z}  ,
\end{equation}
which means that $\Omega U(1)$ is not path connected.
Next, note that
\begin{equation}
LU(1)\cong\Omega U(1) \times U(1)
\end{equation}
(as spaces, not topological groups; note that this relation holds for loop groups of topological groups, but not necessarily for other loop spaces in general). Then
\begin{equation}
\pi_{0} (L U(1))\cong\pi_{0} (\Omega U(1)) \times \pi_{0}(U(1))\cong \mathbb{Z}
\end{equation}
which means the loop group of $U(1)$ is not path connected either.
Let's write the elements of $U(1)$ as
\begin{equation}
e^{i\lambda}.
\end{equation}
I can then write the elements of $L U(1)$ explicitly as
\begin{equation}
e^{i\lambda(t)},
\end{equation}
where $t=e^{i\theta}$ parametrizes the circle $S^1$.
I can then Fourier expand to obtain any element of $\Omega U(1)$ in the form
\begin{equation}
e^{i\sum_n \lambda_{n}e^{in\theta}}.
\end{equation}
However, if I set all the $\lambda_n$ to zero, I obtain the identity of $LU(1)$. This seems to me to contradict the fact that $LU(1)$ is not path connected, since all elements of $LU(1)$ are continuously connected to its identity element. Could someone explain?
Comment: @Najib: in the context of loop spaces and loop groups it's confusing to denote $S^1$ and $U(1)$ with the same symbol since they play different roles. The $S^1$ that you use to take loop spaces doesn't know it's a Lie group.
Comment: Two remarks: 1/ Why do you write $S^1$ and $U(1)$ differently? It's the same thing. 2/ $LX \simeq \Omega X \times X$ is not a general fact; it happens to be true for $X = U(1)$ but not all the time (it's not clear if you believe it's a general fact or not). In general there's only a fibration $\Omega X \to LX \to X$.
Comment: @Najib: I should have been clearer about your second point. Have edited that part, with info from an older answer by Qiaochu, which discusses related matters-http://math.stackexchange.com/questions/979857/when-is-the-free-loop-space-simply-connected
Answer: $\lambda(t)$ does not necessarily have a Fourier series because it is not necessarily a periodic function. The condition on $\lambda(t)$ that makes $e^{i \lambda(t)}$ represent a function $S^1 \to U(1)$ is not that $\lambda(t + 2\pi) = \lambda(t)$ but that
$$\lambda(t + 2\pi) = \lambda(t) + 2 \pi k$$
for some integer $k$ (the winding number of $\lambda$). The different values of $k$ label the different path components of the loop group, so when you implicitly assume that $k = 0$ you only end up in one component.
Comment: Thanks for your clear answer. Would it be safe to use the same explanation when $U(1)$ is replaced by $G$, where $G$ is a non-simply connected, nonabelian Lie group?
Comment: @Meer: it's unclear to me what you mean by "the same explanation" in that case.
Comment: I think I'll write it explicitly: say I replace $U(1)$ in my question by another path connected but not simply connected group $G$, which is nonabelian. I would obtain that $LG$ is not path connected. Then, expressing the elements of $LG$ as $e^{i\lambda _a(t) T^a}$, and expanding in Fourier modes I will find that $LG$ is path connected, which is a contradiction. The source of this contradiction is again that I have not taken into account that $\lambda(t)$ is not necessarily periodic, correct?
Comment: @Meer: yes, that's right, although the Fourier expansion thing isn't a key feature of the original problem anyway. You could also have just said "but I can multiply $\lambda(t)$ by a constant and send that constant to $0$, which connects it to zero," and the problem with that argument is that the condition above, for $k \neq 0$, is not invariant under scaling (unlike periodicity).
Comment: Thanks for clarifying that. I believe the general solution for $\lambda(t)$ in this problem is $\lambda(t)=\lambda_n e^{in\theta} + k\theta, $since this satisfies $\lambda(\theta + 2\pi)=\lambda(\theta) + 2\pi k$, am I correct?
Comment: @Meer: yes, that's right.

Loop group of U(1)


For Loop over Data/Rows from a DataSource/Select-Statement

Question: Here's the use case:
Users enter the budget of each month. So there is a table with the fields [Year], [Month] and [BudgetValue].
Example:
2014  01  200'000.-
2014  02  250'000.-

For each of those entries, I would like to select the working-day dates from my DimDate. For example, for January 2014 I would get 23 dates. (In my DimDate I have a bit which mark all the working days)
In my actual FactBudget I would then insert a dayly budget with the 23 dates.
Example:
2014.01.02   (200'000.-)/23
2014.01.03   (200'000.-)/23
etc.

I have no experience with the For/Foreach Loop Containers in SSIS. Is my problem even solvable with one of those containers or do I need a different structure/approach?
Comment: What are you doing in the package exactly? Is it possible to do it in an Execute SQL task with T-SQL for example?
Comment: Yeah why are you even bringing SSIS into this?   This could be done with a simple stored procedure.   No loop needed.
Answer: Start by creating a temp table with values 1-31.  We will call this #days.
Then use that to create your day-by-day records:
Select * from MyTable a
cross join #days b

This will create 31 rows for each of your MyTable rows, one per (possible day).  Next we want to get rid of the ones that are weekends or not real days (note, I am using temp tables here so you can see what I am doing, but this can be collapsed into one query).
Select cast(b.[day] as varchar) + '-' + cast(a.[month] as varchar) + '-' + cast(a.[year] as varchar) as MyDate, a.*
into #temp2
from MyTable a
cross join #days b
where isdate(cast(d as varchar) + '-' + cast(m as varchar) + '-' + cast(y as varchar)) = 1 --Get rid of non-dates, like February 31

delete
from #temp2
where datepart(weekday, MyDate) in (1,7) --Get rid of weekends

Finally, count the number of weekdays in each month, and join that back onto your table (you could also do this with a partition, but a self join is easier to follow, I think):
select a.MyDate, a.BudgetValue*1.0/CountDays as BudgetPerDay from #temp2 a
left join
    (select [year],[month], count(*) as CountDays from #temp2 group by [year],[month]) b
on a.[year] = b.[year] and a.[month] = b.[month]

Comment: I am just curious, would this work even for months having less than 31 days?
Comment: @VKarthik - It should. The middle step drops all the results that aren't valid dates (like February 30-31, April 31, etc.).


Stirling Binomial Polynomial

Question: Let $\{\cdot\}$ denote Stirling Numbers of the second kind. Let $(\cdot)$ denote the usual binomial coefficients. It is known that $$\sum_{j=k}^n {n\choose j} \left\{\begin{matrix} j \\ k \end{matrix}\right\} = \left\{\begin{matrix} n+1 \\ k+1 \end{matrix}\right\}.$$ Note: The indexes for $j$ aren't really needed since the terms are zero when $j>n$ or $j<k$.
How do I calculate $$\sum_{j=k}^n 4^j{n\choose j} \left\{\begin{matrix} j \\ k \end{matrix}\right\} = ?$$ I have been trying to think of this sum as some special polynomial (maybe a Bell polynomial of some kind) that has been evaluated at 4.
I have little knowledge of Stirling Numbers in the context of polynomials. Any help would be appreciated; even a reference to a comprehensive book on Stirling Numbers and polynomials.
Answer: It appears we  can give another derivation of the  closed form by @vadim123 for the
sum $$q_n = \sum_{j=k}^n m^j {n\choose j} {j \brace k}$$
using the bivariate generating function of the Stirling numbers of the
second kind. This computation illustrates generating function techniques as presented in Wilf's generatingfunctionology as well as the technique of annihilating coefficient extractors.
Recall the species for set partitions which is
$$\mathfrak{P}(\mathcal{U} \mathfrak{P}_{\ge 1}(\mathcal{Z}))$$
which gives the generating function
$$G(z, u) = \exp(u(\exp(z)-1)).$$
Introduce the generating function
$$Q(z) = \sum_{n\ge k} q_n \frac{z^n}{n!}.$$
We thus have
$$Q(z) = \sum_{n\ge k} \frac{z^n}{n!}
\sum_{j=k}^n m^j {n\choose j} {j \brace k}.$$
Substitute $G(z, u)$ into the sum to get
$$Q(z) = \sum_{n\ge k} \frac{z^n}{n!}
\sum_{j=k}^n m^j {n\choose j}
j! [z^j] \frac{(\exp(z)-1)^k}{k!}
\\ = \sum_{j\ge k} m^j \left([z^j] \frac{(\exp(z)-1)^k}{k!}\right)
\sum_{n\ge j} j!  \frac{z^n}{n!} {n\choose j}
\\ = \sum_{j\ge k} m^j \left([z^j] \frac{(\exp(z)-1)^k}{k!}\right)
\sum_{n\ge j}  \frac{z^n}{(n-j)!}
\\= \sum_{j\ge k} m^j \left([z^j] \frac{(\exp(z)-1)^k}{k!}\right)
z^j \sum_{n\ge j}  \frac{z^{n-j}}{(n-j)!}
\\ = \exp(z)
\sum_{j\ge k} m^j z^j \left([z^j] \frac{(\exp(z)-1)^k}{k!}\right).$$
Observe that the sum annihilates the coefficient extractor, producing
$$Q(z) = \exp(z)\frac{(\exp(mz)-1)^k}{k!}.$$
Extracting coefficients from $Q(z)$ we get
$$q_n = \frac{n!}{k!}
[z^n] \exp(z)
\sum_{q=0}^k {k\choose q} (-1)^{k-q} \exp(mqz)
\\ = \frac{n!}{k!}
[z^n] \sum_{q=0}^k {k\choose q} (-1)^{k-q} \exp((mq+1)z)
= \frac{n!}{k!}
\sum_{q=0}^k {k\choose q} (-1)^{k-q} \frac{(mq+1)^n}{n!}
\\ = \frac{1}{k!}
\sum_{q=0}^k {k\choose q} (-1)^{k-q} (mq+1)^n.$$
Note that when $m=1$ $Q(z)$ becomes
$$\exp(z)\frac{(\exp(z)-1)^k}{k!}
= \frac{(\exp(z)-1)^{k+1}}{k!}
+ \frac{(\exp(z)-1)^k}{k!}$$
so that
$$[z^n] Q(z) = (k+1){n\brace k+1} + {n\brace k}
= {n+1\brace k+1},$$
which can also be derived using a very simple combinatorial argument.
Addendum.
Here is another derivation of the formula for $Q(z).$
Observe that when we  multiply two exponential generating functions of
the sequences $\{a_n\}$ and $\{b_n\}$ we get that
$$ A(z) B(z) = \sum_{n\ge 0} a_n \frac{z^n}{n!}
\sum_{n\ge 0} b_n \frac{z^n}{n!}
= \sum_{n\ge 0}
\sum_{k=0}^n \frac{1}{k!}\frac{1}{(n-k)!} a_k b_{n-k} z^n\\
= \sum_{n\ge 0}
\sum_{k=0}^n \frac{n!}{k!(n-k)!} a_k b_{n-k} \frac{z^n}{n!}
= \sum_{n\ge 0}
\left(\sum_{k=0}^n {n\choose k} a_k b_{n-k}\right)\frac{z^n}{n!}$$
i.e. the  product of  the two generating  functions is  the generating
function of $$\sum_{k=0}^n {n\choose k} a_k b_{n-k}.$$
(I have included this derivation in several of my posts.)
Now in the present case we have
$$A(z) = \sum_{j\ge k} {j\brace k} m^j \frac{z^j}{j!}
\quad\text{and}\quad
B(z) = \sum_{j\ge 0} \frac{z^j}{j!} = \exp(z).$$
Evidently $A(z)$  is just the exponential generating  function for set
partitions into $k$ sets evaluated at $mz,$ so we get
$$A(z) = \frac{(\exp(mz)-1)^k}{k!}$$
and with $Q(z) = A(z) B(z)$ the formula for $Q(z)$ follows.
Answer: This is as far as I got; for small $n$ or small $k$ I can work out what this is.
$$\sum_j 4^j{n\choose j} \left\{\begin{matrix} j \\ k \end{matrix}\right\}=$$
$$\sum_j 4^j{n\choose j} \frac{1}{k!}\sum_i(-1)^{k-i}{k\choose i} i^j=$$
$$\sum_i  \frac{1}{k!}(-1)^{k-i}{k\choose i} \sum_j (4i)^j{n\choose j} =$$
$$\frac{(-1)^k}{k!}\sum_i  (-1)^{i}{k\choose i} (4i+1)^n $$
Comment: That looks interesting. It should also be noted that we can assume $n > k$ since the sum is zero otherwise.
Answer: One can continue vadim123's approach with the ideas presented here (A sum with binomial coefficients).
Comment: Alas, this is only effective if $n-k$ is small.

Stirling Binomial Polynomial