What is the appropriate zero-correlation parameter model for factors in lmer?

Question: When one wants to specify a lmer model including variance components but no correlation parameters, as opposed to m1, for a categorical predictor (factor) with levels "A", "B", and "C" one has to convert the factors to numeric covariates or use lme4::dummy().
Until recently I thought m2, where c1 and c2 are the two contrasts defined for the factor, would be the correct way to specify such a zero-correlation parameter model.
But Rune Haubo Bojesen Christensen pointed out that this model does not make sense to him. Instead he suggests m3 (among others) as an appropriate model.
m1 <- lmer(y ~ 1 + factor + (1 + factor | group), data)

mm1 <- model.matrix(~ 1 + factor, data)  # This depends on the contrasts
c1 <- mm1[, 2]
c2 <- mm1[, 3]
m2 <- lmer(y ~ 1 + factor + (1 + c1 + c2 || group), data)

mm0 <- model.matrix(~ 0 + factor, data)  # This does NOT depend on the contrasts
A <- mm0[, 1]
B <- mm0[, 2]
C <- mm0[, 3]
m3 <- lmer(y ~ 1 + factor + (1 + A + B + C || group), data)

In what follows I provide an example using the Machines data set. m2a and m2b are two equivalent models representing m2; m3a and m3b represent m3, respectively.
library("lme4")
data("Machines", package = "MEMSS")
d <- Machines

m1 <- lmer(score ~ 1 + Machine + (1 + Machine | Worker), d)
VarCorr(m1)
 Groups   Name        Std.Dev. Corr
 Worker   (Intercept) 4.07928
          MachineB    5.87764   0.484
          MachineC    3.68985  -0.365  0.297
 Residual             0.96158

mm1 <- model.matrix(~ 1 + Machine, d)
c1 <- mm1[, 2]
c2 <- mm1[, 3]
m2a <- lmer(score ~ 1 + Machine + (1 + c1 + c2 || Worker), d)
m2b <- lmer(score ~ 1 + Machine + (1 | Worker) + (0 + c1 | Worker) + (0 + c2 | Worker), d)
VarCorr(m2a)
 Groups   Name        Std.Dev.
 Worker   (Intercept) 4.07425
 Worker.1 c1          5.88935
 Worker.2 c2          3.64708
 Residual             0.96228

mm0 <- model.matrix(~ 0 + Machine, d)
A <- mm0[, 1]
B <- mm0[, 2]
C <- mm0[, 3]
m3a <- lmer(score ~ 1 + Machine + (1 + A + B + C || Worker), d)
m3b <- lmer(score ~ 1 + Machine + (1 | Worker) + (0 + A | Worker) + (0 + B | Worker) + (0 + C | Worker), d)
VarCorr(m3a)
 Groups   Name        Std.Dev.
 Worker   (Intercept) 3.78595
 Worker.1 A           1.94032
 Worker.2 B           5.87402
 Worker.3 C           2.84547
 Residual             0.96158

How should one specify a mixed model without correlation parameters for factors and what are the differences between m2 and m3?
Also, is there a preferred model for model comparison with m4 (which is discussed here)?
m4 <- lmer(score ~ 1 + Machine + (1 | Worker) + (1 | Worker:Machine), d)

Update: there is an ongoing discussion regarding this and related questions on the R-sig-mixed-models mailing list.
Answer: SUMMARY: What is the most appropriate zero-correlation model, depends on the data. There is no universally correct choice.

I will consider the same Machines data set. It has several Workers, each repeatedly tested on all of the three Machines. The maximal mixed model is thus
lmer(score ~ 1 + Machine + (0 + Machine | Worker), d)

which fits $3\times 3$ covariance matrix of the random effects. The fixed effects define the mean score for each Machine; there are three Machines so it is a three-dimensional vector $\mu$. On top of that each Worker $i$ deviates from this $\mu$ by some "random" three-dimensional vector $\mu_i$. These $\mu_i$ are random vectors with mean zero $(0,0,0)$ and some $3\times 3$ covariance matrix $\Sigma$. Such a covariance matrix has 6 parameters:
$$\Sigma=\begin{bmatrix}\sigma^2_A&\sigma^2_{AB} &\sigma^2_{AC}\\\sigma^2_{AB}&\sigma^2_B&\sigma^2_{BC}\\\sigma^2_{AC}&\sigma^2_{BC}&\sigma^2_C\end{bmatrix}.$$
Note  that
lmer(score ~ 1 + Machine + (1 + Machine | Worker), d)

yields an equivalent model, only parameterized differently. The exact parametrization can also depend on the chosen contrasts, but I find it the easiest to discuss this with dummy contrasts, hence my (0 + Machine | Worker) specification above.
The crucial point here is that every model that simplifies the random effect structure can be understood as imposing some specific constraints on $\Sigma$.
The random intercept (1 | Worker) model corresponds to $$\Sigma=\begin{bmatrix}\sigma^2_w&\sigma^2_w &\sigma^2_w\\\sigma^2_w&\sigma^2_w&\sigma^2_w\\\sigma^2_w&\sigma^2_w&\sigma^2_w\end{bmatrix}.$$ Here each Worker gets a random scalar intercept $m_i$, i.e. $\mu_i = (m_i, m_i, m_i)$; the entries of $\mu_i$ are correlated with correlation 1.
The random interaction (1 | Worker:Machine) model corresponds to $$\Sigma=\begin{bmatrix}\sigma^2_{wm}&0&0\\0&\sigma^2_{wm}&0\\0&0&\sigma^2_{wm}\end{bmatrix}.$$ Here $\mu_i$ has three entries with the same variances but that are assumed to be uncorrelated.
In the following let A, B, and C be dummy variables for three Machines. Then (0 + A | Worker) model corresponds to  $$\Sigma=\begin{bmatrix}\sigma^2_A&0&0\\0&0&0\\0&0&0\end{bmatrix}.$$ Here $\mu_i$ has only one non-zero entry with variance $\sigma^2_A$. Similarly for (0 + B | Worker) and (0 + C | Worker).
The second crucial thing to realize is that a sum of uncorrelated multivariate Gaussians with $\Sigma_1$ and $\Sigma_2$ has covariance matrix $\Sigma_1+\Sigma_2$. So to understand what happens with more complicated random structures we can simply add up covariance matrices written above.
For example,
lmer(score ~ 1 + Machine + (1 | Worker) + (1 | Worker:Machine), d)

fits a covariance matrix with 2 parameters (this form of the covariance matrix is known as "compound symmetry"):
$$\Sigma=\begin{bmatrix}\sigma^2_{wm}+\sigma^2_w&\sigma^2_w &\sigma^2_w\\\sigma^2_w&\sigma^2_{wm}+\sigma^2_w&\sigma^2_w\\\sigma^2_w&\sigma^2_w&\sigma^2_{wm}+\sigma^2_w\end{bmatrix}.$$
The model that Rune Christensen recommends for uncorrelated factors
lmer(score ~ 1 + Machine + (1 + A + B + C || Worker), d)

fits a model with 4 parameters that is a bit more general than compound symmetry (and is only 2 parameters away from the maximal model):
$$\Sigma=\begin{bmatrix}\sigma^2_A+\sigma^2_w&\sigma^2_w &\sigma^2_w\\\sigma^2_w&\sigma^2_B+\sigma^2_w&\sigma^2_w\\\sigma^2_w&\sigma^2_w&\sigma^2_C+\sigma^2_w\end{bmatrix}.$$
The model that you have "until recently" had in mind (your m2) is the model that Reinhold Kliegl recommends as the zero-correlation model:
lmer(score ~ 1 + Machine + (1 + c1 + c2 || Worker), d)

If c1 and c2 were produced using the default treatment contrasts (with A being the reference level), then this model can be written as
lmer(score ~ 1 + Machine + (1 + B + C || Worker), d)

I agree with Rune that it is a somewhat unreasonable model because it treats factor levels differently: B and C get their own variance but A does not (corresponding $\Sigma$ would look the same as the one above but without $\sigma^2_A$). Whereas all three machines should arguably be treated on the same footing.
Thus, the most reasonable sequence of nested models seems to be:
max model --> comp symmetry w/ unequal vars --> comp symmetry --> rand. intercept

A note on marginal distributions
This post was inspired by Rune Christensen's email here https://stat.ethz.ch/pipermail/r-sig-mixed-models/2018q2/026847.html. He talks about $9\times 9$ marginal covariance matrices for individual observations within each Worker. I find this more difficult to think about, compared to my presentation above. The covariance matrix from Rune's email can be obtained from any $\Sigma$ as $$\Sigma_\text{marginal} = I_{m\times m} \otimes \Sigma + \sigma^2 I,$$ where $m$ is the number of repetitions per Worker/Machine combination (in this dataset $m=3$) and $\sigma^2$ is residual variance.
A note on sum contrasts
@statmerkur is asking about sum contrasts. Indeed, it is often recommended to use sum contrasts (contr.sum), especially when there are interactions in the model. I feel that this does not affect anything that I wrote above. E.g. the maximal model will still fit an unconstrained $\Sigma$, but the interpretation of its entries is going to be different (variances and covariances of the grand mean and deviations of A and B from the grand mean). The $\Sigma$ in m2 defined using contr.sum will have the same form as in (1+A+B || Worker) above, but again, with the different interpretation of the entries. Two further comments are:

Rune's critique of m2 still applies: this random effect structure does not treat A, B, and C on the same footing;
The recommendation to use the sum contrasts makes sense for the fixed effects (in the presence of interactions). I don't see a reason to necessarily prefer sum contrasts for the random effects, so I think, if one wants to, one can safely use (1+A+B+C || Worker) even if the fixed part uses sum contrasts.

