Where to add email verification code for android app using parse

Question: Using Parse for an android app,
I am trying to add email verification concept. When data is entered and submit button is clicked, an email is sent to user. Till that time, EmailVerified=false.
Now with the same credentials, when I am trying to login, it is logging in.
Without an email verification, I am able to proceed further.
How to solve this problem?
I want to set EmailVerified=true and if true then only user can log in with that credentials.
Answer: You need to add a web service and maintain a field which shows whether the user email verification is done or not...using that you can validate the user and continue him to login...
Comment: Web service? Can you please elaborate?
Comment: We need to write a service and implement the email verification in our backend. Once it is set and when the user tries to login from your app, in the response you can send whether the user is signedup/not and also if signedup then email verified/not. using the response type we can notify the user to do the necessary email verification.
Comment: Okay. Sounds good. Can you please provide me with the link of any such codes so that I can learn from that?
Comment: Alternatively, you might use facebook/twitter to signup process or even you can use the Parse push notification mechanisms...
Answer: This is the exact answer to your question  :D
http://blog.parse.com/announcements/introducing-app-email-settings/


Rubik's Group Question - Commutators

Question: Suppose that $f: G \rightarrow S_C$ be the action of Rubik's group $G$ on the collection of $C$ of corner cubelets.
So if $C_1$ and $C_2$ be distinct corner cubelets. Show that there is a move $M \in G$ which maps FRU (front right up) to $C_1$ and FRD (front right down) to $C_2$.
Then find a move $N$ in rubiks group $G$ which exchanges the cubelets FRU and FRD but leaves all the other corner cubelets in their place.
I am really lost on the first part of this problem. And I think for the second part, I must find a commutators in order to leave the other corner cubelets in one place with just exchanging FRU and FRD. Any help would be appreciated.
Answer: For the first part, first show it for the case when $C_1$ and $C_2$ are neighbors (this is physically obvious if you fiddle around with an actual cube, moving the FRU-FR-FRD stack around as a unit; how much you prose you need to describe that as a proof is a good question).
Then show that for each possible relative position between $C_1$ and $C_2$, there is a single rotation which makes $C_1$ and $C_2$ neighbors. They can then be moved to FRU/FRD as described above.

The wording of the exercise can sound like you're supposed to use the result of the first part to solve the second, but I think that would be a misunderstanding -- there's no obvious way the first part would be helpful for the second. Instead the point is probably that you're supposed later to combine these two parts to conclude that every transposition of corners can be made (as a conjugation of the FRU-FRD exchange).
Commutators alone will not do you any good in this part, because a commutator is always an even permutation and the one you're trying to create is odd.
Observe, however that if you start by making an F quarter-turn, what you need to reach a state with FRU and FRD exchanged is just a cyclic permutations of some of the front corners. Do you know how to construct 3-cycles as commutators between two permutations whose supports intersect at a single element only?

Rubik's Group Question - Commutators


Generator matrix of $E_5$

Question:
Let $E_5$ denote the binary even weight code of length 5. Write down a generator matrix of $E_5$.

So I know the length $n = 5$ is the number of rows in the generator matrix and the number of columns will be the dimension of $E_5$.
So I firstly need to know how to work out the dimension and I can then attempt to construct the generator matrix. Please can someone give me a hint!
Answer: Think of how many degrees of freedom you have for this code.  How many bits can you fill in however you want, and still be able to use the remaining bits to make the word "even"?

Generator matrix of $E_5$


Theory behind partial least squares regression

Question: Can anyone recommend a good exposition of the theory behind partial least squares regression (available online) for someone who understands SVD and PCA?  I have looked at many sources online and have not found anything that had the right combination of rigor and accessibility.
I have looked into The Elements of Statistical Learning, which was suggested in a comment on a question asked on Cross Validated, What is partial least squares (PLS) regression and how is it different from OLS?, but I don't think that this reference does the topic justice (it's too brief to do so, and doesn't provide much theory on the subject).  From what I've read, PLS exploits linear combinations of the predictor variables, $z_i=X \varphi_i$ that maximize the covariance $ y^Tz_i $ subject to the constraints $\|\varphi_i\|=1$ and $z_i^Tz_j=0$ if $i \neq j$, where the $\varphi_i$ are chosen iteratively, in the order in which they maximize the covariance.  But even after all I've read, I'm still uncertain whether that is true, and if so, how the method is executed.
Answer: Section 3.5.2 in The Elements of Statistical Learning is useful because it puts PLS regression in the right context (of other regularization methods), but is indeed very brief, and leaves some important statements as  exercises.  In addition, it only considers a  case of a univariate dependent variable $\mathbf y$.
The literature on PLS is vast, but can be quite confusing because there are many different "flavours" of PLS: univariate versions with a single DV $\mathbf y$ (PLS1) and multivariate versions with several DVs $\mathbf Y$ (PLS2), symmetric versions treating $\mathbf X$ and $\mathbf Y$ equally and asymmetric versions ("PLS regression") treating $\mathbf X$ as independent and $\mathbf Y$ as dependent variables, versions that allow a global solution via SVD and versions that require iterative deflations to produce every next pair of PLS directions, etc. etc.
All of this has been developed in the field of chemometrics and stays somewhat disconnected from the "mainstream" statistical or machine learning literature.
The overview paper that I find most useful (and that contains many further references) is:

Rosipal & Krämer, 2006, Overview and Recent Advances in Partial
Least Squares

For a more theoretical discussion I can further recommend:

Frank & Friedman, 1993, A Statistical  View  of  Some  Chemometrics  Regression Tools