A note on custom contrasts
I had an email exchange with Reinhold Kliegl about this answer. Reinhold says that in his applied work he prefers (1+c1+c2 || subject) over (1+A+B+C || subject) because he chose c1 and c2 as some meaningful contrasts. He wants to be able to interpret $\Sigma$ and he wants its entries to correspond to c1 and c2.
This basically means that Reinhold is fine with rejecting the assumption (that I made above) that the factor levels should be treated equally. He does not care about individual factor levels at all! If so, then of course it is fine to use (1+c1+c2 || subject). He gives his paper https://www.frontiersin.org/articles/10.3389/fpsyg.2010.00238/full as an example. There a four-level factor is coded with 3 custom contrasts c1, c2, c3, and grand mean as the intercept. These specific contrasts are of interest, and not the individual factors A to D. In this situation I agree that (1+c1+c2+c3 || subject) makes total sense.
But one should be clear that while (1+c1+c2+c3 | subject) does treat factor levels A to D equally (and merely re-parametrizes $\Sigma$ in terms of particular contrasts), (1+c1+c2+c3 || subject) will fail to treat factor levels equally.
Comment: @amoeba nice description! A small comment on terminology: It might be a little confusing for the uninitiated reader when you denote the covariance structure for `(1 | Worker) + (1 | Worker:Machine)` _compound symmetry_. I see why you do that, but a model with `(1 | Worker)` is usually said to be "compound symmetry" because the Var-Cov matrix of $Y$ (marginal distribution) has a compound symmetry form (and can be fitted as such with GLS). But it is of course not easy to see how the residual variance enters the mix unless we look at $\mathrm{Cov}(Y)$ ;-)
Comment: I also note that the description of $\Sigma$ for `(1 | Worker)` is somewhat non-standard. I think most people would think of a scalar random effect with (scalar) variance $\sigma_w^2$ for this model. But @amoeba's representation is mathematically equivalent and offers a fresh perspective - thanks.
Comment: @RuneHChristensen Thanks. Indeed, "compound symmetry" usually refers to the covariance matrix of the marginal distribution, and not to the covariance matrix of the random effects. I borrowed this term for this context from a quote from Douglas Bates, see the first paragraph of this question: https://stats.stackexchange.com/questions/304374/. But I should edit this answer to clarify a little. Regarding the scalar random effect, you are completely right: my description is non-standard but I was happy when I came up with it because it made the whole treatment clearer.
Comment: @statmerkur And by the way, thanks for posting this question (and for starting the bounty to attract attention). I learned quite a bit while answering it.
Comment: To be accurate the model I said that did not make sense to me (https://stat.ethz.ch/pipermail/r-sig-mixed-models/2018q2/026775.html) was a version of `m2a` (for a different data situation) in which `c1` and `c2` was coded with $\pm$ 0.5 which makes the random-effect design matrix $Z$ no longer be an indicator matrix. This is what I cannot but think will seriously alter the variance-covariance structure of the model, and this is why I can't make sense of it. Models in which `c1` and `c2`are indicator contrasts are not as perplexing to me though I don't claim to fully understand those either.
Comment: Nice answer. But, as I said earlier, the random effects part in `m2` is only  equivalent to `(1 + B + C || Worker)`for `contr.treatment`. One has to use `(c1 + c2 || group)` for the general form. Can you give the covariance matrix for `m2` with `contr.treatment` and with `contr.sum`?
Comment: Would be also very nice if there would be an example of the covariance matrix of `m1` for `(Machine | Worker)` with `contr.treatment` and `contr.sum`.
Comment: Hmm. If you use `contr.sum`, then your random effects do not correspond to A, B, and C anymore. You still have 3x3 covariance matrices, but the rows/columns correspond to the grand mean M, and the deviation of A from M and the deviation of B from M (I *think* that's how `contr.sum` works; right?). I am not sure what you want to see for `m1`, it's the still a generic 3x3 cov matrix. The same is true for `m2`: it would have the same form as with treatment contrasts, just the interpretation of the entries is different. I think the critique remains that `m2` treats A, B, and C differently.
Comment: I made an update about `contr.sum` to be more explicit about it.
Comment: Sorry, I did not realize that this https://stat.ethz.ch/pipermail/r-sig-mixed-models/2018q2/026857.html was *your* email. The answer to your Q1 from that email is related to the 2nd bullet point in my Update: it does not matter what contrasts are used for the fixed part; the estimated coefficients will one way or another define means for A, B, and C. So a random part `(1+A+B+C|Worker)` can still be thought as random deviations from these means. It might be a bit confusing when the fixed part and the random part use different contrasts (so to say), but it's fine.
Comment: How would the cov matrix of `m2` for `contr.treatment` look like? Like the one for `m3` except for entry (1,1) which would be just sigma_omega^2 ?
Comment: Re first comment: Yes! I added this into the answer. Re second comment: well, the fixed part in this example just defines means $\vec\mu$ (I'm writing it as a vector to stress that it's averages for 3 machines). Whatever contrast scheme you use, it still yields the same $\vec\mu$, just parametrized differently. So random effects can be zero-centered Gaussian random variables around entries of $\vec\mu$. Nothing changes! Nothing breaks if you parameterize $\vec\mu$ in one way for the fixed part and in another way for the random part.
Comment: @statmerkur I have just written another Update based on an email exchange with Kliegl. Please take a look.
Comment: @RuneHChristensen: sorry, gave the wrong link, corrected it. This is the one I'm referring to (IIRC we were still using `contr.treatment` there) https://stat.ethz.ch/pipermail/r-sig-mixed-models/2018q2/026769.html. And if `c1` and `c2` are custom contrasts this will alter the variance-covariance structure of the model, too (I think). So what do you think about @amoeba's "note on sum contrasts" and "note on custom contrasts"
Comment: @amoeba Coming back to this after a while, I just looked through Reinhold Kliegl's derivation (https://rpubs.com/Reinhold/423796) of $\Sigma$ for `m2` with `contr.sum` and wasn't able to figure out why you say that it looks like the one for `(1+A+B || Worker)`. Would be great if you could elaborate on this. See next comment for the $\Sigma$ he derived
Comment: $\Sigma = \begin{bmatrix}
\sigma^2_1 & \sigma^2_1 & \sigma^2_1\\ \sigma^2_1 & \sigma^2_1 & \sigma^2_1\\
\sigma^2_1 & \sigma^2_1 & \sigma^2_1 \end{bmatrix} + \begin{bmatrix} \sigma^2_2 & 0 & -\sigma^2_2\\ 0 & \sigma^2_3 & -\sigma^2_3\\ -\sigma^2_2 & -\sigma^2_3 & \sigma^2_2 + \sigma^2_3 \end{bmatrix}$
Comment: @statmerkur Sorry, it's been a while, and I don't really recall everything here very well anymore. I'd need to spend quite some time remembering what was going on here before I could answer that. Not sure I'll be able to do it any time soon... Might very well be that my statement was wrong.
Comment: Sure, that's totally understandable. Would be great if you found the time to go over it again. Or, coincidentally, maybe @RuneHChristensen can provide a quick answer to that question?


Is there a way to check for sure that optimization was applied to the weights of NN?

Question: Given the first or next steps of NN training, where weights were initially randomly sampled from some distribution, is there a reliable way to determine if some optimization was applied to the weights?
Or in other words, I want to have a way to check if some training has been done, and weighs are not randomly generated.
My thoughts were to check if the distribution of the weights will change in time, but the information I found so far indicates that if weights were, for example, sampled from the normal distribution, the distribution of weights may keep normal even after a bunch of training epochs.
I've thought about tracking the improvements of predictions in time, but to my understanding, there can be theoretical situations when optimization will not give a quick improvement of the accuracy, so in that case, there will be some performed training, and just checking the accuracy will be not enough.
Comment: Is there any reason you're not just looking at the difference between the initial weights W0 and the weights you want to check, W1? I expect the l2 norm of the difference would be close to zero only when no optimization was done (which I guess is what you're trying to debug).
Comment: If you make the strong assumptions that (1) the initial weights come from a known distribution and (2) the optimized weights do not come from that distribution then this reduces to a statistical test
Comment: @galoosh33 what I want to achieve is somewhat specific - I want to check the 3rd-party's computations, and there is no expected trust for that 3rd-party, so I want to find a way to check that some meaningful computations have been done, and the result weights are not completely random.
Answer: Yes, please see "verifiable computing from homeomorphic encryption" which allows for a client to send job to a worker, the worker to complete the job (== apply gradient descent) and send the results back, and for the client to verify that the computation was done correctly. As an additional side-benefit, the worker never has access to the weights or data used during training. Unfortunately I don't understand this field well enough to explain how exactly it works.
Of course this comes with the caveat that I don't believe there is any computationally feasible implementation of homeomorphic encryption so far, so it is only possible in theory.

Alternatively, consider requesting the worker to send back weights from checkpoint iterations $0$, $k$, $2k$, $\ldots$ then, when training is complete at iteration $T$, select $m$ unique random checkpoints and train to the next checkpoint, verifying that starting from the weights from iteration $tk$ you really will end up with the weights from iteration $(t+1)k$ after $k$ iterations. To do this the worker probably also needs to send you the random seed used for constructing the input batches to the training.
If the worker has cheated in just one iteration, then you will detect this with probability $mk/T$, at a cost of $O(mk)$ work and $O(T/k)$ space. If the worker has cheated substantially (say $T'$ iterations), then at least $T'/k$ checkpoints will reveal this, and your chances of catching them becomes roughly $1- \left(1-\frac{T'}{T}\right)^m$.
Answer: From your point of view NN weights are always randomly. There is no way to guarantee matrix of weights is a result of training method. Random process can also generate the same weights.
If you assume distribution for your weights you can use statistic to evaluate probability that your matrix is from this distribution. I don't think that way could be useful in any way.


How do competitive runners with asthma handle Doping tests?

Question: Many asthmatic medications such as pseudoefedrine (in DUACT) and different inhalers are performance-enhancing-performance drugs. I have heard cases where athletes have forgotten to inform officials that they need to use certain drugs and false alerts about doping positivity. So
How do competitive runners with asthma handle doping tests?
Answer: There is the national level and the international level. IAAF has forms by which athletes can send exemption forms.
IAAF

IAAF Therapeutic Use Exemptions (TUE) Application Form here
Cardiovascular evaluation of athletes - IAAF
Comment: This has been a hot-button issue of late because the abuse of TUEs is seen as an area where athletes may be circumventing doping rules.


Is it bad practice to score a E major piece for Bb Clarinet in 6 sharps/flats?

Question: I'm currently writing my first piece for a full orchestra, to be played by a high school orchestra and band. The piece is in E major, but it is somewhat chromatic and modulates to different keys for short periods of time (short enough to not change the key signature). However, the only clarinets the orchestra has are Bb clarinets, which would put their part in 6 sharps or 6 flats.
Should I write their part keyless and write in all the accidentals? If so, should I make this change on both the entire score and the clarinet part? Or only on the clarinet part?
Or is it better to keep their part in 6 sharps/flats? My concern is that the short sections in F major (as an example) would be cumbersome to read with all the naturals written in, and the sections that are in E major sometimes require double sharps, which make it harder to read.
Comment: If you're worried about the clarinetists not being able to cope with E major, why not just transpose the whole piece up a half step to F major?  That's a nice easy key for everyone.
Comment: A piece in E major for high school? Expect plenty of intonation and tuning issues. If you use "A" clarinets it would alleviate your problem. My advice: better to choose more familiar keys for student players. Good luck, this will be an excellent learning experience for you.
Comment: The Grade 12 students might not have issues with E major. The Grade 9 students probably will. With that being said, I've never seen Bb clarinet parts in orchestral or wind ensemble works where their key signatures were blanked out (unlike French horn parts, whose key signatures were often blanked out).
Comment: When composing, some of the questions to ask oneself is why is this key the best? Which other transposing instruments will it affect adversely? Is it in this key as it's the best place for a solo (etc) instrument?
Comment: this is for the top band/orchestra in a school of roughly 3000, so I'm expecting decent 11th or 12th grade clarinetists. Along the lines of Mr. Witthoft's answer, typically how common are A clarinets? How much of a problem is intonation in a foreign key?
Comment: Regarding your last comment. I'd imagine not many students would own an A clarinet. Intonation is maybe more of a problem not due to the instrument, but the player playing sets of notes that are not within his usual remit.
Answer: Clarinets read key signatures.   Yes, six sharps is cruel, but it happens!  And if it takes a double sharp, write a double sharp.  Notes that sound sharpened but are written flattened are harder, not easier to read.  A scale should look like a scale, a leading note should look sharpened not flattened.
You'll get opinions about whether players 'prefer' sharps or flats.   Your notation software might make the decision for you when the 6#/6b issue arises.   My advice is not to go to the trouble of concocting a 'Clarinet in A#' just to force your preference.   Bb Saxophone players play in Blues bands.  Blues music is often in E.   They cope.
Comment: I don't think so.  The issue only arises with F#/Gb major.   F# major is 6 sharps - F, C, G, D, A, E.   Gb major is 6 flats.  B, E, A, D, G, C.   Yes?
Comment: Don't know why 7b came out. Meant 6b! Typo! Deleted.
Answer: Look to the future, so to speak.  Write the part for A-clarinet, and provide a transcribed part for Bb clarinet to support your local orchestra/band.   For that matter, the school might well be willing to rent a couple A-clarinets for the orchestra members to use for your piece.
In reality, a decent high-school clarinetist, at least in the orchestra (which presumably has 4 or fewer clarinets), can transpose from A to Bb by sight.
Comment: So you're suggesting writing a Clarinet in A part, that Clarinet in Bb players will sight-transpose, in order to avoid a 'hard' key signature in a Clarinet in Bb part?  Slightly muddled thinking...   :-)
Comment: @LaurencePayne  This long-term clarinetist knows you are wrong.  :-) . But what I meant was: write the part in A, and if necessary provide a transposed part in Bb, but that a skilled high-school licorice-stickler can transpose anyway


unary potentials in graph cuts like optimization for computer vision

Question: I am currently reading a paper which performs minimisation of energy function of the form:
$
E(z, \alpha) = U(z, \alpha) + \lambda V(z, \alpha)
$
Here $z$ is the image data defined in a uniform grid and $\alpha$ is some labelling we want to do per pixel in the image. Now, the paper went on to say that for the segmentation problem, given some real-world log-likehood ratio as:
$
    L(x) = \log p(z_{n}(x)|\alpha_{n}(x) = Fg) - \log p(z_{n}(x)|\alpha_{n}(x) = Bg)
$
My question is how can one create such a likelihood/appearance model from the image data. Say I have an image on a 2D grid and some initial foreground and background pixels marked by user. How would one go about computing this likelihood function? I am guessing there are many forms this function can take but does anyone know how this can be typically modeled.
If anyone is interested, the paper can be found here: https://www.microsoft.com/en-us/research/publication/geos-geodesic-image-segmentation/
Answer:
how can one create such a likelihood/appearance model from the image
data.

The usual way is to model the distribution of pixel intensities of each class ({FG,BG} in your case).  The very simplest is to assume constant variance Gaussian, in which you only need to estimate the mean of the pixel intensities for each class. You'd have two distributions: $p_{Fg}(z)$ and $p_{Bg}(z)$ (where I shortened $z = z_n(x)$ to match your notation).
Then
$\log p(z|α_n=Fg) = p_{Fg}(z)$
and similar for the background.
More complicated models fit different distributions, e.g. by storing histograms for intensities of each class.  Or they use more than just the intensity, say by computing a representation of the "texture" around every pixel and modeling a multivariate distribution $p(z_1,z_2,...z_N|α_n=Fg)$
Since you have pixels marked by a user, you can fit the distribution of your choosing over the variables of your choosing for each class, then you're all set!


How to mathematically describe lag measured from cross correlation

Question: In MATLAB, this is the function used to measure lag using cross-correlation:
[acor,lag] = xcorr(s2,s1);
[~,I] = max(abs(acor));
lagDiff = lag(I)
timeDiff = lagDiff/Fs

where $s1$ and $s2$ are the signals, $acor$ is the cross-correlation coefficent $r$, $I$ is the coordination of $lag$ at which the maximum cross correlation occurs
Can somebody help me to explain $lagDiff$ in mathematical form?
Comment: it is the lag at which the maximum cross correlation occurs
Comment: @michaelStachowsky edited based on your suggestion
Answer: Let $X = \langle x_1, \cdots x_n\rangle$ be the vector of cross correlations, where the subscript indicates the lag - you may suitable turn this into a time value if you know the time step of your original data.  We can define the lag vector much more simply: $L = \langle 1, 2, ..., n \rangle$, and let $L_i$ be the $i^{th}$ component.
Then $I = \underset{i}{\operatorname{argmax}}X$
Your "lagDiff" is just $L_{I}$.
EDIT: Explaining some notation in general
The "argmax" operation is related to finding a maximum.  Using our above example,
$M = \underset{i}{\operatorname{max}}X$ means: "search through all of the $x_i$ components of $X$, and find the biggest one".  Literally: find the maximum of $X$.  $M$ will be the maximum value we've found.
Then $I = \underset{i}{\operatorname{argmax}}X$ means "search through all of the $x_i$ components of $X$, and find the biggest one.  We aren't interested in knowing what that is.  Instead, we want to know the index at which it occurs."  That index is stored in I.
Comment: Thank you for your answer. However, I need further clarification between the relationship between $I$ and $ i$ using the `argmax` (I am still learning about math symbols). Is argmax $i$ means the index $i-th$ of where $X$ is max. To put this simply, is $i$ here automatically refers to an index?
Comment: I've edited my answer, hopefully it explains a bit more


Carregar um elemento em ajax conforme escolha do usuário

Question: Tenho um código que insere um campo textearea conforme uma escolha de input radio. Gostaria de simplificar esse código fazendo com que use só JavaScript. É possível? Segue abaixo:
HTML

2.3 - Você estuda?

<input type="radio" name="estuda" id="estuda" value="1" required=""> Sim
<input type="radio" name="estuda" id="estuda" value="2" required=""> Não

JavaScript
$('#estuda').change(function () {
  var chars = (this.value);
  $.post(URL + 'Ajax/pesquisa', {val: chars}, function (busca) {
  $('#ret-ajax').html(busca);
 });
});

Ajax
$char = $_POST['val'];
$body = '';
if($char == 1){
     $body .= '<textarea name="curso" rows=4></textarea>';
  }
   elseif($char == 2){
     $body .= '';
}

$retorno = $body;

Answer: Tinhas um erro grave no teu html, não pode haver dois id's iguais (#estuda), podes colocar como classe (.estuda), faz o seguinte:

$('.estuda').change(function () {
  var chars = parseInt(this.value);
  if(chars === 1) {
    $('#ret-ajax').html('<textarea name="curso" rows=4></textarea>');
    return;
  }
  $('#ret-ajax textarea').remove();
});

2.3 - Você estuda?

<input type="radio" name="estuda" class="estuda" value="1" required=""> Sim
<input type="radio" name="estuda" class="estuda" value="2" required=""> Não

Comment: Valeu amigo, funcionou perfeitamente.
Comment: De nada @EduardoSantos. Ainda bem que sim
Answer: Você não deve usar um mesmo id para dois elementos diferentes.
http://www.w3schools.com/TAGS/att_global_id.asp
Dito isso, sugiro você remover a função $.post e fazer a comparação no próprio JavaScript. Algo como:
$('#estuda').change(function () {
  var chars = (this.value);
  if(chars == 1)
     $('#ret-ajax').html('<textarea name="curso" rows=4></textarea>');
  else
     $('#ret-ajax textarea').remove();
});

Answer: O atributo id deve ser único, mas você pode obter as entradas pelo name, adicionar um ouvinte (listener) para cada radio button e criar um textarea caso seja a opção 1. Com Javascript puro pode ser algo mais ou menos..

// obtém todas os elementos com name estuda
var entradas = document.getElementsByName("estuda");

// adiciona um listener change para cada um
for (var i = 0; i < entradas.length; i++) {
  entradas[i].addEventListener("change", criar);
}

// funcao que verifica o valor do radio
function criar() {
  if (this.value == 1)
    document.getElementById("ret-ajax").innerHTML = '<textarea name="curso" rows=4></textarea>'; // innerHTML adiciona um conteudo HTML ao elemento
  else
    document.getElementById("ret-ajax").innerHTML = '';
}

2.3 - Você estuda?

<input type="radio" name="estuda" id="estudaS" value="1" required="">Sim
<input type="radio" name="estuda" id="estudaN" value="2" required="">Não

Comment: Valeu amigo. Isso mesmo.


Text Search not working with Spring Boot MongoDB

Question: I am developing the Spring Boot + MongoDB + spring data mongo + Text search Example. By taking a reference from link: https://spring.io/blog/2014/07/17/text-search-your-documents-with-spring-data-mongodb, I developed my code, but when I am executing that, it's giving empty resultset. Please help in this scenario. I was expecting to get both results OrderId = 10248 and 10249, but I got empty.
My developed code:
OrderDetails.java
@Document(collection="order-details")
public class OrderDetails {

    @Id
    private ObjectId id;

    //@TextIndexed(weight=2)
    @Field("OrderID")
    private Integer orderID;

    @Field("ProductID")
    private Integer productID;

    @Field("UnitPrice")
    private Double unitPrice;

    @Field("Quantity")
    private Integer quantity;

    @Field("Discount")
    private Integer discount;
        // setters and getters
}

OrderDetailsService.java
public interface OrderDetailsService {
    List<OrderDetails> findAllBy(Integer searchValue);
}

OrderDetailsServiceImpl.java
@Component
public class OrderDetailsServiceImpl implements OrderDetailsService{

    @Autowired
    private OrderDetailsRepository odRepository;
    @Autowired
    private MongoOperations mongoOperations;

    public List<OrderDetails> findAllBy(Integer searchValue) {
        //TextCriteria criteria = TextCriteria.forDefaultLanguage().matchingAny(searchValue);
        TextCriteria criteria = TextCriteria.forDefaultLanguage().matchingPhrase("OrderID")
                .matchingPhrase(String.valueOf(searchValue));
        Query query = TextQuery.queryText(criteria).sortByScore();

        List<OrderDetails> orderDetails =mongoOperations.find(query, OrderDetails.class);
        return orderDetails;
    }
}

MainController.java
@Controller
public class MainController implements CommandLineRunner {
    private Logger LOGGER = Logger.getLogger(MainController.class);

    @Autowired
    private OrderDetailsService odService;

    @Override
    public void run(String... args) throws Exception {
        LOGGER.info("~~ STARTED ~~");

        // Find OrderID
        List<OrderDetails> orderDetails = odService.findAllBy(102);
        LOGGER.info("Order Details Size  :"+orderDetails.size());
    }
}

MondoDB looks like?

And if I use below in model class
@TextIndexed(weight=2)
    @Field("OrderID")
    private Integer orderID;

I see following error comes.
Caused by: com.mongodb.CommandFailureException: { "serverUsed" : "localhost:27017" , "createdCollectionAutomatically" : false , "numIndexesBefore" : 2 , "errmsg" : "exception: Index with name: OrderDetails_TextIndex already exists with different options" , "code" : 85 , "ok" : 0.0}
    at com.mongodb.CommandResult.getException(CommandResult.java:76)
    at com.mongodb.CommandResult.throwOnError(CommandResult.java:131)
    at com.mongodb.DBCollectionImpl.createIndex(DBCollectionImpl.java:362)
    at com.mongodb.DBCollection.createIndex(DBCollection.java:563)
    at org.springframework.data.mongodb.core.index.MongoPersistentEntityIndexCreator.createIndex(MongoPersistentEntityIndexCreator.java:133)
    at org.springframework.data.mongodb.core.index.MongoPersistentEntityIndexCreator.checkForAndCreateIndexes(MongoPersistentEntityIndexCreator.java:127)
    at org.springframework.data.mongodb.core.index.MongoPersistentEntityIndexCreator.checkForIndexes(MongoPersistentEntityIndexCreator.java:119)
    at org.springframework.data.mongodb.core.index.MongoPersistentEntityIndexCreator.onApplicationEvent(MongoPersistentEntityIndexCreator.java:103)
    at org.springframework.data.mongodb.core.index.MongoPersistentEntityIndexCreator.onApplicationEvent(MongoPersistentEntityIndexCreator.java:45)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:151)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:128)
    at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:331)
    at org.springframework.data.mapping.context.AbstractMappingContext.addPersistentEntity(AbstractMappingContext.java:306)
    at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentEntity(AbstractMappingContext.java:180)
    at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentEntity(AbstractMappingContext.java:140)
    at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentEntity(AbstractMappingContext.java:67)
    at org.springframework.data.mongodb.repository.support.MongoRepositoryFactory.getEntityInformation(MongoRepositoryFactory.java:141)
    at org.springframework.data.mongodb.repository.support.MongoRepositoryFactory.getTargetRepository(MongoRepositoryFactory.java:83)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:173)
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.initAndReturn(RepositoryFactoryBeanSupport.java:239)
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:225)
    at org.springframework.data.mongodb.repository.support.MongoRepositoryFactoryBean.afterPropertiesSet(MongoRepositoryFactoryBean.java:108)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1633)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1570)
    ... 40 more

EDIT:
I follow your instructions and I see following error, please guide further

16-04-06 01:30:32.601 DEBUG MongoTemplate - find using query: { "$text" : { "$search" : "\"OrderID\" \"10248\""}} fields: { "score" : { "$meta" : "textScore"}} for class: class com.common.model.OrderDetails in collection: order-details
16-04-06 01:30:32.610 DEBUG MongoDbUtils - Getting Mongo Database name=[boot]
16-04-06 01:30:32.774 DEBUG DirtiesContextTestExecutionListener - After test method: context [DefaultTestContext@37d4349f testClass = OrderDetailsTest, testInstance = com.common.index.OrderDetailsTest@434a63ab, testMethod = test@OrderDetailsTest, testException = org.springframework.data.mongodb.UncategorizedMongoDbException: Unable to execute query: error processing query: ns=boot.order-details limit=0 skip=0
Tree: TEXT : query="OrderID" "10248", language=, tag=NULL
Sort: { score: { $meta: "textScore" } }
Proj: { score: { $meta: "textScore" } }
 planner returned error: need exactly one text index for $text query; nested exception is com.mongodb.MongoException: Unable to execute query: error processing query: ns=boot.order-details limit=0 skip=0
Tree: TEXT : query="OrderID" "10248", language=, tag=NULL
Sort: { score: { $meta: "textScore" } }
Proj: { score: { $meta: "textScore" } }
 planner returned error: need exactly one text index for $text query, mergedContextConfiguration = [MergedContextConfiguration@6e0f5f7f testClass = OrderDetailsTest, locations = '{classpath:application-config.xml}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]], class dirties context [false], class mode [null], method dirties context [false].
16-04-06 01:30:33.232 DEBUG DirtiesContextTestExecutionListener - After test class: context [DefaultTestContext@37d4349f testClass = OrderDetailsTest, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [MergedContextConfiguration@6e0f5f7f testClass = OrderDetailsTest, locations = '{classpath:application-config.xml}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]], dirtiesContext [false].
16-04-06 01:30:33.236 INFO  GenericApplicationContext - Closing org.springframework.context.support.GenericApplicationContext@53045c6c: startup date [Wed Apr 06 01:30:28 IST 2016]; root of context hierarchy
16-04-06 01:30:33.237 DEBUG DefaultListableBeanFactory - Returning cached instance of singleton bean 'lifecycleProcessor'

OrderDetailsRepository.java
public interface OrderDetailsRepository extends CrudRepository<OrderDetails, String>{

    List<OrderDetails> findAllBy(TextCriteria criteria);
}

My Junit:
OrderDetailsTest.java
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:application-config.xml"})
public class OrderDetailsTest {
    @Autowired
    private OrderDetailsService odService;

    @Test
    public void test() {
        List<OrderDetails> orderDetails =odService.findAllBy("10248");
        System.out.println("Size : ["+ orderDetails +"]");
        for (OrderDetails od : orderDetails) {
            System.out.println("-------------------------");
            System.out.println(od.getDiscount());
            System.out.println(od.getOrderId());
            System.out.println(od.getProductId());
            System.out.println(od.getQuantity());
            System.out.println(od.getUnitPrice());
            System.out.println(od.getId());
            System.out.println("-----------------------------");
        }
    }
}

Junit error logs:
org.springframework.data.mongodb.UncategorizedMongoDbException: Unable to execute query: error processing query: ns=boot.order-details limit=0 skip=0
Tree: TEXT : query="OrderID" "10248", language=, tag=NULL
Sort: { score: { $meta: "textScore" } }
Proj: { score: { $meta: "textScore" } }
 planner returned error: need exactly one text index for $text query; nested exception is com.mongodb.MongoException: Unable to execute query: error processing query: ns=boot.order-details limit=0 skip=0
Tree: TEXT : query="OrderID" "10248", language=, tag=NULL
Sort: { score: { $meta: "textScore" } }
Proj: { score: { $meta: "textScore" } }
 planner returned error: need exactly one text index for $text query
    at org.springframework.data.mongodb.core.MongoExceptionTranslator.translateExceptionIfPossible(MongoExceptionTranslator.java:101)
    at org.springframework.data.mongodb.core.MongoTemplate.potentiallyConvertRuntimeException(MongoTemplate.java:2075)
    at org.springframework.data.mongodb.core.MongoTemplate.executeFindMultiInternal(MongoTemplate.java:1918)
    at org.springframework.data.mongodb.core.MongoTemplate.doFind(MongoTemplate.java:1729)
    at org.springframework.data.mongodb.core.MongoTemplate.doFind(MongoTemplate.java:1712)
    at org.springframework.data.mongodb.core.MongoTemplate.find(MongoTemplate.java:602)
    at org.springframework.data.mongodb.core.MongoTemplate.find(MongoTemplate.java:593)
    at com.common.Service.OrderDetailsServiceImpl.findAllBy(OrderDetailsServiceImpl.java:29)
    at com.common.index.OrderDetailsTest.test(OrderDetailsTest.java:24)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:70)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:224)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:83)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: com.mongodb.MongoException: Unable to execute query: error processing query: ns=boot.order-details limit=0 skip=0
Tree: TEXT : query="OrderID" "10248", language=, tag=NULL
Sort: { score: { $meta: "textScore" } }
Proj: { score: { $meta: "textScore" } }
 planner returned error: need exactly one text index for $text query
    at com.mongodb.QueryResultIterator.throwOnQueryFailure(QueryResultIterator.java:246)
    at com.mongodb.QueryResultIterator.init(QueryResultIterator.java:224)
    at com.mongodb.QueryResultIterator.initFromQueryResponse(QueryResultIterator.java:184)
    at com.mongodb.QueryResultIterator.<init>(QueryResultIterator.java:62)
    at com.mongodb.DBCollectionImpl.find(DBCollectionImpl.java:86)
    at com.mongodb.DBCollectionImpl.find(DBCollectionImpl.java:66)
    at com.mongodb.DBCursor._check(DBCursor.java:498)
    at com.mongodb.DBCursor._hasNext(DBCursor.java:621)
    at com.mongodb.DBCursor.hasNext(DBCursor.java:657)
    at org.springframework.data.mongodb.core.MongoTemplate.executeFindMultiInternal(MongoTemplate.java:1904)
    ... 35 more

Note: boot is my mongodb name.
Please see another EDIT:
db['order-details'].getIndexes()
/* 0 */
{
    "0" : {
        "v" : 1,
        "key" : {
            "_id" : 1
        },
        "name" : "_id_",
        "ns" : "boot.order-details"
    }
}

db['order-details'].createIndex({"OrderID" : "text"})

db['order-details'].getIndexes()
{
    "0" : {
        "v" : 1,
        "key" : {
            "_id" : 1
        },
        "name" : "_id_",
        "ns" : "boot.order-details"
    },
    "1" : {
        "v" : 1,
        "key" : {
            "_fts" : "text",
            "_ftsx" : 1
        },
        "name" : "OrderID_text",
        "ns" : "boot.order-details",
        "weights" : {
            "OrderID" : 1
        },
        "default_language" : "english",
        "language_override" : "language",
        "textIndexVersion" : 2
    }
}

Comment: Can you share you Repository class?
Comment: Deendayal Garg - As requested, OrderDetailsRepository.java is shared above.
Answer: first drop indexs commandline db.order-details.dropIndex()
and refactor this line TextCriteria criteria = TextCriteria.forDefaultLanguage().matchingPhrase("OrderID").matchingPhrase(String.valueOf(orderId)); after run application
Comment: Mongodb is looking type for maching "123" not equal 123
Comment: Then  it ask string change orderid type to string in orderdetails.class
Comment: your data not indexed
Comment: document.order-details.getIndexes () run this did see any indexed ?
Comment: first run this drop all index : db.order-details.dropIndex()  after run this create index by OrderId field : db.order-details.ensureIndex({OrderID:"text"}) and run application after
Comment: I see this now: { "$text" : { "$search" : "\"OrderID\" \"10248\""}}. Please see Edit, still no luck !!
Comment: Return any data in your application console ,this means index is created your mongodb databases
Comment: kakashi - Did you get chance to fixed issue with my provided source code? Could you please guide?
Comment: @javatechnology I dont know but if orderId is string I get data but integer noting any search result also if orderId is string generated query is work in mongodb console but integer again not work query and also mongodb console saying  : "search need string"
Comment: If Mongo docs says search is possible with string only, then wonder, how  we can search likes of TransactionId's etc, Anyway, many thnx for info !
Comment: @javatechnology   I asked answer now in  stackowerflow : ) and if your think my answer is good  please confirm : )