A short primer on PLS regression with univariate $y$ (aka PLS1, aka SIMPLS)
The goal of regression is to estimate $\beta$ in a linear model $y=X\beta + \epsilon$. The OLS solution $\beta=(\mathbf X^\top \mathbf X)^{-1}\mathbf X^\top \mathbf y$ enjoys many optimality properties but can suffer from overfitting. Indeed, OLS looks for $\beta$ that yields the highest possible correlation of $\mathbf X \beta$ with $\mathbf y$. If there is a lot of predictors, then it is always possible to find some linear combination that happens to have a high correlation with $\mathbf y$. This will be a spurious correlation, and such $\beta$ will usually point in a direction explaining very little variance in $\mathbf X$. Directions explaining very little variance are often very "noisy" directions. If so, then even though on training data OLS solution performs great, on testing data it will perform much worse.
In order to prevent overfitting, one uses regularization methods that essentially force $\beta$ to point into directions of high variance in $\mathbf X$ (this is also called "shrinkage" of $\beta$; see Why does shrinkage work?). One such method is principal component regression (PCR) that simply discards all low-variance directions. Another (better) method is ridge regression that smoothly penalizes low-variance directions. Yet another method is PLS1.
PLS1 replaces the OLS goal of finding $\beta$ that maximizes correlation $\operatorname{corr}(\mathbf X \beta, \mathbf y)$ with an alternative goal of finding $\beta$ with length $\|\beta\|=1$ maximizing covariance $$\operatorname{cov}(\mathbf X \beta, \mathbf y)\sim\operatorname{corr}(\mathbf X \beta, \mathbf y)\cdot\sqrt{\operatorname{var}(\mathbf X \beta)},$$ which again effectively penalizes directions of low variance.
Finding such $\beta$ (let's call it $\beta_1$) yields the first PLS component $\mathbf z_1 = \mathbf X \beta_1$. One can further look for the second (and then third, etc.) PLS component that has the highest possible covariance with $\mathbf y$ under the constraint of being uncorrelated with all the previous components. This has to be solved iteratively, as there is no closed-form solution for all components (the direction of the first component $\beta_1$ is simply given by $\mathbf X^\top \mathbf y$ normalized to unit length). When the desired number of components is extracted, PLS regression discards the original predictors and uses PLS components as new predictors; this yields some linear combination of them $\beta_z$ that can be combined with all $\beta_i$ to form the final $\beta_\mathrm{PLS}$.
Note that:

If all PLS1 components are used, then PLS will be equivalent to OLS. So the number of components serves as a regularization parameter: the lower the number, the stronger the regularization.
If the predictors $\mathbf X$ are uncorrelated and all have the same variance (i.e. $\mathbf X$ has been whitened), then there is only one PLS1 component and it is equivalent to OLS.
Weight vectors $\beta_i$ and $\beta_j$ for $i\ne j$ are not going to be orthogonal, but will yield uncorrelated components $\mathbf z_i=\mathbf X \beta_i$ and $\mathbf z_j=\mathbf X \beta_j$.

All that being said, I am not aware of any practical advantages of PLS1 regression over ridge regression (while the latter does have lots of advantages: it is continuous and not discrete, has analytical solution, is much more standard, allows kernel extensions and analytical formulas for leave-one-out cross-validation errors, etc. etc.).

Quoting from Frank & Friedman:

RR, PCR, and PLS are seen in Section 3 to operate in a similar fashion. Their principal goal is to shrink the solution coefficient vector away from the OLS solution toward directions in the predictor-variable space of
larger sample spread.  PCR and PLS are seen to shrink more heavily away
from the low spread directions than RR, which provides the optimal shrinkage (among linear estimators) for an equidirection prior. Thus
PCR and PLS make the assumption that the truth is likely to have particular preferential alignments with the high spread directions of the
predictor-variable (sample) distribution. A somewhat surprising result
is that PLS (in addition) places increased probability mass on the true
coefficient vector aligning with the $K$th principal component direction,
where $K$ is the number of PLS components used, in fact expanding the
OLS solution in that direction.

They also conduct an extensive simulation study and conclude (emphasis mine):

For the situations covered by this simulation study, one can conclude
that all of the biased methods (RR, PCR, PLS, and VSS) provide
substantial improvement over OLS. [...] In all situations, RR dominated
all of the other methods studied. PLS usually did almost as well as RR
and usually outperformed PCR, but not by very much.

Update: In the comments @cbeleites (who works in chemometrics) suggests two possible advantages of PLS over RR:

An analyst can have an a priori guess as to how many latent components should be present in the data; this will effectively allow to set a regularization strength without doing cross-validation (and there might not be enough data to do a reliable CV). Such an a priori choice of $\lambda$ might be more problematic in RR.

RR yields one single linear combination $\beta_\mathrm{RR}$ as an optimal solution. In contrast PLS with e.g. five components yields five linear combinations $\beta_i$ that are then combined to predict $y$. Original variables that are strongly inter-correlated are likely to be combined into a single PLS component (because combining them together will increase the explained variance term). So it might be possible to interpret the individual PLS components as some real latent factors driving $y$. The claim is that it is easier to interpret $\beta_1, \beta_2,$ etc., as opposed to the joint $\beta_\mathrm{PLS}$. Compare this with PCR where one can also see as an advantage that individual principal components can potentially be interpreted and assigned some qualitative meaning.
Comment: That's right, @Frank, but honestly, as far as predictive performance is concerned, I don't see much sense in doing anything else than ridge regression (or perhaps an elastic net if sparsity is desired too). My own interest in PLS is in the dimensionality reduction aspect when both $X$ and $Y$ are multivariate; so I am not very interested in how PLS performs as a regularization technique (in comparison with other regularization methods). When I have a linear model that I need to regularize, I prefer to use ridge. I wonder what's your experience here?
Comment: My experience is that ridge (quadratic penalized maximum likelihood estimation) gives superior predictions.  I think that some analysts feel that PLS is a dimensionality reduction technique in the sense of avoiding overfitting but I gather that's not the case.
Comment: I think that nomenclature can be confusing.  _Dimension reduction_ makes it sound as if the effective number of parameters being estimated is lessened.  But when associations with $Y$ are examined in order to achieve this, the number of parameters "lost" is illusory and overfitting is not avoided at least not entirely.  This is in distinction with PCA, predictor variable clustering, etc.
Comment: b) if you are going for a, say, spectroscopic interpretation of what the model does, I find it easier to look at PLS loadings what kind of substances are measured. You may find one or two substances/substance classes in there, wheras the coefficients which include all latent variables are harder to interprete because spectral contributions of more substances are combined. This is more prominent because not all of the usual spectral interpretation rules apply: a PLS model may pick some bands of a substance while ignoring others. "Normal" spectra interpretation uses a lot of this band could ...
Comment: ... come from this or that substance. If it is this substance, there must be this other band. As this latter possibility of verifying the substance is not possible with the latent variables/loadings/coefficients, interpreting things that vary together and therefore end up in the same latent variable is much easier than interpreting the coefficients that already summarize all kinds of possible "hints" that are known by the model.
Comment: That paper looks useful.  I don't think it addresses how much overfitting can be caused by PLS.
Comment: @clarpaul: I think what Frank meant is that while PLS is a regularization technique (as you say), it might not be able to "avoid overfitting" altogether; there can still be a fair amount of overfitting when using PLS (as compared e.g. with ridge regression).
Comment: @amoeba: are two very practical and very chemometric reasons I can think of: a) The external knowledge about application and data generating process can decidedly point towards a particular number of latent variables. In this situation, I check whether the data agrees with this external knowledge. If yes, fine, basically the hyperparameter optimization is eleminated. If not, this tells me that I need to understand the application problem better.
Comment: ... b) Depending on the data generating process, the latent variables can be interpreted (e.g. what their spectroscopic meaning is). This is much easier if sorted into a bunch of latent variables comparted to having just one coefficient vector.
Comment: @amoeba: I'm not saying that the best PLS model is going to outperform the best RR model, I'm trying to say that in some situations (particularly if sample size does not really allow model comparisons) to get a good (or even the best) PLS model by external knowledge without hyperparameter optimization. I do not have enough experience with RR to know whether with more experience it is possible to fix λ by similarly external knowledge.
Comment: @amoeba, regarding *I don't see much sense in doing anything else than ridge regression (or perhaps an elastic net if sparsity is desired too)*. The Zou & Hastie paper that introduced elastic net has some examples where the elastic net beats ridge regression by design. So it is not only sparsity, but also forecast accuracy where elastic net may excel above ridge. (I am working on these issues from a theoretical perspective these days.)
Comment: So for the first note (PLS1 is the same as OLS when all the latent variables are included), does it also hold when the number of predictors > the number of samples? Because in this case OLS does not have an unique solution, but PLS does, so I am a little confused. Or do you have the ref for that? Thanks!
Comment: @Vickyyy Good question. What exactly do you mean by PLS1 with all components when p>n? What are "all" components? I guess the idea is that components equal to zero are not considered? In this case, there can be only n-1 components and the PLS1 regression solution will be the same as doing PCA of X, removing all zero PCs, and then doing OLS. Another way to say it, is that it's a minimum-norm OLS solution. Anyway, I should edit to say this more explicitly -- good point.
Comment: @Frank Harrell, why do you imply PLS is not "a dimensionality reduction technique in the sense of avoiding overfitting"?  In ["Elements of Statistical Learning"](http://statweb.stanford.edu/~tibs/ElemStatLearn/printings/ESLII_print10.pdf), the topic is considered with selection and shrinkage techniques, from which I infer the authors consider it regularization-like.  It is certainly a parameter reduction technique, in that it helps "down-select" to small(er) number of coefficients from an originally very large set (e.g., one with $p > n$).  And very large sets of variables tend to overfit.
Comment: In [Elements of Statistical Learning](http://statweb.stanford.edu/~tibs/ElemStatLearn/printings/ESLII_print10.pdf), the algorithm that the authors give for PLS in section 3.5.2 runs out after only the first iteration if the variables are already orthogonalized (stated in 3.5.2; see Exercise 3.14).  So, does that imply that for cases where the data is almost orthogonal (for whatever reason) PLS brings little value?  And that to some degree, PLS is more about orthogonalization than about "uncovering latent structure" in the variables $X$ & $y$?
Comment: @clarpaul, But what *is* "uncovering latent structure"? If you run PCA on orthogonalized data, you will also get exactly the same data back; still, PCA is usually taken to "uncover latent structure". That's because we assume that latent structure manifests itself in correlations; if all correlations are zero, there is no *latent* structure. In the context of regression, if predictors $X$ are orthogonal (and if there is only one $y$) then both PCR (Section 3.5.1) and PLS will equal OLS. Note that ridge shrinkage can still be beneficial (even though it's rarely used with orthogonal $X$).
Comment: @clarpaul, I have now included an extended discussion of what PLS regression does (that might make it clearer to you), and along the way realized that PLS only yields OLS after one iteration if predictors are uncorrelated **and all have the same variance**. Hastie et al. assume that that's the case in the beginning of Section 3.5.2. Without this equal variance condition, the statement is not necessarily true.
Comment: @amoeba, thanks for your comments. When applied to orthogonal, normalized $X$ for single response $y$, PLS  creates only a single latent variable, thus not providing any guidance on feature selection at all. In PCR, the number of distinct PCA directions, and the order of preference for regression, is pre-defined and does not depend on starting point or choice of computational algorithm.  Am I wrong?
Comment: @clarpaul, you are not wrong, that's all true. I noticed that I was not correct above in my comment about PCR. So if X is orthogonal and standardized, then PLS creates only one latent variable and this be equivalent to OLS. Further, if X is orthogonal and standardized, then all directions have exactly the same variance, so PCR is sort of ill-defined... It can pick up the same latent variable as the first PC, but it can also pick up any other linear combination as the first latent variable. So it does not have to be equivalent to OLS.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/31034/discussion-between-clarpaul-and-amoeba).
Comment: @amoeba, in *Introduction to Statistical Learning*, by Hastie & Tibshirani,  the authors actually recommend "standardizing" each predictor by dividing by its standard deviation!  Can it be that there is still useful PCA data left in  $X$ after it is standardized?
Comment: @amoeba, thanks for your write-up. But in your post above, how should we interpret your statements about singular vectors of $X'y$? $X'y$ is only a vector, not a matrix, right?
Comment: (1) If all predictors are standardized and uncorrelated, then their covariance matrix is the identity matrix. There is absolutely no sense in doing PCA then. But if the predictors are correlated, then even after standardizing PCA can certainly make sense. (2) Oops, thanks for noticing. I was thinking about multivariate $Y$, when $X^\top Y$ is a whole matrix. In the case of single $y$ that we are discussing here, you are right that $X^\top y$ is only a vector, so no need for any singular vectors at all! I will now edit my post to remove this confusion. Thanks.
Comment: @clarpaul: I found one more paper that discusses theory behind PLS regression, I inserted the link into my answer and some quotes from there. Seems to be a useful paper. See also my previous comment.
Comment: @cbeleites: Thanks for joining in! (a) I am not sure I fully understand. Are you saying that you expect PLSR to outpeform RR in chemometrics applications due to certain specific properties of the data? Can you point me to some studies where this was actually shown to happen? Or what happens when the performance of PLSR is compared to RR? (b) That's interesting. So are you saying that $\beta_1$, $\beta_2$ etc. can be separately interpreted, and even though they can all in the end be joined into one single $\beta_\mathrm{PLS}$, it's easier to interpret them separately?
Comment: @FrankHarrell: I seem to remember reading that the required (recommended) sample size for training PLS and PCA based classifiers compared to unregularized linear models improves from ca. 5 to 3 cases per class and  variate. (Cannot find the source right now, possibly in the handbook of statistics vol. 2; I'm not sure about further assumptions and characteristics of the explored situations) - so some improvement, but nothing close to solving all kinds of small sample size problems.
Comment: @amoeba, the reminder that OLS maximizes corr(Xβ,y) was really really helpful to me!  Thanks for all your work on this.  But, may I suggest, you define what you mean by z_i & z_j in your Note (3)?
Comment: @amoeba, this is just a "nit", but in your write up on PLS1, don't you have to specificy that the magnitude of $ \beta_1 $ is 1?  Otherwise you'd end up with large values of $\beta_1$, in order to maximize $\sqrt{var(X\beta_1)}$.
Comment: @amoeba, I don't understand why *Frank and Friedman* say variance dominates bias where there is high collinearity.  Do you, and can you explain this: `"The solutions and hence the performance of RR, PCR, and PLS tend to be quite similar in most situations, largely because they are applied to problems involving high colli- nearity in which variance tends to dominate the bias"` It's near the end of the first paragraph of section 1.1.
Comment: Thanks, @clarpaul. I made various fixes/updates and a big addendum summarizing the points raised by cbeleites. Regarding this quote: no, it is not completely clear to me either. What is clear, is that high collinearity means a lot of variance (for the OLS estimator); that's what leads to overfitting. F&F probably mean that RR/PCR/PLS introduce bias, but it's beneficial because reduction in variance is larger (see http://stats.stackexchange.com/questions/179864/ and also *The Elements*). That's how I understand "dominates". Not sure though how this explains that RR/PCR/PLS tend to be similar.
Comment: Thanks, @cbeleites. I made an update trying to summarize your points as I understood them.
Comment: @RichardHardy Yes, I agree.
Answer: Yes. Herman Wold's book Theoretical Empiricism: A general rationale for scientific model-building is the single best exposition of PLS that I'm aware of, especially given that Wold is an originator of the approach. Not to mention that it's simply an interesting book to read and know about. In addition based on a search on Amazon, the number of references to books on PLS written in German is astonishing but it may be that the subtitle of Wold's book is part of the reason for that.
Comment: This http://www.amazon.com/Towards-Unified-Scientific-Models-Methods/dp/B007N3HZS2/ref=sr_1_1?s=books&ie=UTF8&qid=1446487159&sr=1-1&keywords=inge+helland  is related but covers much more than PLS
Comment: That is true but the primary focus of the book is Wold's development of the theory and application of PLS.
Answer: I recommend this lecture: https://www.youtube.com/watch?v=Px2otK2nZ1c by Prof Asada who explains that PLS consists of the follwoing three steps which are iterated for k times (when k components are used):

finding the directions v,w which maximize the correlation E[(xv)(yw)]
finding the parameter beta of the linear model $\hat{y} = \beta z$ (with z =xv) wich minimizes the squared residuals
deflation (removing information used in the previous two steps by updating x and y)
Comment: This is too short for an answer. Consider either expanding to provide a summary of the lecture or turning your answer into a comment under the question.


Two independent Poisson process question

Question: If I have two independent Poisson processes, X and Y, with X having a lambda 2 and Y having a lambda 3. Given that the starting value for Y is 3 and X is zero, then how do I calculate the probability of X being larger than Y at any given point, even if only for one instant in time.
I realize that I can just simulate my way out of it, but that does not really seem like an elegant solution. Any help/directions would be much appreciated.
Besides the solution below, is it possible to use the CDF and pmf of a Poisson distribution instead of only its PMF, see below.
$1-\prod_{t=1}^{\infty}\bigg[\prod_{k=0}^{\infty} \bigg [1-\bigg(1-e^{-\lambda_1*t}\cdot \sum_{i=0}^{k+D+1}\bigg[\frac{(\lambda_1*t)^{i}}{i!}\bigg]\bigg)\cdot \frac{(\lambda_2*t)^{k}*e^{-\lambda_2*t}}{k!}\bigg]\bigg]
$
My idea was that we find the probability that Poisson distribution X with Lambda 2 receives k+3+1 more occurrences conditioned on the fact that Poisson distribution Y gets equal to k occurrences. This is done for all k and then subsequently we do it for all points in time. Is this also a correct way of doing it?
Comment: You really *should* run a simulation, if only to check any analytical answers.  I might be misunderstanding your question, but my simulations produce values around $0.40$.
Comment: Hmm probably true, currently I get values around 0.30 with analytical, this is the probability that process X exceeds process Y at any given point.
Comment: @Whuber would you mind sharing your simulation code?
Answer: Pick some time point $t > 0$. We know that $X(t) \sim \text{Poisson}(2t)$ and $Y(t) - 3 \sim \text{Poisson}(3t)$. You are asking for $P(X(t) > Y(t))$. Independence comes in handy.
\begin{align}
P(X(t) > Y(t)) &= \sum_{j=1}^{\infty}\sum_{k=0}^{\infty} P[X(t) = k+j \cap Y(t) = k ] \\
&= \sum_{j=1}^{\infty}\sum_{k=0}^{\infty} P[X(t) = k+j] P[ Y(t) = k ] \\
&= \sum_{j=1}^{\infty}\sum_{k=3}^{\infty} P[X(t) = k+j] P[ Y(t) = k ] \\
&= \sum_{j=1}^{\infty}\sum_{k'=0}^{\infty} P[X(t) = k'+3+j] P[ Y(t) - 3 = k' ] \\
&= \sum_{j=1}^{\infty}\sum_{k'=0}^{\infty} \frac{e^{-2t}(2t)^{k'+3+j}}{(k'+3+j)!} \frac{e^{-3t}(3t)^{k'}}{k'!} \\
\end{align}
Edit: this might actually be simpler...
\begin{align*}
1-P(X(t)\le Y(t)) &= 1 - \sum_{i=0}^j\sum_{j=3}^{\infty}P(X(t)=j-i)P(Y(t)=j) \\
&= 1-\sum_{j=3}^{\infty} P(X(t)\le j)P(Y(t)=j) \\
&= 1-\sum_{j'=0}^{\infty} P(X(t)\le j'+3)P(Y(t)-3=j')
\end{align*}
Which you can approximate in R by typing
<code>calcProb <- function(t)
{
  sumVal <- 0
  for(jprime in 0:1000){
    sumVal <- sumVal + ppois(jprime+3, 2*t)*dpois(jprime,3*t)
  }
  return(1-sumVal)
}

#plot
t <- seq(0,50,.1)
probs <- sapply(t, calcProb)
plot(t,probs, type="l")
</code>
And you can see how this probability changes as $t$ changes. This makes sense to me because $Y(t)$ starts higher and grows faster than $X(t)$.
Comment: Thanks a bunch for the help!
I have a code snippet from R that I created before I saw your solution, we get almost the same result but not quite:

for (j in 1:100){
  for (i in 0:100){

    val=val*(1-(1-ppois(i+3,2*j))*ppois(0+i,3*j))
    print(1-val)
    }
}

As far as I can see we are doing pretty much the same thing right? But the results differ a bit.
Comment: @nonein see my edit
Comment: Awesome! This is somewhat what I ended up doing, I do have one question though when using ppois wouldn't it be 1-ppois? As we are interested in calculating the probability of exceeding?

Lastly, how come we are adding the probabilities and not multiplying them?
Comment: @nonein last question: because $P(A \cup B) = P(A) + P(B)$ if $A \cap B = \emptyset$. First question,  no, the code inside the for loop estimates the value of the sum of the last line, which has cdfs of X and pmfs of Y-3
Comment: Sorry for not understanding completely.

 Normally when wanting to the probability of event A happening conditional on event B isn't that then P(A)*P(B)? Just like we do with the pmf and CDF.

Regarind the R-code I am unsure what you mean, in the code above we multiply the probability of scoring jprime +3 or below multiplied by the probability of scoring jprime. Aren't we interested in the probability of scoring above jprime multiplied by the probability of scoring exactly jprime in poisson process Y?
Comment: You would be extremely well advised to continue your plot beyond the value of $t=10$.  Plot it to $t=50$ and see what happens.
Comment: great catch @whuber. I increased the number of iterations to 1000 so the probability doesn't go to 1 as $t \to \infty$. Definitely a mistake. It should be good now. I'll attach the picture later. For some CV doesn't like my image files right now
Comment: @nonein " Normally when wanting to the probability of event A happening conditional on event B isn't that then P(A)*P(B)? " no, definitely not. Regarding your other question, it'll be easier for me to answer if you ask me about a specific step I did
Comment: Okay, so the way I thought about the problem and structured my solution is as follows: I want the probability that either X>3 and Y=0, or X>4 and Y=1 and so forth. Thus I take the individual probability of each of these events not happening, and multiply them. 1 is subtracted from the result to arrive at the total probability at a given time t. How come you are adding the probabilities of the individual events happening? I am sorry if this seems a little confused. We ALMOST get the same results, and if there is a large difference between process X and Y the result basically the same.
Comment: I"m afraid I don't understand how this answers the question, which appears to be about whether $X(t)$ can exceed $Y(t)$ *at any (unspecified) time $t$*.  It looks like your analysis tries to answer the question for some *specific time* $t$ only.  (That answer is provided by a Skellam distribution.)
Comment: First I calculate it for any specific time and then generalized it for t approaching infinity.

I.e. P(X(t)>3+Y(t)) for all t's. I.e. $1-\prod_{t=1}^{\infty}(1-P(X(t)>3+Y(t)))$
Comment: @whuber These are one and the same. Just checked. Never heard of a Skellam distribution. Pretty cool.
Comment: @nonein $P(X(t) > Y(t)) \neq P(X(t) > 3 +Y(t))$
Comment: https://cran.r-project.org/web/packages/skellam/index.html <- awesome
Comment: @Taylor Yeah I agree but what we are trying to estimate is the probability that X at any given time is not only above Y but also above its starting point, hence 3+Y(t). Unless I am misunderstanding something
Comment: @Taylor I have an additional question if you don't mind, how do I aggregate the total probability that X exceeds Y at any given time, i.e. for all t's. Is it correct to do as I have done in my edit in my post?


Python: why can a variable stand on its own?

Question: I am a beginner in python told my friend today, that the following code would throw an error, but it did not:
a = 5
a

So I wondered, what does "a" actually do and why is the interpreter fine with this?
If this is a duplicate, please refer me to the right post and sorry in advance.
edit: I used a *.py file.
Answer: If you type this code into the shell and click enter, the value of a is returned. Functionally, as there is no operation being performed on a, the value of a will not change.
You define the variable in the line above. The variable contains a value, so the "NameError: name 'a' is not defined" error is not triggered.

Also, even if the variable is a different data type, for example, a string, the value of a is returned.
If you run the code in a different environment, the line won't be printed and the line won't impact the value of itself or of any other variables.
Answer: I think you tried it in der REPL Console, paste it to a *.py file and execute that. So when you just type the variable name and hit enter this is actually a print command behind the scenes
Comment: It's not accurate to say it's a print command behind the scenes. While it will be displayed on the console when running interactively, that doesn't make it a print statement.
Answer: You can type in a int into the shell or whatever, and it will return it. The variable you put is just a int, so it returns 5.


Java LoadLibrary Issues on Linux

Question: I am loading a Library on Linux through System.LoadLibrary( ) call.  (Previously asked about here)
A new twist is that I discovered gstack, so I can see where it is actually frozen.. One red flag I see is this:
Thread 15 (Thread 0xb73feb90 (LWP 12892)):
#0  0xb7f57402 in __kernel_vsyscall ()
#1  0x0075ebc5 in pthread_cond_wait@@GLIBC_2.3.2 () from /lib/libpthread.so.0
#2  0x7fd2416c in system__task_primitives__operations(short, long,...)(...)( *) () from /app/gnatpro6.2.2-linux/lib/gcc/i686-pc-linux-gnu/4.3.3/adalib/libgnarl-6.2.so
#3  0x7fd2cd13 in system__tasking__stages__activate_tasks () from /app/gnatpro6.2.2-linux/lib/gcc/i686-pc-linux-gnu/4.3.3/adalib/libgnarl-6.2.so
#4  0x7fd2272c in system__interrupts___elabb () from /app/gnatpro6.2.2-linux/lib/gcc/i686-pc-linux-gnu/4.3.3/adalib/libgnarl-6.2.so
#5  0xb7377e37 in loadinit () from /home/user1/workspace/javaLinux/lib/libload.so
#6  0xb7377ecd in __do_global_ctors_aux () from /home/user1/workspace/javaLinux/lib/libload.so
#7  0xb7377579 in _init () from /home/user1/workspace/javaLinux/lib/libload.so
#8  0x005b73f3 in call_init () from /lib/ld-linux.so.2
#9  0x005b7503 in _dl_init_internal () from /lib/ld-linux.so.2
#10 0x005baeab in dl_open_worker () from /lib/ld-linux.so.2
#11 0x005b7036 in _dl_catch_error () from /lib/ld-linux.so.2
#12 0x005ba652 in _dl_open () from /lib/ld-linux.so.2
#13 0x0074ec6d in dlopen_doit () from /lib/libdl.so.2
#14 0x005b7036 in _dl_catch_error () from /lib/ld-linux.so.2
#15 0x0074f2ec in _dlerror_run () from /lib/libdl.so.2
#16 0x0074eba4 in dlopen@@GLIBC_2.1 () from /lib/libdl.so.2
#17 0xb792c099 in os::dll_load(char const*, char*, int) () from /home/user1/tools/Linux/jdk1.6.0_17/jre/lib/i386/server/libjvm.so
#18 0xb77e0cd9 in JVM_LoadLibrary () from /home/user1/tools/Linux/jdk1.6.0_17/jre/lib/i386/server/libjvm.so
#19 0xb7394cac in Java_java_lang_ClassLoader_00024NativeLibrary_load () from /home/user1/tools/Linux/jdk1.6.0_17/jre/lib/i386/libjava.so
#20 0xb43554aa in ?? ()
#21 0x086a9510 in ?? ()
#22 0xb73fdf34 in ?? ()
#23 0xb73fdf30 in ?? ()
#24 0xb434e08d in ?? ()
#25 0xb73fdf00 in ?? ()
#26 0x00000000 in ?? ()

Specifically this:  #17 0xb792c099 in os::dll_load
Shouldn't this be calling into a Linux load library call, not a dll call? Any ideas why it would make the wrong call?
Comment: Don't worry about the call to `dll_load()` - you can see from the stacktrace that `dlopen()` is being called along the way.  Have you tried loading that library from a C/C++ program using `dlopen()` directly to see what happens?
Answer: I think, this is just a matter of naming things. It seems, that the JVM authors preferred to name their wrapper dll_load instead of so_load. If you look at the stacktrace (in particular, the frames immediately above in the list), you see
dlopen@@GLIBC_2.1 () from /lib/libdl.so.2

which actually is the Linux equivalent to LoadLibrary under windows.

Java LoadLibrary Issues on Linux


Problem with MySQL VALUES using PHP variables

Question: I'm trying to send data from an AJAX call to database tables that are generated from PHP. I'm wrapping the MySQL queries in a function with for loops so I can create any number of tables on the fly. I have every part of it working except for the query that defines the VAULES. I'm trying to append an integer variable at the end of $usrscore so that as it loops through, my VALUES will be $usrscore1, $usrscore2, $usrscore3, etc. The problem is that it only picks up the integer as the value (i.e. 1, 2, 3) instead of using the entire variable (i.e. $usrscore1, $usrscore2, $usrscore3).
Concatenating doesn't work (i.e. "$usrscore" . $counter . ") and combining them as two separate variables doesn't work either (i.e. $usrscore + $counter). If I literally write out the variable with an integer at the end it works as expected but I need this to work in a loop.
Thanks!
Comment: Post the code, and the error message
Answer: as i guess you want to call a variable, but don't know it's name.
you must concatenate them like:
<code>$myvar1 = 'hi there';
$str = 'myvar';
$int = 1;
echo ${$str.$int};
</code>
it must return
<code>hi there
</code>
hope it helps


bad results with SVM

Question: I have a dataset of 1157 samples. The number of features are 6 and I have only one output. My training error is very poor although I have tried a wide range of cost values and followed the recommended procedure:
I scaled my inputs and output to the interval 0 and 1.
then, found the SVM error rate for cost c=2^{-15:1:15} and gamma g=2^{-15:1:15}
the best result I could get is with  c=32768, g=4, rate=0.0291635.
Should I go for larger c values? or should I decide my features are  bad predictors of the target?
Comment: Your question implies that you are adjusting the parameters to get good results on the training data.  This is a very bad idea and will very likely lead to severe overfitting (and hence poor generalization performance).  It would be better to optimise a cross-validation based selection criterion (use nested cross-validation for performance estimation).  Have you tried other methods?  It may be that it is just a difficult problem and no method will perform significantly better?
Comment: Oh I see. I am searching now more about "nested cross validation for performance estimation."Any good resource?
Answer: Your parameter search sweeps over a large area. So probably it is your features' fault. Open your data with a Tool like "Weka Explorer", when loading it make sure to use the apropriate "...ToNominal"-attribute-filter.
Then examine your features in the "Select attribute"-tab. There you can get an impression how correlated your features are with the target variable.
For some insights, take a look at Hall, "Correlation-based Feature Selection for Machine Learning", 1999, http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.37.4643
Comment: I would trust my features for now, and try to troubleshoot my SVR.
Answer: Are you using a non-linear kernel? try a linear kernel first. Actually, try logistic regression first, with 6 features it will be fast and easy and give results similar to an SVM with linear kernel.
It's hard to know whether an error rate of 0.03 is "poor" without knowing how many positive and negative samples are in your data. For example, it there's only 10% positives, then an a error rate of 10% is poor (not better than random). If there's 50%, then not as bad. Hence it's better to use other measures like area under ROC curve or precision/recall (precision still depends on % positives, ROC doesn't).
You should definitely use cross-validation like in the first answer, but if your model is still nominally "bad" in the training data regardless of how much you tune it, then there's little hope for it being good in cross-validation, and either your features are not useful or your model is not relevant to the problem.
Comment: you mean by ROC, Receiver operating characteristic curves?
Comment: yes, receiver operating characteristic curves

bad results with SVM


Posicionar uma Image View pelo acelerômetro do celular

Question: Quero criar um jogo no utilizando o android studio onde a minha image view se posiciona de acordo com o movimento que realizo no celular.
Por exemplo: Ao iniciar a aplicação a imagem aparece no centro do celular, e ao movimentar o aparelho para os lados a imagem vai se movimentando pegando os valores da posição inicial e da posição atual do aparelho.
Conseguir rotacionar a imagem, mas mesmo assim não estou conseguindo uma boa precisão do sensor e nem mover a imagem na horizontal ou vertical, abaixo estar o código que estou usando até o momento
MainActivity:
public class MainActivity extends AppCompatActivity implements SensorEventListener {

private TextView tvValorX;
private TextView tvValorY;
private TextView tvValorZ;

private ImageView eixoX;
private View eixoY;

private SensorManager mSensorManager;
private Sensor mAcelerometro;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    tvValorX = (TextView) findViewById(R.id.tvValorX);
    tvValorY = (TextView) findViewById(R.id.tvValorY);
    tvValorZ = (TextView) findViewById(R.id.tvValorZ);

    eixoX = findViewById(R.id.imagem);

    mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    mAcelerometro = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
}

@Override
protected void onResume() {
    super.onResume();
    mSensorManager.registerListener(this, mAcelerometro, SensorManager.SENSOR_DELAY_UI);
}

@Override
protected void onPause() {
    super.onPause();
    mSensorManager.unregisterListener(this);
}

@Override
public void onSensorChanged(SensorEvent event) {
    float x = event.values[0];
    float y = event.values[1];
    float z = event.values[2];

    tvValorX.setText(String.valueOf(x));
    tvValorY.setText(String.valueOf(y));
    tvValorZ.setText(String.valueOf(z));

    float rotation = eixoX.getRotation();
    eixoX.setRotation(rotation + x);

}

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}

public void btMeusSensoresOnClick(View v) {
    List<Sensor> listaSensores = mSensorManager.getSensorList(Sensor.TYPE_ALL);
    String[] lista = new String[listaSensores.size()];

    for (int i = 0; i < listaSensores.size(); i++) {
        lista[i] = listaSensores.get(i).getName();
    }

  }
}

XML da aplicação:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Valor x:" />

<TextView
    android:id="@+id/tvValorX"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="" />

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Valor y:" />

<TextView
    android:id="@+id/tvValorY"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="" />

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Valor Z:" />

<TextView
    android:id="@+id/tvValorZ"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="" />

<android.support.constraint.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/imagem"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher_background"
        tools:ignore="MissingConstraints"
        tools:layout_editor_absoluteX="112dp"
        tools:layout_editor_absoluteY="95dp" />

</android.support.constraint.ConstraintLayout>

</LinearLayout>

Answer: Você confundiu um pouco as coisas, o acelerômetro retorna a aceleração do dispositivo, não a posição inicial e da posição atual do aparelho.
Crie variáveis de velocidade para o X e Y e as inicialize com onde você quer que o ImageView inicialize, em onSensorChanged some o valor da aceleração nas variáveis e vai ter sua velocidade.
Para mudar a posição do ImageView, você vai precisar usar um LayoutParams com as variáveis que você definiu.
Não é recomendável fazer um jogo diretamente no Android Studio, essas APIs são pensadas para serem usadas em aplicativos, para fazer um jogo, use uma game engine como a Unity ou o GameMaker: Studio.
Fazendo dessa forma o ImageView vai se mover em velocidades estranhas, já que não há um controle da velocidade do update do sensor.


Find value of $AB$

Question:
Let
$$A=\dfrac{1}{\sin20^\circ\cos40^\circ}+\dfrac{1}{\sqrt{3}\cos20^\circ\cos40^\circ}$$
and
$$B=\cot40^\circ+\cot230^\circ-\tan185^\circ(\tan230^\circ-\cot50^\circ)$$
Find $AB$.

My attempt :
\begin{align*}
A&=\dfrac{1}{\cos40^\circ}(\dfrac{1}{\sin20^\circ}+\dfrac{1}{\sqrt{3}\cos20^\circ})\\
&=\dfrac{2(\sqrt{3}\cos20^\circ+\sin20^\circ)}{\sqrt{3}\cos^2 40^\circ}\\
B&=\tan50^\circ(1-\tan5^\circ)+\tan40^\circ(1+\tan5^\circ)
\end{align*}
I tried to factor $A$ and $B$ because I think it will cancel each other out.
Comment: Your $A$ is wrong. $\left(\dfrac{1}{\sin20^\circ}+\dfrac{1}{\sqrt{3}\cos20^\circ}\right)
=\dfrac{2(\sqrt{3}\cos20^\circ+\sin20^\circ)}{\sqrt{3}\color{blue}\sin 40^\circ}$
Answer: \begin{align*}
A &= \frac{4(\sin 60^{\circ} \cos 20^{\circ} + \cos 60^{\circ} \sin 20^{\circ})}{\sqrt{3} \sin 40^{\circ}\cos 40^{\circ}} = \frac{4\sin 80^{\circ}}{\sqrt{3} \sin 40^{\circ}\cos 40^{\circ}} \\&= \frac{8\sin 80^{\circ}}{\sqrt{3}\sin 80^{\circ}} = \frac{8\sqrt{3}}{3}\\
B &= \cot 40^{\circ} + \cot 230^{\circ} - \tan 185^{\circ}(\tan 230^{\circ} - \cot 50^{\circ})  \\ &=\cot 40^{\circ} + \tan 40^{\circ} - \tan 5^{\circ}(\tan 50^{\circ} - \cot 50^{\circ}) \\ &= \cot 40^{\circ} + \tan 40^{\circ} - \tan 5^{\circ}(\cot 40^{\circ} - \tan 40^{\circ})\\
\therefore AB \tan 40^{\circ} &=\frac{8\sqrt{3}}{3} \left ( 1 +\tan^{2} 40^{\circ} - \tan 5^{\circ} ( 1 - \tan^{2} 40^{\circ}) \right ) \\&= \frac{8\sqrt{3}}{3} \left ( 1 +\tan^{2} 40^{\circ} - (\frac{1- \tan 40^{\circ}}{1 + \tan 40^{\circ}}) ( 1 - \tan^{2} 40^{\circ}) \right ) \\ &= \frac{8\sqrt{3}}{3} \left ( 1 +\tan^{2} 40^{\circ} -  ( 1 - \tan 40^{\circ})^{2} \right ) \\ &= \frac{16\sqrt{3}}{3} \tan 40^{\circ}
\end{align*}
Comment: Isn't $A= \frac{2(\sin 60^{\circ} \cos 20^{\circ} + \cos 60^{\circ} \sin 20^{\circ})}{\sqrt{3} \sin 40^{\circ}\cos 40^{\circ}}$ ?

Find value of $AB$


Git status summary

Question: I added recursively files and folder under a folder in git and would like to know the summary (say x files, y folders). I didn't find a suitable parameter for git status. Do we have a way to get this information?
Answer: git ls-files would help. Check the options to get modified files etc. Also git doesn't deal with folders at all only with files in subfolders, so you have to write some scripting wrappers for your particular case
Answer: If you're using posh-git, status summary information is shown in Powershell by default.

Git status summary


Generalized ridge regression estimator subject to elliptical constraint

Question: Ok, so I have this question:
For the linear model (matrix notation) $y=X\beta+\epsilon$, show that a generalized ridge regression estimator, $\hat\beta_{R}=(X'X+\lambda A)^{-1}X'y$ can be obtained as a solution of minimizing $SS_{res}(\beta)$ subject to the elliptical constraint $\beta'A\beta$, where $A$ is known, positive-definite symmetric matrix. Assume that both $X'X$ and $X'y$ are in correlation form.
So I've got:
$SS_{res}(\beta)=(y-X\hat\beta_{R})'(y-X\hat\beta_{R})$ and I should  minimize this w.r.t. $\hat\beta_{R}$ taking into consideration the constraint $\beta'A\beta$. So I think I've got:
$min_{\hat\beta_{R}} (y-X\hat\beta_{R})'(y-X\hat\beta_{R})+\lambda\beta'A\beta$ (should there be a $\lambda$ there?).
But I can't seem to get the right answer, can someone please help?
Answer: Recall that $\frac{\partial}{\partial \beta} ||Y- X\beta||_2^2 = 2X'(Y-X\beta)$ and $\frac{\partial}{\partial x}(x'Ax) = 2Ax$ for symmetric (real) $A$. Your problem is
$$
\arg \min_{\beta \in \mathbb{R}^p} ||Y-X\beta||_2^2
$$
s.t.
$$
\beta'A\beta = \sum\sum a_{ij}\beta_i \beta_j < c,
$$
or
$$
\arg \min_{\beta \in \mathbb{R}^p} S(\beta)= \arg \min_{\beta \in \mathbb{R}^p} ||Y-X\beta||_2^2 + \lambda\beta'A\beta,
$$
thus
$$
\frac{\partial}{\partial \beta} S(\hat{\beta}) = -2X'(Y-X\hat\beta)+2\lambda A\hat\beta = 0,
$$
$$
(X'Y+ \lambda A )\hat\beta    = X'Y
$$
$$
\hat \beta = (X'Y + \lambda A)^{-1}X'Y .
$$
Comment: As always you come to my rescue, thank you.
Comment: You are welcome (BTW, you can click on "accept" if the answer satisfies you).
Comment: Absolutely, I owe you so much. Thanks for sharing your knowledge.


Drupal Commerce 2 deployment

Question: I'm developing a store on Drupal 8 with Drupal Commerce 2.1. I'm doing it locally using docker4drupal Docker containers.
I just want to be sure that all my Commerce settings including categories, products and variations will be transferred to the external server during deployment.
Do I need special modules or methods for this except copying the files, database etc?
Comment: I suggest you to change the word "migration" for "deployment" as it is what you want to do. Migration is more related to migrate a site or commerce store from Drupal 7 or other source to Drupal 8.
Answer: I don't think you need special modules or methods. Just copying the files and exporting/importing the database is enough. A module like Backup and Migrate can help you on that task but is not a must.
Anyway and as an extra information there are some optional but good practices (tools):

Drush: Apart that it can help you on some tasks (clearing cache, enabling modules, etc) it also can help you make a database dump using a command like drush sql-dump > file.sql, then you transfer the database to your server and you can import the database with a command like drush sql-cli < file.sql. If you are using Drupal 8.4.* just make sure to use drush 8.1.12 or higher. Drush can also help you syncronize the local dev site with the production site and even clone the site (more advanced).
Git repository: It will help you track custom files and even the configuration using a sync directory. The good thing about this is that you actually don't "transfer" the files, but commit/checkout, it can help you on your development workflow. Some people commit also the drupal or vendor files, other people (like me) just commit the custom files (modules and themes) and commit the composer files (see next).
Composer. The good thing about this is that you just transfer the composer.json and composer.lock file and then on the production server just run the command composer install --no-dev and it will download all the drupal/vendor files including contrib, modules, themes, libs, etc that you specified in the composer.json file (so you're actually not transfering the files). Specifically for commerce, the project base of drupal commerce can be a good starting point. Just customize it as you want.
Config Split module. It will helps on spliting your configuration so you can have modules that are enabled only locally on your dev environment but not enabled on the production server (like explained here), so in combination with composer you can have downloaded and enabled the devel module locally but not in the production server (as an example).

This answer is not intended to give you a how to on the tools mentioned, but to let you know some tools that exists and can help you in the process of developing drupal sites in general, if them sounds new to you and you are interested in any topics, please look their documentation sites and look around the internet as there are plenty of information, tutorials and videos that will help you consolidate your own workflow.
Comment: Thank you!
I've moved my Commerce site several times without issues.
Comment: @MaxZviagintsev glad that it helped you. Please mark the answer as "the answer" so the community knows it.

Drupal Commerce 2 deployment


Split bitmap into pieces and save

Question: I load image from disc:
var img = Image.FromFile("foo");
var bmp = new Bitmap(img);

I wrote method to split image into pieces:
public static IEnumerable<Bitmap> VerticalSplit(this Bitmap src, int pixels)
{
    var bmps = new List<Bitmap>();

    for (int i = 0; i < src.Width; i+=pixels)
    {
        var dst = new Bitmap(pixels, src.Height);
        using (var grD = Graphics.FromImage(dst))
        {
            grD.DrawImage(src, new Rectangle(i, 0, pixels, src.Height), new Rectangle(0,0,pixels,src.Height), GraphicsUnit.Pixel);
            bmps.Add(dst);
        }
    }

    return bmps;
}

And this is the usage:
var parts = bmp.VerticalSplit(10);

for (int i = 0; i < parts.Count(); i++)
{
    parts[i].Save(@"output/" + i + ".jpg");
}

The problem is that every image except 1 is blank. Why does that happen?
Answer: See DrawImage, which has a signature of:

public void DrawImage (System.Drawing.Image image,
  System.Drawing.Rectangle destRect, System.Drawing.Rectangle srcRect,
  System.Drawing.GraphicsUnit srcUnit);

Note that the second parameter is "destRect", and the third parameter is "srcRect".  Your code has the destination and source rectangles BACKWARDS.
Change:
grD.DrawImage(src, new Rectangle(i, 0, pixels, src.Height), new Rectangle(0,0,pixels,src.Height), GraphicsUnit.Pixel);

To:
grD.DrawImage(src, new Rectangle(0,0,pixels,src.Height), new Rectangle(i, 0, pixels, src.Height), GraphicsUnit.Pixel);

Split bitmap into pieces and save


Worker Unable to query / access Mongoose Model

Question: I tried importing the Mongoose model directly in the worker like :
  Worker, isMainThread, parentPort, workerData
} = require('worker_threads');

if (isMainThread) {
  module.exports = function parseJSAsync(script) {
    return new Promise((resolve, reject) => {
      const worker = new Worker(__filename, {
        workerData: null
      });
      worker.on('message', resolve);
      worker.on('error', reject);
      worker.on('exit', (code) => {
        if (code !== 0)
          reject(new Error(`Worker stopped with exit code ${code}`));
      });
    });
  };
} else {
  const MyModel = require("../models/MyModel.js");
  const data = await MyModel.find();
}

Query didn't run! But no exceptions or errors
So then I tried passing the model as WorkerData from the main thread :
const {
  Worker, isMainThread, parentPort, workerData
} = require('worker_threads');

const MyModel = require("../models/MyModel.js");

if (isMainThread) {
  module.exports = function parseJSAsync(script) {
    return new Promise((resolve, reject) => {
      const worker = new Worker(__filename, {
        workerData: MyModel
      });
      worker.on('message', resolve);
      worker.on('error', reject);
      worker.on('exit', (code) => {
        if (code !== 0)
          reject(new Error(`Worker stopped with exit code ${code}`));
      });
    });
  };
} else {

  const MyModel = workerData;
  const data = await MyModel.find();
}

This time I got the exception :
DOMException [DataCloneError]: function model(doc, fields, skipId) {
      model.hooks.execPreSync('createModel', doc);
      if (!(this insta...<omitted>... } could not be cloned.
    at new Worker (internal/worker.js:144:17)

What do I do to be able to access the Database from the Worker thread?
Should I establish a separate connection to the DB within the thread using :
mongoose.connect() ?
Answer: I dont know if you're resolved your problem, but i had the same, for people that arrive here, the solution is:
as a fact (like @jackOfAll supposed): establish connection with DB


Understanding the shifted log-normal distribution

Question: I have difficulties understanding why a third parameter (the shift) is necessary to describe the log-normal distribution.
Let's say we have a normal random variable X, if I shift this variable by an additive constant b, X+b is still normally distributed and can still be described by the two parameters $\mu$ and $\sigma$.
Why is it not the same for log-normal random variables? By definition, a random variable X has a shifted log-normal distribution with shift $\theta$ if log(X + $\theta$) ~ N($\mu$,$\sigma$).
However, if X + $\theta$ ~logN($\mu$,$\sigma$), then also X has a log-normal distribution X ~logN($\mu'$,$\sigma'$).
Accordingly, the two parameters should suffice to describe any shifted log-normal fully, or not?
Comment: Did you prove or have link about "However, if X + θ ~logN(μ,σ), then also X has a log-normal distribution X ~logN(μ′,σ′)." ?
Comment: I thought this follows from Glen_b's answer here - is my understanding hence incorrect that shifting a lognormal distribution by an additive constant results in a log-normally distributed variable X+b? https://stats.stackexchange.com/questions/156277/shifted-log-normal-distribution-and-moments
Comment: The question and answers are related to moments, did not mention the distributions.
Comment: @Glen_b What do you think? I do not think that $X+\theta$ and $X$ follow lognormal simultaneously given $\theta \ne 0$.
Comment: Hence log(X) ~ N($\mu$,$\sigma^2$) implies that X+c is a shifted log-normal, i.e. log(X+c) ~ N($\mu+c$,$\sigma^2$), but the reverse is not correct?
Answer:
By definition, a random variable X has a shifted log-normal distribution with shift $\theta$ if log(X + $\theta$) ~ N($\mu$,$\sigma$).

In the more usual notation, that would correspond to a lognormal with shift $-\theta$.

However, if X + $\theta$ ~logN($\mu$,$\sigma$), then also X has a log-normal distribution X ~logN($\mu'$,$\sigma'$).

This is not the case, as we'll see.
To keep things clear, let us distinguish between the two parameter lognormal (with parameters $\mu$ and $\sigma^2$) and a shifted (i.e. three parameter) lognormal ($\delta,\mu,\sigma^2$); if $\delta=0$ we get the two-parameter lognormal as a special case. The density for the three parameter lognormal is:
$$\frac {_1}{^{(x-\delta)\sigma {\sqrt {2\pi }}}}\, e^{-{\frac{1}{2\sigma ^{2}} {\left(\ln (x-\delta)-\mu \right)^{2}}}},\quad x>\delta, \:\delta,\mu\in \mathbb{R},\,\sigma>0$$
[Here a positive $\delta$ shifts up by $\delta$, corresponding to the negative of your $\theta$; a positive $\theta$ corresponds to a shift down by $\theta$. I'll stick with the more common convention.]
It is the case that if you already have a shift (location-parameter) in  the model, then adding a shift parameter would do nothing. For example,  $\mu$ plays this role in the normal distribution, so there would be no point in adding a shift parameter to a normal distribution; it would simply be combined with the $\mu$ term.
However, in the lognormal, $\mu$ is not a shift parameter. It is a scale parameter; it stretches and compresses rather than shifts. Meanwhile $\sigma$ is a shape parameter, controlling how skewed/heavy tailed the lognormal distribution is.
One quick way to see that the shift parameter does something different to the two parameters already there (assuming you don't wish to follow through the algebraic manipulations on the density), is to use the fact that the log of any two parameter lognormal variate is itself distributed as a normal (the three parameter lognormal doesn't share this property in general, as we'll see).
With the normal, if we apply a shift we move the density up or down along the x-axis, which simply alters its $\mu$ parameter and leaves us with another normal. With the two parameter lognormal, altering the $\mu$ parameter leaves us with another two parameter lognormal but does not simply shift the values. It does have the property that if we then take logs, we get back to a normal. Shifting the normal and then exponentiating to a two parameter lognormal is different from shifting the two parameter lognormal.
[The issue boils down to the fact that addition and exponentiation are not commutative, so shifting the lognormal doesn't work like shifting the normal.]
We can immediately see that if we supply a negative shift ($\delta<0$ in a three parameter lognormal) that we can't take logs to get back to a normal -- some of  the density applies to negative values of $x$. We might briefly entertain the notion that positive arguments might somehow work but we can readily determine that it cannot be the case via simulation, or more directly, even just by considering the lower limit:
The log of a three-parameter lognormal variate with $\delta>0$ will have a smallest possible value of $\ln \delta$; therefore it cannot be normal, since all normal variates range over the whole real line.
Alternatively, in a simulation, the steps are:

generate data from a normal distribution with some $\mu,\sigma$
exponentiate, to a corresponding two-paramater lognormal with the same parameters
shift the distribution up by a substantial amount (say, twice the mean of the lognormal), so that it has a clear impact on the location
take logs and note that the result is clearly not normal.

For a large sample from a standard normal and a shift parameter of $\delta=2e^\frac12\approx 3.3$, we obtain:

These histograms are what we get at step 1 and 4 respectively.
We can clearly see we don't get a normal back out (it's skewed, for starters), so the shift parameter is not doing the same thing as changing $\mu$ would*. The lowest value in the $\log(x)$ sample displayed on the right, is $1.19498$, just above the lower limit of $\frac12+\log(2)\approx 1.19315$
* we can actually see that back in the formula for the density, where $\delta$ is inside the $\log(x..)$ part but $\mu$ is outside it, so they clearly don't just add together.

Appendix:
<code>#R code for the above (fewer simulations than I did, but enough)
#
z <- rnorm(1000000,0,1) # 1 million normals
delta <- 2*exp(1/2)
y <- exp(z)             # 2-parameter lognormal
x <- y + delta          # shifted (i.e. 3-parameter) lognormal
par(mfrow=c(1,2))
hist(z,n=200,col="skyblue",bord="skyblue",freq=FALSE)
hist(log(x),n=200,col="lightgreen",bord="lightgreen",xlim=c(1,5),freq=FALSE)
</code>
Comment: You seem to have picked up a new confusion about what a lognormal is. Neither of your statements in the second sentence are correct. The part where you mention commutativity is also odd; if $Z$ is normal, then $µ+σZ$ is normal, so then (clearly) $\exp(µ+σZ)$ is not normal (whether or not you shift it). Neither $\log(X)$  nor $\log(X)+c$ will be lognormal (of any kind). .... Instead: of $Z$ is normal, then $\exp(Z)$ is lognormal (ordinary two parameter lognormal) and $\exp(Z)+c$ is shifted lognormal (three parameter lognormal).
Comment: I don't see any disagreement between what you quoted and anything in my answer. Can you help me understand where you feel the two disagree? ...  if log(X+c) is normal then X+c is two parameter lognormal but X is not (it's shifted lognormal)
Comment: Thanks! It might sound trivial, but I think the problem was that I did not understand the definition correctly: I read it as "Y is a shifted log-normal if for ∀ s: (Y+s) ~ N", when in fact the reading is that "Y is a shifted log-normal iff ∃s s.t. (Y+s) ~ N" - correct? If I understand correctly, what you meant with addition and exponentiation not being commutative can easily be seen by: X = exp(sigma + mu*Z) + s is not a normal? Has the fact however, that log(X) ==> log(X)+c is a shifted log-normal be proven by showing that the distribution of log(X) + c can be written as the 3-param logN?
Comment: 1. Is this correct: "Y is a shifted log-normal if for ∀ s: (Y+s) ~ N", when in fact the reading is that "Y is a shifted log-normal iff ∃s s.t. (Y+s) ~ N" - correct? 2. Here I was not referring to the commutativity, but solely on the statement from wikipedia: Has the fact however, that log(X) ==> log(X)+c is a shifted log-normal be proven by showing that the distribution of log(X) + c can be written as the 3-param logN? How do we know this implication is correct?
Comment: Thank you for writing such a beautiful answer. I understand that shifting in the normal "space" on the x-axis is not a shift in the log-normal space, where changes in $\mu$ scale the distribution. I also see in my own data, that only my shifted data leads to a normal distribution of log(data) and else the log of the data leads to a skew-normal. The point which is still confusing me is this (e.g. from wikipedia): "If X ~ logn($\mu$,$\sigma$) then X+c is said to be a shifted lognormal" -- how is this not opposed to your arguments at the end & the simulation, if by def. then log(X+c) is normal?


Como fazer git pull em todas as branches?

Question: Tenho varias branches e fazendo duas versões de um scripts, em branches separadas em um servidor de desenvolvimentismo. Então como atualizar todas as branches, do clone, no servidor de produção?
Comment: @MárcioMocellin Se espera que a resposta apresente essa diferença, faça essa pergunta. Você pode [edit] a pergunta e adicionar algo como "vi que existem esses dois comandos ... qual a diferença?". Porém, isso já foi respondido em [Qual a diferença entre os comandos 'git pull' e 'git fetch'?](https://pt.stackoverflow.com/q/3231/5878)
Comment: git pull --all não resolve?
Comment: @epx fiquei em duvida entre ```git fetch --all --prune``` e ```git pull --all```, estava esperando uma resposta mais completa.
Comment: É, por isso coloquei como comentário, não tenho certeza se atende seu caso de uso em particular.
Comment: Já achei a resposta:
https://stackoverflow.com/questions/10312521/how-to-fetch-all-git-branches
Answer: Acredito que você deva mesclar-las em uma branch só e depois enviar esta única para o repositório. Posso estar falando besteira então faça um teste antes em uma cópia.
Exemplo : https://git-scm.com/book/pt-br/v2/Git-Branching-Basic-Branching-and-Merging


Who should the moderators be?

Question: I'm asking another of the essential meta questions as a precursor to some great news, Expats is going to be advancing to the public beta stage at some point this week!1 You all have done a fantastic job of building what appears to be a really strong site in the making.
We're going to need leadership from within this community to help guide the site on its journey to a graduated site. I'm looking for three people that would like to step up take on this position, in accordance with our theory of moderation. Great candidates have the following qualities:

Consistently patient and fair when dealing with other users
Have a little time each week to devote to moderating the site
Willing to help jump start promotional activities, and guide new users as they find the site for the first time

You'll also have our ear, as a liaison, between this community and the Stack Exchange community team.
Are you interested? Nominate below with whatever text you'd like to offer about yourself and why you want the job, and include a link to your profile on the main site. Do you feel strongly that someone else would be a great moderator? Feel free to nominate them as well, explaining why you feel strongly about them as a potential candidate, and link to their main profile as well.
Third-party nominations need to be accepted by the person you nominate, they can either leave a comment to accept, or edit your post with whatever detail they wish to add.
I'm starting this a bit early due to the activity we saw during the private beta, I have a feeling we're going to see quite a few new faces once we open - the sooner I start the process of looking, the sooner I can get a great team in place.
1Should be this week, don't panic if it's next.

March 20, 2014 - Update
Because we got such a huge amount of attention on opening day (which isn't going to be subsiding in the near future), I'm very likely going to begin appointments as early as today. If you're reading this and interested in joining the team, I need to see your nomination very soon.
You might begin to see diamonds next to names that have nominated here, that's simply me getting people in a position where they can be of the most use while I continue making selections and contacting folks. I'll be writing a formal 'welcome, moderators' meta post after I have all three in place.
Comment: Glad I posted this early, first day out we ended up with 6 questions on the hot list, front page of HN and now we're climbing our way through Reddit.
Comment: *Suggested edits are not allowed on non-tag-wiki posts on meta sites*
Comment: @GaëlLaurans Actually, neither of us are mods on Travel..
Comment: Could you be a moderator for the site? ;-)
Comment: @Dirty-flow Doh, forgot to convert to wiki, that basically fixes it.
Comment: I have no problem with either Mark or Dirty-flow and upvoted both nominations but isn't it a problem that we are on track to get two moderators from travel.SE, nominated by travel.SE contributors? (I am also active on travel.SE under another name)
Comment: But you were in the past and are pillars of the community there, which is my point.
Comment: Yes, I was, but @Dirty-flow has never been. Just clarifying :)
Comment: @Manishearth I plan to be a 'fourth mod' here, at least initially. You'll also probably see some of our expat employees participating here quite a bit, and pitching in to clean up when the hot questions party bus rolls through, which I suspect is going to be a frequent thing.
Answer: I nominate Mark Mayo. Mark made a wonderful initial moderator for Travel.SE, is a "serial expat" so has a huge range of knowledge on the topic, as his experiences both here and on Travel.SE shows!
(I believe Mark would be reluctant to stay on after the initial time, but as with Travel we can hopefully talk him into starting out as one)
Comment: OK, after thinking about it since the beta started, and more intently since you nominated me, firstly, thanks for the nomination, and yes, I'll accept if the community will have me.  I'm going to be around the site for a while anyway, that's for sure, and I like helping out where I can.
Answer: I nominate Dirty-flow.  We need someone with European knowledge for the Schengen / EU / EEU questions, laws and timezones.
Comment: LOL! I'm a little bit surprised. I accept the nomination. I hope that I can use my experience on Travel.SE to make this site a great place for high quality questions.
Comment: Yes, we need someone who'd be strong agaist US-perspective closing as too localized when "it's only moving between 2 EU provinces" or "it affects only Luxemburg, it's like a small city in US" ;)
Comment: @MarkMayo Except me. *evilgrin*
Comment: Plus nobody could argue with a mod with that avatar!
Answer: Since it already started I'm also nominating myself, as a semi-experienced expat originally from Hungary, but also living in both Germany and now in the UK. I'm also very curious about other countries, not only ones in Europe, but others as well.
Though I'm not a very high rep user elsewhere on the SE sites, I did my fair share on the review page of StackOverflow, and I'm involved on the meta.SO site, especially on topics about the issues in the current close/review system. You can also check my expat.SE profile and my global SE profile.
Comment: I was just coming to this page to nominate you. +1 from me!
Comment: This candidate's fashion sense _alone_ qualifies them, in my humble opinion.
Answer: I will throw myself into the moderator ring in response to wanting someone who is not actively part of Travel.SE. I am pretty active on TeX.SE and use it as a resource to ask questions and learn and answering when I can. I am also active on Academia.SE where I try and help people find the information they need. I am a US expat who has been living in the UK for 5+ years.
I have never been a diamond moderator on an SE site, but I have access to the review told on Academia.SE and try and work my way through the review queues and participate in meta and chat.
Comment: @Gagravarr see edits. Never a diamond mod, but have used the high rep review tools.
Comment: Have you been a moderator on any of those sites? Experience with the moderation tools as a high-rep user?
Answer: I would like to put my name forward. I have never been a moderator on any StackExchange sites, but would enjoy spending some time on it.
Usually, I tend to hang out on StackOverflow and Ask Different, as I am inclined towards the techy. But the ins and outs of expat life are of course always at the forefront of the mind for anyone who lives 'in another country'.
I am a UK citizen who has lived in Thailand for the last ten years, along with all the bureaucracy, political upheaval, headaches and coups d'etat that that entails.
It was only this morning that I came across this site, but I feel that it can make an excellent resource for people suffering the frustrations of expat life, as well as helping people who are faced with the possibility of living in a country in which they are not a citizen, to make decisions that can have far-reaching consequences in their life.

Who should the moderators be?


Dependency injection for FormElement #process callback

Question: Is there any way to inject container services into FormElement callbacks like '#process'? Or do I need to call \Drupal::container()->get(..)?
I noticed https://www.drupal.org/docs/8/api/services-and-dependency-injection/dependency-injection-for-a-form, but this is for forms, not for form element types.
Comment: All form element callbacks are simple callables so you would have to pass the whole instantiated object instead of just a class and method to call...and somehow instantiate it(maybe via wrapper?). In the end, it does not make any sense.
Comment: To clarify: I am not so interested whether it is technically called dependency injection, but if there is any clean way to use container services in a #process callback. It seems the answer is no.
Answer: Dependency injection for any method of a class is done for the whole class. So if you have a dependency for the method you're adding for any method in the class, you will set that as a dependency for the whole class, not just a single function. However, #process callbacks are static functions, and static functions cannot use dependency injection. They should use the \Drupal::service() method, which is for static functions and procedural code.
Comment: see comment from @IvanJaros, the class is not instantiated and the callable is a static function, so you have no access to `$this`.
Comment: If the callable is a static function, then there is no dependency injection. Dependency injection is only for non-static methods.
Comment: the downvote was not from me, the answer is not wrong. If you add the comment to the answer, it is clearer, that you mean, no, you can't use dependency injection for the static #process callback.
Answer: Technically it's possible with the help of ContainerFactoryPluginInterface. The #process is just an array of callables, and it's initialized in getInfo() which is non-static. So, you have access to FormElement's $this when creating the array of #process callbacks. Documentation doesn't seem to put any restrictions on #process array, except requiring it to be an array of callables (nothing is said about them to be static). Also, it's not enforced by any interface nor class inherited by FormElement. So, generally, the following is possible:
<?php

namespace Drupal\my_module\Element;

use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Render\Element\FormElement;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * @FormElement("my_element")
 */
class MyElement extends FormElement implements ContainerFactoryPluginInterface {
    /**
     * @var MyDependency
     */
    protected $myDependency;

    public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition): static {
        return new static(
            $configuration,
            $plugin_id,
            $plugin_definition,
            $container->get('my_dependency')
        );
    }

    public function __construct(array $configuration, $plugin_id, $plugin_definition, MyDependency $my_dependency) {
        parent::__construct($configuration, $plugin_id, $plugin_definition);
        $this->myDependency = $my_dependency;
    }

    public function getInfo() {
        return [
            '#process' => [[$this, 'processMyElement']],
        ];
    }

    public function processMyElement(&$element, FormStateInterface $form_state, &$form) {
        // $this->myDependency available here...
        return $element;
    }
}

Unfortunately I haven't found any instance of non-static #process method in Drupal's core, so maybe there is a convention, or silent agreement, to not use instance methods as callbacks.
Comment: The process element function will be called statically if referenced from outside the class, and will thrown an error. So to make code more bulletrpoof, #process callbacks should be created/treated as static even when in a class like this.
Comment: Well, I don't believe anyone developed a code which enforces static invocation of ready to use (static or non-static) callables provided via ``#process`` array. No matter, from inside or outside of the class. It's kinda useless. :)
Comment: There is a risk that this stuff could be serialized, although I think it can be avoided depending how it is used.


C# - Convert a string '07th December 2022' to DateTime

Question: We need to convert a string into a date. The data we received from client is in following format:

07th December 2022
08 December 2022
01st December 2022

Cab anybody suggest how this can be converted using any of C# date functions to a date format like YYYY-MM-DD.
Thanks
I tried few examples from here but none of them work:
https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings
Comment: Hmm... The last edit changed the nature of the question (changing `"07th December 2022 08 December 2022 01st December 2022"` to a bulleted list).  Was that the intent?
Comment: Either use Regex or string Split by Space and manipulate/clean the value to get day, month and year
Comment: Does this answer your question? [How can I parse dates with a suffix "th", "st" or "nd" on the day of the month?](https://stackoverflow.com/questions/14583285/how-can-i-parse-dates-with-a-suffix-th-st-or-nd-on-the-day-of-the-month)
Comment: So you have a string like `"07th December 2022 08 December 2022 01st December 2022"` that has three dates, in two different formats (with or without the `th`/`st`), with the month, day and year separated by spaces, and with the different dates separated by spaces. Do you have a general rule? My guess is that you'll need to preprocess things with a regex and then go from there.
Comment: So, did my answer help? By upvoting and/or accepting an answer (or answers - you can upvote more than one), you not only reward the answerer, you provide information to the next person who wants to know how to do this; in effect saying "this is a useful answer"
Answer: How about something like this?  I use a regex to split the day month and year up (ignoring "st", "nd", "rd" and "th" if they are there).  Then I reconstitute things into an easy to parse string and parse it.
I use named Regex groups to make getting the day/month/year out of the original string easier
It will, of course, half work (the regex half) and then fail if you pass it "99th Horse 1234":
<code>public const string SampleString = "07th December 2022 08 December 2022 01st December 2022";
public const string Pattern = @"(?<day>\d{1,2})((st)|(nd)|(rd)|(th))? (?<month>[A-Za-z]+) (?<year>\d{4})";

public static Regex DateRegex = new Regex(Pattern);

public static IEnumerable<DateTime> ParseDates(string input)
{
    var matches = DateRegex.Matches(input);
    var result = new List<DateTime>();
    var culture = new System.Globalization.CultureInfo("en-US");

    foreach (var match in matches.Cast<Match>())
    {
        var day = match.Groups["day"].ToString();
        var month = match.Groups["month"].ToString();
        var year = match.Groups["year"].ToString();
        var date = DateTime.ParseExact($"{day}-{month}-{year}", "d-MMMM-yyyy", culture);
        result.Add(date);
    }

    return result;
}
</code>