Two abelian groups are isomorphic iff their corresponding sylow subgroups are isomorphic.

Question: I know that any abelian group can be written as a direct product of sylow subgroups and any sylow subgroup can be written as a product of cyclic groups.
Let $G$ and $G^{\prime}$ be two abelian groups of order m and n.
and $m=p_1^{n_1} \dots p_k^{n_k}$ and $n=q_1^{n_1} \dots q_l^{n_l}.$
Then $G = S_1 \times \dots \times S_k,$ where $|S_i|=p_i^{n_i}$ and since any Sylow subgroups can written as a direct product of cyclic groups.
It can be written as $S_i = A_{i1} \times \dots A_{ik},$ where $A_{ij} = \langle a_{ij} \rangle,$ and $|A_{ij}| = p_i^{a_j}$ and $a_1 + \dots + a_k = n_i$
simlarly holds for $G^{\prime}.$
what can i do next ? I am struck with it ?
Answer: If $G\cong G'$, then of course also their Sylow subgroups are isomorphic. So we only need to show the converse direction. If all Sylow subgroups of $G$ and $G'$ are isomorphic, then also $G$ and $G'$ are isomorphic, since every abelian group is the direct product of its Sylow subgroups:
$$
G=P_1\times \cdots \times P_r\cong P_1'\times \cdots \times P_r'=G'.
$$
Comment: After rewriting we have $G=G'$. So of course, their Sylow subgroups are also the same, i.e., $P_i=P_i'$. What is there not to understand? Do you know what $G$ isomorphic to $G'$ means?
Comment: Why if G≅G′, then their Sylow subgroups are isomorphic ?
Comment: Because then $G$ and $G'$ can be considered "the same", and "everything" of them then is equal.
Comment: I dont understand.


Prove that $\lim\limits_{n \to +\infty} \int_0^1 f(t)\sin(nt^2)dt$ exists

Question: Problem: Suppose $f:[0,1] \to \mathbb{R}$ is continuous. Define $a_n=\int_0^1 f(t)\sin(nt^2)dt$. Prove that exists $\lim\limits_{n \to +\infty}a_n$.
Attempt:
I tried rewriting $a_n=\int_0^n \frac{f(\frac{\sqrt{y}}{\sqrt{n}})}{2\sqrt{ny}}\sin(y)dy$. Then I would define $I_k=[\sqrt{k\pi},\sqrt{(k+1)\pi}]$ and get that: $$\int_{[0,(k+1)\pi]}\frac{f(\frac{\sqrt{y}}{\sqrt{n}})}{2\sqrt{ny}}\sin(y)dy=\int_0^1 \frac{\sin(y)}{2\sqrt{n}}[\sum_{j=0}^k (-1)^j\frac{f(\frac{\sqrt{y+j\pi}}{\sqrt{n}})}{\sqrt{y+j\pi}}]dy$$
but I do not know if it helps.
Answer: Let $t=\sqrt s$ in the integral defining $a_n.$ We get
$$a_n=\int_0^1 \frac{f(\sqrt s)}{2\sqrt s} \sin (ns) \,ds.$$
Since $\dfrac{f(\sqrt s)}{2\sqrt s}\in L^1[0,1],$ the Riemann Lebesgue lemma implies $a_n\to 0$ as $n\to \infty.$
Comment: Awesome answer.
Comment: @DionelJaime  Thank you.
Answer: Not only does $a_n$ converge, but we have that
$$\lim_{n\to\infty}2\sqrt{n}\cdot a_n=\sqrt{\frac{\pi}{2}}f(0)$$
and thus by extention
$$\lim_{n\to\infty}a_n=0$$
To get this we let $g(x)=f(\sqrt{x})$, since this is just as well an arbitrary real valued function. We note that the differentiable functions $k:[0,1]\to\mathbb{R}$ with $\sup_{x\in[0,1]}|f'(x)|<\infty$ are dense in the full set of continuous functions $[0,1]\to\mathbb{R}$, we we may assume $f$ is of this sort and then use the trial observation that if $\sup|g(x)-k(x)|<\epsilon$ then
$$\left|\int_0^1g(t^2)\sin(nt^2)dt-\int_0^1k(t^2)\sin(nt^2)dt\right|<\epsilon$$
so we can apply epsilon-delta from the density. Note that the compactness of the interval $[0,1]$ is very important for this step.
We can now apply integration by parts on $a_n$ to see that
\begin{align*}
&\frac{1}{2\sqrt{n}}\int_0^ng\left(y/n\right)\frac{\sin(y)}{\sqrt{y}}dy\\
&=\left.\frac{1}{2\sqrt{n}}\cdot g\left(y/n\right)\left(\int_0^y\frac{\sin(x)}{\sqrt{x}}dx\right)\right]_0^n-\frac{1}{2\sqrt{n}}\cdot\frac{1}{n}\int_0^ng'\left(y/n\right)\left(\int_0^y\frac{\sin(x)}{\sqrt{x}}dx\right)dy
\end{align*}
It is a well known fact (see, for example, Wolfram Alpha) that
$$\lim_{n\to\infty}\int_0^n \frac{\sin(x)}{x}dx=\sqrt{\frac{\pi}{2}}$$
as $n\to\infty$ we have
$$\left.g\left(y/n\right)\left(\int_0^y\frac{\sin(x)}{\sqrt{x}}dx\right)\right]_0^n\to \sqrt{\frac{\pi}{2}}\cdot g(1)$$
Turning our attention now to the second part of our expression, we note that
$$\frac{1}{n}\int_0^ng'\left(y/n\right)\left(\int_0^y\frac{\sin(x)}{\sqrt{x}}dx-\sqrt{\frac{\pi}{2}}\right)dy$$
tends to $0$ by a simple $\epsilon-\delta$ argument using the boundedness of $g'(y/n)$. This means that
\begin{align*}
\frac{1}{n}\int_0^ng'\left(y/n\right)\left(\int_0^y\frac{\sin(x)}{\sqrt{x}}dx\right)dy&\to \sqrt{\frac{\pi}{2}}\cdot\frac{1}{n}\int_0^ng'\left(y/n\right)dy\\
&=\sqrt{\frac{\pi}{2}}\cdot \left(g(1)-g(0)\right)
\end{align*}
Collecting these results, we get that
$$\lim_{n\to\infty}2\sqrt{n}a_n=\sqrt{\frac{\pi}{2}}\cdot g(0)$$
Since $g(0)=k(0)$ we, apply our density argument and we are done.


loop bus waiting time with randomly stopping

Question:
A bus runs on a loop. It takes to the bus 10min to complete the loop. You go to the bus station at random times. Along the way the bus driver randomly stops for 10 min with a $p$ chance (only one time each loop). What is the expected waiting time?

I saw series of answers. I just want to confirm my understanding.
The bus will stop randomly in a loop (station to station). Suppose bus stopped at $x$ min from station. When you arrived station,

if bus is after the stopping place (>x), the probability of stopping is 0;

if bus is before the stopping place (<x), the probability of stopping is $p.$

Therefore, bus will stop with probability $x/10*p.$ So the expected waiting time is
$$5 + \int^{10}_010*(\dfrac{x}{10}*p)\dfrac{1}{10}dx=5+5p.$$
Am I right?
Comment: does sitting on the bus in the station count as waiting
Comment: I doubt $5+p/2$ is correct.  If $p=0$ (the bus never stops) then you would get $5$ as you have.  But if $p=1$ (the bus always stops) then you would get $10$ rather than $5.5$.  Why do you have $(\dfrac{x}{10}*p)\dfrac{1}{10}$?
Comment: @Henry sorry I forget to multiplying 10,  the answer should be $5+5p.$ And pls see my update.
Answer: You can do it simpler without having to worry about the distribution of the stopping place (it's true even when the stopping place isn't uniform).
If the bus doesn't stop, the expected time is $5$ (expectation of uniform distribution). It doesn't matter whether or not the speed of the bus is constant.
If the bus does stop along the way, the expected time is $10$. Again, expectation of a uniform distribution. As before, it doesn't matter whether the speed of the bus is constant (in particular, that it is $0$ for $10$ minutes straight).
So the total expectation is $$E(\text{wait time} \mid \text{no stop}) P(\text{no stop}) + E(\text{wait time} \mid \text{stop}) P(\text{stop}) = 5 \cdot (1-p) + 10 \cdot p \,.$$
Answer: If you're refering to wait time before the bus leaves the station, the average time to complete a journey is $10p + 10$ minutes. On average the bus is half way through its journey so you can expect to wait $5p + 5$ minutes before the bus leaves from the station.
If you are referring to time spent waiting to get on the bus, the probability that the bus is already at the station is $p/2$ and the average wait time when the bus isn't at the station is 5 minutes.
$\frac{p}{2}\cdot0+\left(1-\frac{p}{2}\right)\cdot5=5-\frac{5p}{2}$
Comment: I think $5p+5$ is what I mean. But how to understand average adding (stopping) time is $10p/2$ directly rather than using conditional probability?


Why isn't code for $op == 'presave' being executed in hook_nodeapi?

Question: I want the administrator users can publish nodes of the story content type; the other roles can unpublish. The following is the code I am using, but it doesn't work. I unchecked the box "published", which is in the "story" content type.
   function mymodulename_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
     global $user;

     if ($op== 'presave' && $node->type == 'story') {
       if (in_array('administrator',array_values($user->roles))) {
         $node->status = 1;
       }
     }
   }

I am using echo 'test' above on the if ($op....), the page outputs "test." When I put the echo 'test' into if body, the page doesn't output "test." but When I delete $op == 'presave', it can output "test."
Comment: Generally it's not a good practice to directly refer to a role from code that manage user rights. Instead you should check for a specific permission and grant this permission to user with this role.
Comment: It's enough you use `user_access('permission to check')`.
Comment: Use `dpm()` from the devel module and `dpm($user)`.
You can also add a `dpm($op)` just after the `global $user` to see which operations are executed.
Comment: Passing `$user->roles` to `array_values()` is not necessary; `$user->roles` can be passed directly to `in_array()`.
Comment: Drupol, the global $user can be execusted, because When I put the echo 'test' into if body, the page doesn't output "test." but When I delete $op == 'presave', it can output "test."
Comment: kiamlaluno,why i couldn't by means of the hook_nodeapi to change the publish status?thank you
Comment: could you tell me how to do that? thank you.
Comment: @enjoylife Do you actually have a role called 'administrator'?
Answer: Regarding your problem, you're editing the node right ? Because presave acts during saving.
On a site I use this module which is quite handy, maybe it can help you: Publish Content


Framework Python Open-ID

Question: Galera, estou com um problema.
Não acho que o stack seja o melhor lugar para perguntar mas não sei exatamente aonde perguntar isso.
Como todos sabem, o OpenId 2.0 não terá mais suporte da google o que nos obriga a alterar nossas aplicações para OpenId Connect(Oauth2.0).
Depois de algumas pesquisas, encontrei dois frameworks de Oauth2.0:
https://github.com/google/oauth2client
https://github.com/rohe/pyoidc
O problema é que nenhum dos dois frameworks possuem uma documentação clara sobre como serem utilizados e, antes de me aprofundar sobre algum deles para buscar a solução, resolvi perguntar aqui se alguém já utilizou algum deles ou se conhece algum outro.
Acredito que esta pergunta possa ajudar muitos aqui na comunidade, mas vou entender se optarem por fechar essa pergunta.
Obrigado
Comment: Você pretende usar OAuth só para autenticar (sua app é só um cliente) ou para emitir tokens (sua app é usada por outras apps para autenticação) ?
Comment: Só para autenticar
Answer: Caso voce queira acessar so os servicos do Google existe um lib chamada gdata[1] mantida pelo Google, aqui tem a documentacao[2], aqui[3] o Google fala um pouco mais sobre ela.
Caso queira uma lib para conectar com Oauth2.0 da uma olhada aqui[4]

[1] https://pypi.python.org/pypi/gdata
[2] http://pythonhosted.org//gdata/
[3] https://developers.google.com/gdata/articles/python_client_lib
[4] https://github.com/simplegeo/python-oauth2

Framework Python Open-ID


Poisson integral formula (Cauchy integral)

Question: Q. If f: $\Omega \rightarrow \Bbb C $ is a holomorphic function, $ 0 \in \Omega $ and $r > 0$ chosen such that $B_r(0) \subset \Omega $, show that for all $z\in B_r(0)$ that,
$$ f(z) = {1\over 2 \pi i} \int_{|w|=1} {f(w)\over w} {r^2-|z|^2 \over |w-z|^2} dw.$$
By starting with Cauchy's integral formula, $$ f(z) = {1\over 2\pi i} \int {f(w)\over (w-z)}dw $$ and subtracting an integral of the form, $$ {1\over 2 \pi i } \int {f(w) \bar z \over w\bar z-r^2}dw =0 $$ (which is zero by Cauchy's theorem), I get $$ {1\over 2\pi i} \int f(w) {r^2-|z|^2 \over(z-w)(w\bar z -r^2)}dw. $$
This appears to be along the right lines, however any advice on if this is the correct approach and/or on how to proceed is appreciated.
Answer: I think there's a typo in the question: it should be $\lvert w \rvert = r$ (otherwise the integral has a nasty singularity if $\lvert z \rvert = 1$, for one thing). Then, you have $r^2 = w\bar{w}$, so $w\bar{z}-r^2 = w(\bar{z}-\bar{w})$. Hence
$$ \frac{r^2-\lvert z \rvert^2}{(z-w)(w\bar{z}-r^2)} = \frac{r^2-\lvert z \rvert^2}{w(z-w)(\bar{z}-\bar{w})} = \frac{r^2-\lvert z \rvert^2}{w\lvert z-w\rvert^2}, $$
as you want.
Comment: Hmm, that seems to make sense, thank you!
Comment: You have to upvote those kind of questions (new user...)


Como chamar uma função PostgreSQL 9.1?

Question: Tenho uma função:
CREATE OR REPLACE FUNCTION f_2(p_vetoratributos text[], p_vetorvalores numeric[])

Estou tentando chamar:
SELECT  f_2('{"0","0","0"}', '{0,1,2,3,4,5,6,7,8,9,10,11,12,13}')

Mas ele esta dando erro:
ERRO:  operador não existe: text >= integer
LINE 1: SELECT fosforo>=8  AND  kalcio>=9
^
HINT:  Nenhum operador corresponde com o nome e o(s) tipo(s) de argumento(s) informados.
Você precisa adicionar conversões de tipo explícitas.
QUERY:  SELECT fosforo>=8  AND  kalcio>=9
CONTEXT:  PL/pgSQL function "f_2" line 14 at IF

Estou achando que a forma que estou chamando a função não está totalmente certo.
Comment: Pela mensagem de erro vc precisa converter o tipo `text`para `integer`, pode fazer isso com: `cast(campo as tipo)`.
Answer: Você expressou duas strings na chamada. Se fizer
 SELECT  '{"0","0","0"}', '{0,1,2,3,4,5,6,7,8,9,10,11,12,13}';

ou
 SELECT  '{"0","0","0"}'||'ola', '{0,1,2,3,4,5,6,7,8,9,10,11,12,13}'||'ola';

vai reparar que é realmente tudo string.
Experimente com a sintaxe tradicional (nunca falha nem tem ambiguidades),
   SELECT  array['0','0','0'], array[0,1,2,3,4,5,6,7,8,9,10,11,12,13];

aqui o meu PostgreSQL (pg) entendeu como text[] e int[]. Se sua versão de pg não entender, aí você inclui o cast... No caso, inclusive, você quer cast para tipo numeric,
   SELECT  array['0','0','0']::text[],
           array[0,1,2,3,4,5,6,7,8,9,10,11,12,13]::numeric[];

Ou seja...
Solução
 SELECT  f_2(array['0','0','0']::text[], array[0,1,2,3,4,5,6,7,8,9,10,11,12,13]::numeric[]);

Como chamar uma função PostgreSQL 9.1?


On the projection onto the image set of an $m\times n$ matrix

Question: I came accross as statement that:  "If $K$ is the image set of an $m\times n$ matrix $A$ with full column rank, then $$P_Kx=A(A^TA)^{-1}A^Tx."$$
How do I verify this?
I know that the inequality $\langle x-z, y-z\rangle\leq 0, \,\,\,\forall y\in K$ holds if and only if $z=P_Kx$. But I can't see how to show that this inequality is true here.
Comment: There's no inequality there
Answer: $P_K$ acting on any element $Ay$ of $K$ yields $A(A^\top A)^{-1}A^\top Ay=Ay$, so $P_K$ has the correct action on $K$. Any element $z$ of the orthogonal complement of $K$ is orthogonal to the columns of $A$, so $A^\top z=0$. Thus $K$ also has the correct action on the orthogonal complement of $K$, and thus by linearity on the entire space.


Solving for $a$ (log probably required)

Question: I need to get $c$ in terms of $a$.
Both $c, a\in \Bbb R^+$
$$
c^{2a} = c/a
$$
I'm pretty sure that log is required to solve this, but I'm not quite sure how to approach it.
Comment: How about dividing by $c$ then taking the appropriate power?
Comment: @JonathanY. Oh, that seems like it might make more sense.  It just seemed to me like log would be needed, because of the powers
Answer: Since $c>0$, we may divide both sides by $c$ to obtain:
$$
c^{2a-1} = \frac1a
$$
To undo the exponent, we raise both sides of the equation to the power of $\dfrac{1}{2a-1}$ to obtain:
$$
c= \left(\frac1a\right)^{\dfrac{1}{2a-1}}
$$
Comment: It should probably be pointed out that this doesn't work if $a=\frac{1}{2}$; however, in that case the equation is $c=c/a$, so that either $a=1$ or $c=0$.
Comment: Well, it can't.  So that tells you that $c=0$. :-P
Comment: @NicholasR.Peterson If $a=\frac{1}{2}$, how can $a=1$?

Solving for $a$ (log probably required)


What is the technique used in Beethoven's "Für Elise"

Question: People say that Beethoven's "Für Elise" is in ABACA structure. What does that actually mean?
Comment: I am flagging this - please restrict one post to one question.
Comment: I agree this is a bit confusing. Technique, musical structure, and the presence of an unexpected note are all three separate topics that are not related at all.
Answer: There's a D# because it sounds good!! Why shouldn't there be? There is no rule (at least that needs following) about which notes should or shouldn't be in a piece in a particular key! It's more than likely some teacher has said 'you can't use that note, cos it's not in the key'. A bit like when you're 5, you're told you can't take 7 away from 4...
The structure is a different issue, and A, B and C are sections. When a section re-occurs, its label (A or B), is stated again. Any new section needs a new name/letter.
Comment: If a piece of music was restricted to using the notes of one scale, we wouldn't have the term 'Chromatic note'.
Answer: That is in reference to the form of the piece. You would have a A section, a B section and a C section and this refers as to how you move between them and how you move from them. In a broader sense you could call this Form Analysis
Comment: Moving *between* sections or moving *from them* doesn't make the sections. The sections are entities in themselves - A, B and C.
Answer: ABACA structure simply means that there are 3 'repeated ideas'/sections: A, B and C.
It is the structure of the piece. Section A is played, followed by a different section B, then returning to A, to C and finishing in a cyclical structure with section A.
Under analysis, Für Elise does have this structure.


Why my BottomNavBar doesn't update when I use Obx wherease it works fine when I use Getbuilder?

Question: I have started learning getx lately, for a moment I thought that I understood how it works, but I get stack to this issues, where my navigator bar upated really fine when I use Getbuilder and it doesn't work when I use Obx, actually it work only when I use hotreaload otherwise it doesn't work, why? this is my controller
class DashboardController extends GetxController{
      RxInt navBarIndexController= 0.obs;

      void navbarController(int index){
        this.navBarIndexController= RxInt(index);
        print(index);
      }
    }

   class DashBoard extends StatelessWidget {
     static const String PageName = "/dashboard";
      List<Item> ItemsList = [
        Item(wilaya: 'Setif', itemname: 'Table de menage', ProfilePicturePath: 'assets/images/zahrou.jpg', surname: 'Soualem', FavCounts: 300, ImagePath: 'assets/images/posters.jpg', name: 'Zahreddine'),
        Item(wilaya: 'Alger', itemname: 'Trainers', ProfilePicturePath: 'assets/images/zahrou.jpg', surname: 'Benaouda', FavCounts: 10, ImagePath: 'assets/images/trainers.jpg', name: 'Chouaib'),
        Item(wilaya: 'Oran', itemname: 'Bags', ProfilePicturePath: 'assets/images/zahrou.jpg', surname: 'Djidel', FavCounts: 378, ImagePath: 'assets/images/postersin.jpg', name: 'Akrem'),
        Item(wilaya: 'Annaba', itemname: 'Phone', ProfilePicturePath: 'assets/images/zahrou.jpg', surname: 'Djemmal', FavCounts: 400, ImagePath: 'assets/images/Angle.jpg', name: 'Islem'),
     ];

      final controller = Get.put(DashboardController());
     @override
     Widget build(BuildContext context) {
       double height = MediaQuery.of(context).size.height;
       double width = MediaQuery.of(context).size.width;
       return     Obx(() => Scaffold(

               bottomNavigationBar: BottomNavigationBar(
                 type:BottomNavigationBarType.fixed,
                 onTap: controller.navbarController ,
                 currentIndex: controller.navBarIndexController.value,
                 selectedItemColor: Colors.green,
                 unselectedItemColor: Colors.black ,
                 showSelectedLabels:false,
                 showUnselectedLabels: false,
                 items: [
                   BottomNavigationBarItem(icon: Icon(Icons.home_outlined,),title:Text("home")),
                   BottomNavigationBarItem(icon: Icon(Icons.favorite_outline,),title:Text("home")),
                   BottomNavigationBarItem(icon: Icon(Icons.shopping_bag_outlined,),title:Text("home")),
                   BottomNavigationBarItem(icon: Icon(FontAwesomeIcons.bell,),title:Text("home")),
                   BottomNavigationBarItem(icon: Icon(Icons.account_circle_outlined,),title:Text("home")),
                 ],
               ),

             ),
       );
         }

   }

This is where the problemm appears
Answer: You just need to change this
this.navBarIndexController= RxInt(index); // not the way to update values of Rx types

to this
navBarIndexController.value = index;

Or another shorthand way where you don't have to use .value
navBarIndexController(index);


Resolvido - Reescrever HTTP para HTTPS com Let's Encrypt

Question: Tenho o arquivo .htaccess com o seguinte conteúdo:
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l

RewriteRule ^(.+)$ index.php?path=$1 [QSA,L]

Ao carregar a página preciso que já seja exibido o https://...
Mas somente quando clico nos links internos é exibido o certificado.
Não entendo muito bem destas instruções. Sei que o site utiliza a estrutura MVC, por isso esta configuração no .htaccess
Possuo também um config.php, que contém algumas configurações e a seguinte linha:
define( 'HOME_URI', 'http://meusite.com/' );

Desde já agradeço a todos!
Answer: adicione as seguintes linhas abaixo do rewriteEngine ON e abaixo das suas rewriteCond
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

ficando assim o codigo
RewriteEngine On

RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l

RewriteRule ^(.+)$ index.php?path=$1 [QSA,L]

isso vai fazer com que toda requisição http seja redirecionada para https
Comment: Obrigado Gilmar pela contribuição.Mas a pagina acusa o seguinte erro: "Redirecionamento em excesso por meusite.com
ERR_TOO_MANY_REDIRECTS"
Comment: Então tente no lugar daquelas duas linhas, essas duas:

RewriteCond %{SERVER_PORT} 80

RewriteRule ^(.*)$ https://seudominio.com.br/$1 [R,L]

O editor aqui não deixa dar enter, mais cada Rewrite, é uma linha
Comment: meu amigo, o negócio ficou punk aqui. Ele reescreveu a URL com o caminho do servidor: http://wacabinetsorlando.com/var/www/html/wacabinetsorlando.com/web/wacabinetsorlando.com/
Comment: entrei em contato com o Uol Hosts, e o problema estava na configuração deles!


Logic formulas. Deciding if one of them implies other.

Question: Let $\varphi$ will be $\forall x\forall y(y =f(g(x)) \to(\exists u(u=f(x)\land y =g(u))))$ and $\psi=\forall x[f(g(f(x))) =g(f(f(x)))]$
Decide if $\{\psi\}\models\varphi$.
Can aynone help me solve it ? I have no idea how to start.
Comment: Please double check that you wrote the problem correctly.  The first formula is very strange.
Comment: Are you assuming $f$ and $g$ are total functions?  Otherwise it seems to be undecidable.
Comment: Yes, It is written correctly
Answer: The problem is to find counterexamples $f$ and $g$ that make $\psi \vdash \varphi$ untrue.  I recommend starting by simplifying both formulas (I'll be leaving parenthesis off unary function applications, and treating them as binding to the right):
$$\forall x \forall y~(y = fgx \to \exists u ~ (y = gu \land u = fx))$$
Apply the rule $\forall q ~ (q = r \to Pq) \equiv Pr$ :
$$\forall x \exists u~(fgx = gu \land u = fx)$$
Now we know that since $f$ is a function, there is always a $u$ such that $u=fx$ (assuming $f$ is not the empty set...check the case of $f=\emptyset$ separately to see if it is a counterexample).  So this can again be simplified:
$$\forall x ~ (fgx = gfx)$$
So $\varphi$ is equivalent to the claim "$f$ and $g$ are inverses over the entire universe".

Then second formula to be simplified:
$$\forall x~(fgfx = gffx)$$
If $If$ is the Image of $f$, then prior is equal to:
$$\forall y \in If~(fgy = gfy)$$
Alpha transform:
$$\forall x \in If~(fgx = gfx)$$
So $\psi$ is equivalent to the claim "$f$ and $g$ are inverses over the image of $f$".

So the problem becomes determining if you can find $f$ and $g$ that are counter examples to :
$$\forall x \in If~(fgx = gfx) \vdash \forall x ~ (fgx = gfx)$$
In other words, can you find 2 functions, $f$ and $g$, such that they are inverses in the Image of $f$, but otherwise not inverses?  You can choose any universe for the domain that you like.  If you want to see my answer, hover over the following solution (please try to find your own counterexample or reason to believe there isn't a counterexample first):

 $$\begin{array} {l} \text{Domain = Real numbers from 0 to 2} \\ f(x) = \frac{1}{2}x \\ g(x) = \begin{cases} x \le 1 & 2 \cdot x \\ x \ge 1 & 2 \end{cases} \end{array}$$
Comment: Assuming your domain is integers, it looks good.  Try putting it into the original formulas and seeing what you get.
Comment: @HaskellFun Actually if you choose a finite domain (like 0, 1, and 2) then the original formulas are trivially computable.
Comment: @HaskellFun Plug it in and check~
Comment: My counter example is:   $$f(x)= x \mod 2$$ $$g(x)=x^2$$. Ok ?
Comment: My domain for $f,g$ is $\mathbb{N}$ Ok ?
Comment: Thanks you very much for your help!


Issue retrieving UserID inside SignalR hub

Question: I had my SignalR private chat system working when it was forcing client updates for every client connected but I wanted to streamline this so only update specific connected users when they specifically receive new messages. Using the posted "Mapping SignalR users to connections" on msdn I set everything up and it logs and changes connection IDs and users but as soon as I want to retrieve their assoicated UserID for my Sql query I get Null?
As stated above, the query worked fine when I was using HTTPContext.User.Identity.GetUserId() to retrieve the users GUID but now I have updated the code I can no longer get the currently connected UsersID no matter what I do. Even though the associated database functions have NO issue retrieving the current users UserName...
<code>public override Task OnConnected()
{
var name = Context.User.Identity.Name;
who = Context.User.Identity.Name;
UserID = Context.User.Identity.GetUserId();
.....
}

string query = "SELECT msgTo, msgFrom, msgContent, date FROM [dbo].[messages] WHERE msgTo = @id";
connection.Open();
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("@id", UserID);
try
{
  ...
}
</code>
The parameterized query '(@id nvarchar(4000))SELECT  msgTo, msgFrom, msgContent, date FRO' expects the parameter '@id', which was not supplied.
Comment: so, your `Context.User.Identity.GetUserId()` return `null` right? What is in your `Context.User.Identity` then?
Comment: Context.User.Identity is System.Security.Claims.ClaimsIdentity
Comment: I have found the cause of the issue; Upon initial connection the UserId is retrieved fine, but if a message is received then the userid cannot be retrieved. I recall reading something about the fact that asp.net doesn't sent the user information with every single request(which makes sense).
Answer: I managed to fix it by sending a querystring with each request($.connection.hub.qs = { userId: document.getElementById("usrid").value};) and then retrieving it in the hub update function


Given a deck of cards, what are the odds of consecutively drawing higher cards for a given number of draws?

Question: Lets say you're trying to draw n cards, each higher than the last. How likely are you to succeed in consecutively drawing higher for a given starting number & number of iterations?
Somebody said to add my thoughts to the question! We've had a lot (my brother and i are trying to solve it!) so wait just a few minutes while I write it all out!
So first we tried by thinking about some easy cases. Lets say you only wanted 3 consecutive higher draws. If you drew a king or a queen you're done right off the bat, the odds of that are 8/52. If you drew a Jack, you have to get the sequence of JQK to succeed. That's $4/52* 4/51*4/50$. From this we can't yet establish too much, but we found a general way to answer this problem for three draws. If you start with a Jack, there is one way, a 10 in three ways, a 9 in six ways, an 8 in 10 ways... each drop in card number adds one more positive outcome than the last drop did (K-Q added zero, Q-J added one, J-10 added two, 10-9 added three etc).  So the equation is $1(4/52 * 4/51 * 4/50) + 3(4/52 * 4/51 * 4/50) + 6(4/52 * 4/51 * 4/50)... + 66(4/52 * 4/51 * 4/50)$. (<- if we aren't mistaken)
Around here is where we have gotten stuck as brute force gets more difficult and we don't yet have an overarching formula to apply.
Any ideas of where to go from here to apply this to higher numbers of draws?
BIG EDIT (unless we're super wrong... not 100% sure of proper math notation)
Okay... so our thought process from where we left off is as follows:
If we're drawing four cards instead of three, the sum is the same except the 66 term is lobbed off (because the 1,3,6,10... series starts a number lower [in the case of 4 cards, you can't draw a jack first] and ends at the same place, thereby eliminating one term) and the inside term gains 4/49 (signifying the probability of another drawn card). The equation would be: $1(4/52 * 4/51 * 4/50 * 4/49) + 3(4/52 * 4/51 * 4/50 * 4/49) + 6(4/52 * 4/51 * 4/50 * 4/49)... + 55(4/52 * 4/51 * 4/50 * 4/49)$. Notice the similarities between the equation for drawing three cards and drawing four.
From this, we derived the (hopefully correct) formula for any number of draws.
let x = number of cards you want to draw.
let y = the value of the first card drawn.
Note: in the following, $n_{-1} = 0$
$$\sum_{n=0}^{14-x}((n + n_{n-1} +1)*(\prod_{n=0}^{x}(4/(52-n))))$$
Posting for now, any questions will be addressed after we eat dinner.
Comment: Welcome to MSE.  You'll get a lot more help, and fewer votes to close, if you show that you have made a real effort to solve the problem yourself.  What are your thoughts?  What have you tried?  How far did you get?  Where are you stuck?  This question is likely to be closed if you don't add more context.  Please respond by **editing the question body.**  Many people browsing questions will vote to close without reading the comments.
Comment: What have you tried?  Where did you get stuck?
Comment: Updated the body with our attempts. Any thoughts? Thanks.
Comment: @That clarifies the problem a bit.  I think you should be explicit that "high" means higher face value regardless of suit.  Right?  You don't allow $K\spadesuit$ then $K\heartsuit$, right?
Comment: Hi David, thanks for the question. Yes, we are disregarding suit here.
Answer: First of all, as I can see, you dont know very much about probability, so my suggestion is that, if you are interested in these kind of questions about probability of games, try to read a book about it! By example books as Introduction to probability with Texas Hold'em!, or The mathematics of Games: An Introduction to Probability, or Probability and Games, or Probability and Statistics. A Didactic Introduction seems suitable for you.
For the case in hand: probability in many situations can be evaluated as number of valid cases divided by the number of all possible cases.
A simpler general case:
If you have a list of numbers from one to $n$ (for some $n\in {\mathbb N}$) and you want to know what is the probability to get a list of $j$ numbers, taken without replacement such that each number is greater than the precedent then you need to count two things:

The number of different lists of length $j$ of numbers  with the desired properties, taken from a bag with $n$ distinct numbers.
The total number of different list of numbers of length $j$, taken from a bag with $n$ distinct numbers.

To count the lists of 1. we can notice that after draw any list of length $j$ it can be ordered from the lowest to the higher number, therefore for any distinct set of $j$ numbers there is a unique ordered list, so 1. is equivalent to count all possible distinct subsets of $\{1,\ldots,n\}$ of length $j$, this number is just $\binom{n}{j}$.
The second number, this said in 2., is just all possible ordered lists of length $j$ given $n$ possible distinct values for each number of the list, this is known in combinatorics as variations of length $j$ out of $n$ possible numbers, and is just $n^{\underline{j}}:= \prod_{k=0}^{n-j+1}(n-k)$.
Therefore the probability would be
$$
\frac{\binom{n}{j}}{n^{\underline{j}}}= \frac1{j!}
$$
where $j!:=1\cdot 2\cdots j$.
The probability of the question:
Your case with cards is a little more complicate to handle because a deck of 52 cards have each rank repeated four times (that is, there are four cards of the same "value"), then the number of lists in 1. cannot be calculated in the same way for this probability. However is not too much complicate: we only need to count for every list of 1. (with $n=13$) all possible variations where each card can be of one of four suits, that is for each valid list of length $j$ there are $4^j$ distinct possible variations of the same depending of the suits of the cards, therefore the probability of your question is
$$
\frac{\binom{13}{j}\cdot 4^j}{52^{\underline{j}}}
$$
This number doesn't seem that could be simplified significantly, so I leave it like this.
If you start from a given rank, namely the rank $m$ (of $13$ possible distinct ranks) and a list of ranks of length $j$, then the number of valid lists of length $j$ and ranks greater than $m$ are in one to one correspondence with the number of subsets of $\{m+1,\ldots,13\}$ of length $j$, each one multiplied by $4^j$ that represent the number of variations due to the four possible suits for each card, therefore $ \binom{13-m}{j}4^j$ are all possible distinct increasing lists of length $j$ of ranks greater than $m$, therefore the corresponding probability will be
$$
p_{m,j}:=\frac{\binom{13-m}{j}\cdot 4^j}{52^{\underline{j}}}
$$
Now suppose that you want to know what is the probability to succeed in $n$ tries, where a try is not a draw: it is just an attempt to get $j$ cards of the deck suck that they are increasing in it ranks and the minimum rank is greater than $m$. If you dont get a valid list then you put the cards again in the deck, shuffle, and try again; then the possibility to get a valid list of cards in $n$ tries would be $F_X(n)$, where $F_X$ is the cumulative distribution function of a random variable $X$ with geometric distribution of parameter $p_{m,j}$, that is, it would be $F_X(n)=1-(1-p_{m,j})^n$.
Now: to know the probability, after $n$ draws, to get some increasing sublist of length $j$ in this list of $n$ cards, of ranks greater than $m$, you need to count all these lists and divide by the total number of lists of length $n$. However this count is not easy to handle, it seems better suited for a computer.
Comment: Thanks! Just read through your answer, yes it's definitely a bit beyond me! But it is fascinating! I'm certainly no probability pro, not even through highschool yet :) but thank you! And thanks for the book recommendations
Comment: @KarrsenB if you like it consider to accept the answer
Answer: The probability changes after the 1st draw, but it also changes after the 2nd draw. If you have three draws: i, j,k corresponding to the 1st, 2nd, and 3rd draw, then you have:
$$ P(j>i) = \sum_{j=i+1}^{13} \frac{4}{51} $$
$$ P(k>j) =  \sum_{k=j+1}^{13} \frac{4}{50} $$
$$ P(k>j) \cap  P(j>i) =  \sum_{j=i+1}^{13} \sum_{k=j+1}^{13} \frac{4}{51} * \frac{4}{50}  $$
Plugging in your 1st draw, I, should give you the probability of getting two higher consecutive draws.
For a test case, let us take the Jack, 11, for the 1st draw, i. You have a 4/51 chance of getting the Queen (if you get the King, you lose) then you have a 4/50 chance of getting the king.
Another test case, let us take the 10 as the 1st draw, i. You have a 8/51 chance of getting the Jack or Queen. If you get the Jack then you have a 8/50 chance of getting a Queen or King. If you get the Queen, you have a 4/50 chance of getting the king. So 8/51*8/50 + 8/51*4/50 = 0.018.
python code:
<code>def proba_higher_consecutive_draws(i):
    result = 0
    for j in np.arange(i+1,14):
        for k in np.arange(j+1,14):
            result+=4/51*4/50
    return result

i=11
proba_higher_consecutive_draws(i)
</code>


How to measure correlation between variance and rank?

Question: I have an independent variable is a manipulation/predictor which is applied in increasing degrees of strength across groups. The independent variable alters the amount of variation in the dependent variable.
Because we are looking at variance, I cannot use Spearman's Rho to calculate correlation without a weird hack (detailed below).
What is the best way to measure the correlation of variance?
In non-mathematical terms,  I am testing if increasing the use of a metaphor/mental model unifies responses.  If the mental model alters the way people think about a problem, then increasing the "reminders" of this mental model should unify the responses.
There are 5 independent groups, 0-4, ranked according to the number of "reminders" in each one.  As the reminders are qualitatively different, I must use ranks.
If one examines the SD of each group according to rank, they line up almost perfectly:
SD - group
drop down

.639 - drop down menu

radio buttons

.604 - vertical
.484 - horizontal

slider

.5515
.4504 - colored

Group Averages

.639
.544
.501

That's a difference of ~15% and ~8%, albeit a very rough and indirect way of measuring change in variance.  However, Bartlett and Levene's tests confirm a statistically significant difference in the variance between the groups.
However, neither Spearman nor Kendall look at variance directly, so a difference of -1 and +1 will negate each other using these measures.  If I combine the two extreme scores (0-1-2 -> 0-1) then I get a Spearman's of .142 with a sig <.001.
While I think this is a defensible hack, it doesn't seem to match up with my ad-hoc analysis above.
Comment: Thanks. So you mean that the shape of the response distribution (in particular, its variance, or maybe its spread) differs depending on the level of your independent variable? However, you end up with a 3-level discrete response variable (taking values in {0,1,2}): what would a variance test, usually applied on a continuous measure, mean in that case? What about your independent variable: Is it continuous or discrete like your outcome?
Comment: Why did you consider absolute values if you are interested in the dispersion of the response distribution on the original scale?
Comment: I am testing for extremes on a Likert scale, so strong agreement/disagreement are no different since they are both strong feelings.
Comment: The independent variables are discrete; "slider", "colored" slider, and "drop-down".
Comment: @chl I've reformulated this question, would you mind taking another crack?
Answer: You could model the variance explicitly specifying a shared mean and only the variance with a Maximum Likelihood Formation such as
$$    \max_{\hat\gamma_0,\hat\gamma_1} (\sum_{i=1}(ln(D(x_i, \hat\mu, \hat\gamma_0+\hat\gamma_1 rank)))$$
Where D is the PDF of a distribution of your choice in which the mean is specified as the first argument ($\mu$) and the second argument specifies the variance.
I show how to do this in R using a normal distribution.
This will not directly give you a correlation between rank and variance but you can approximate such a correlation by transforming the coefficient (using $cor(x,y)=cov(x,y)/sd(x)sd(y)$ and $\hat \beta=cov(x,y)/var(x))$
  $$\hat {cor}_{rank,var}=\hat\gamma_1 \hat {sd({\gamma_1})}/\hat {sd}({rank})$$
Note, because $\hat \beta=cov(x,y)/var(x))$ is only true in OLS the above transformation is at best only an approximation.
But really, you don't need the "correlation" when you have a more interesting statistic generated directly from the MLE estimation: "How does variance change with respect to a one unit change in ranking?"
Comment: Well, this is proof that I need SE Q/A.  From what I can tell, this looks correct.  I need to run it past my professor before I really grok the answer, however.  As to your latter comment, I'm guessing that it hits on the problem I had with Spearman's Rho.
Answer: One option is to report the ratio of the larger to the smaller standard deviations or the ratio of the larger to the smaller variance for the two groups. Such a metric is more comparable than the raw difference in standard deviation or variance with different studies that are on different scales.
Answer: Perhaps this solution is overly simplistic. If so, could you please provide a reference to prove me wrong?
What if we just take regression of DV with respect to case/control CV and all confounders, and then apply Levene's test to residuals?
Since we only care about variability in dv between groups defined by values of cv, let's regress out all confounding factors iv1, iv2, etc. as follows:
library('lawstat')
library('xlsx')
d <- read.xlsx('DV-CV-and-confounders.xlsx',1)
m <- lm(dv ~ cv*(iv1 + iv2), data = d, na.action = na.omit)
levene.test(m$residuals, cv,
        location="median", correction.method="zero.correction",
        bootstrap=TRUE,num.bootstrap=1000)

Answer: Sounds like an analysis of a 3x3 table. How about a log-linear analysis with appropriate odds ratios of the effects?

Further edits
Loglinear regression analysis is used to describe the pattern of data in a contingency table. A model is constructed to predict the natural log of the frequency of each cell in the contingency table. For a 2x2 table, that means the model is $\ln f  = br * row + bc * col + bi * int + a $.
Your data appears to be a 3x3, three response levels (0,1,2) by three conditions (slider,colored slider,dropdown). You would construct a model to predict the natural log of the frequency of each cell in the contingency table.
Comment: Could you elaborate on your answer?  Even pointing to some examples would help.
Comment: This sounds like a Chi^2 table, so just drop in the SD's instead of the mean?


Change the bordercolor of the selecteditem from an array of objects

Question: I want to change the bordercolor of the selecteditem from my array which i'll map it on a button
array= [{id: 0, name: "josh" }, {id: 1, name: "tim"} , {id:2, name:"jonathan"}]. how can I achieve this?? if I select 1 from the button all border color's changed. Please help me, i'm new with react native. Thanks
Answer: You can create two styles, one for simple item and another for selected item. And then you can apply based on condition. Here is the example :
<code>import React from "react";
import { FlatList, TouchableOpacity, StyleSheet, Text } from "react-native";
import { useState } from "react";

const YourComponent = () => {
  const yourArray = [
    { id: 0, name: "josh" },
    { id: 1, name: "tim" },
    { id: 2, name: "jonathan" },
  ];
  const [selectedItem, setSelectedItem] = useState(null);

  return (
    <FlatList
      data={yourArray}
      extraData={yourArray}
      keyExtractor={(item) => item.id.toString()}
      renderItem={({item, index}) => (
        <TouchableOpacity
          style={[styles.listItem, selectedItem === item.id ? styles.selectedItem : null]}
          onPress={() => setSelectedItem(item.id)}
        >
          <Text>{item.name}</Text>
        </TouchableOpacity>
      )}
    />
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  listItem: {
    padding: 10,
    borderWidth: 1,
    borderColor: '#dddddd'
  },
  selectedItem: {
    borderColor: '#00ff00',
  },
});

export default YourComponent;
</code>


A question on Staccato in the end of a slur (piano playing)

Question:
A staccato note in the end of a slur( 1)
A normal staccato note(2)
question
Do I play the (1) the same as (2)?
Answer: Yes.  The slur just indicates that the note should touch the preceding note, but it's still played on time and ended according to the staccato dot.
Basically, a slur does not change the last note it reaches but only the notes before it.
Answer: You will have to play "Portato" .Portato is also known as articulated legato (Blood 2012).It is a bowing technique for stringed instruments (Anon. 2001), in which successive notes are gently re-articulated while being joined under a single continuing bow stroke. It achieves a kind of pulsation or undulation, rather than separating the notes. It has been notated in various ways. One early 19th century writer, Pierre Baillot (L'art du violon, Paris, 1834), gives two alternatives: a wavy line, and dots under a slur. Later in the century a third method became common: placing "legato" dashes (tenuto) under a slur (Wall 2001a). The notation with dots under slurs is ambiguous, because it is also used for very different bowings, including staccato and flying spiccato (Walls 2001a; Walls 2001b).
Currently, mezzo-staccato is sometimes indicated in words, by "mezzo-staccato" or "non-legato"; or can be shown by three graphic forms:
a slur that encompasses a phrase of staccato notes (the most common), or
a tenuto above a staccato mark (very often), or
a slur that encompasses a phrase of tenuto notes (less common) (Tsai 2008).
Portato is defined by some authorities as "the same as portamento" (Kennedy 1994).
Comment: This answer appears to be about violin technique, not piano. Also, if the whole answer is apparently a quote cut-and-pasted from somewhere, you should give a reference to the original source.
Comment: Portato is more to do with what happens DURING a slur, rather than the last note. All the player does in the quoted piece is cut the last note short.


Is there an upper bound on the number of primitive pythagorean triples in which some odd number can be a non-hypoteneuse edge?

Question:
Is there an upper bound on the number of primtive pythagorean triples in which some odd number can be a non-hypoteneuse edge?

Take $15$ for example, we have $15,8,17$ then $15,112,113$ but it's not clear we can keep going forever.
I suspect if infinitely many odd integers were the non-hypoteneuse edge of infinitely many primitive pythagorean triples then we might use the diagonal argument to imply uncountably many different pythagorean triples.
But that would contradict that for $a^2+b^2=c^2$ we have $\left(\dfrac{a}{c}\right)^2+\left(\dfrac{b}{c}\right)^2=1$, putting every triple into bijection with a set of rational points on the unit circle and making them countable.  So by that argument there are at most finitely many which are members of infinitely many triples.
Comment: A common divisor of $c-b$ and $c+b$ also divides $(c - b) + (c + b) = 2c$ and $(c + b) - (c - b) = 2b$. If $a$ is odd, then $c - b$ and $c + b$ are both odd, so $\gcd(c-b,c+b) = \gcd(b,c)$. So for odd $a$, the primitive Pythagorean triples containing $a$ as a leg are in bijection with the factorisations of $a^2$ into two coprime factors (where order of the factors doesn't count). Given an arbitrary $n$, can you find an $a$ that admits at least $n$ factorisations of $a^2$ into two coprime factors?
Comment: Say the number of interest is $a$. Every Pythagorean triple in which $a$ occurs as a non-hypotenuse corresponds to a factorisation $a^2 = (c-b)(c+b)$. What condition says the Pythagorean triple is primitive?
Comment: I meant, "what condition for the factorisation $(c-b)(c+b)$".
Comment: @DanielFischer I've no idea really. I can see if it wasn't primitive then $(c-b), (c+b)$ would not be coprime but I can't show the contrapositive.
Comment: @DanielFischer I think if $f(p,2)$ counts the ways to partition $p$ elements into two groups then we would require $p$ the number of distinct prime factors in $a$ to be sufficient that $n\leq f(p,2)$. Is that right?
Answer: A simple way to show there is not is to use the parameterization of primitive Pythagorean triples.  Let $m,n$ be coprime and of opposite parity.  Then $m^2-n^2,2mn,m^2+n^2$ is a primitive Pythagorean triple.  For our use, let $m$ be even and $n=1$, giving the fact that $m^2-1,2m,m^2+1$ is a Pythagorean triple.  If you want an odd number that is a leg of $k$ Pythagorean triples we start with
$$2^2-1,2\cdot 2,2^2+1\\4^2-1,2\cdot 4,4^2+1\\6^2-1,2\cdot 6,6^2+1\\ \ldots \\(2k)^2-1,2\cdot 2k,(2k)^2+1\\$$
Now multiply each by $(2^2-1)(4^2-1)(6^2-1)\ldots ((2k)^2-1)$ divided by its first element and we will have $k$ triangles all with odd leg $(2^2-1)(4^2-1)(6^2-1)\ldots ((2k)^2-1)$
Comment: @ProducerofBS:  that is correct.  I thought this was a simpler approach to answer the question by actually constructing a number that it part of at least $k$ different triangles for any given $k$.  In fact it will be part of many more for any reasonably large $k$.
Comment: thanks Ross, nice. If I understand correctly Daniel Fischer has also shown with with a bit of combinatorics it looks like we can actually derive a function for the number of triples in which any odd integer appears as a leg, based on its number of distinct prime factors.
Comment: You have answered the question so I feel bad for not accepting just yet but it would also be lovely to arrive at the formula Daniel has alluded to. I'll set aside some time to tackle it myself but in truth I judge myself unlikely to arrive at a reliable answer.
Comment: @ProducerofBS:  Daniel Fischer is talking about primitive pairs as well.  If $a$ has $p$ distinct prime factors the number of factorizations of the type he says is $2^{p-1}$.  All the powers of one prime have to go into the same factor to have the two factors coprime.  If you just take all the subsets of the set of prime factors as one factor, you count every division twice, once when you pick a set and once when you pick its complement.
Comment: Thanks. I had come to the conclusion it would be $2^{p-1}$ in fact asked exactly that here: https://math.stackexchange.com/questions/2744881/ as I wasn't totally confident in my own abilities. Happy for you to confirm that in either this answer or an answer to that.