Violation of Gauss-Markov assumptions

Question: Which of the Gauss-Markov assumptions is violated in this picture?
If all other Gauss-Markov assumptions are satisfied, is the OLS estimator for $\beta_1$ unbiased and consistent? Why?

In the diagram, u is the error term, Einkommen is income (an explanatory variable).
The model is specified as follows:
$y = \beta_0 + \beta_1  \text{einkommen} + u$
The problem is taken from an exam.
My thoughts (x is einkommen):
the figure shows a quadratic function
the Gauss-Markov assumptions are:
(1) linearity in parameters
(2) random sampling
(3) sampling variation of x (not all the same values)
(4) zero conditional mean E(u|x)=0
(5) homoskedasticity
I think (4) is satisfied, because there are residuals above and below 0
(5) is satisfied, since the variation seems to be constant over all x
(3) satisfied , since einkommen is not the same value for all observations
(2) random sampling is satisfied, dont ask me why.
so only (1) is left, the model is not linear in parameters.
I hope I am not totally wrong with my thoughts.
Comment: Please add the `[self-study]` tag & read its [wiki](http://stats.stackexchange.com/tags/self-study/info), then tell us what you understand thus far, & where you are stuck. We will provide hints to help you get unstuck.
Comment: Thank you for your ongoing improvements to the question.  You are right to focus on (4): please consider the distinction between "mean" and "conditional mean." You are also correct to point out that (2) simply cannot be verified.  Since you have told us that $u$ is the "error term," that implies it was already obtained by a linear model, so you have no basis to reject (1): that is a given (if only implicitly).
Comment: to make that clear: u is the error term in this figure.
Comment: Please state that in your question.  When you do, please also explain the relationship between `Einkommen` and the model: is it a covariate? The dependent variable? The predicted value? A variable not in the model at all?
Comment: i edited my first post
Comment: self -study added , and wiki read
Comment: Can you explain what you think the phrase "the model is linear in the parameters" means? Can you explain what you think the term "conditional mean" refers to and then relate that to what you see in the plot?
Comment: yes, i see it now: for x in (500;1000), x in (1500;2000) and x in (2500; 3000) E(u|x) is not 0. thanks for your hints. now i have to answer the question of unbiasedness and consistency. has anybody a hint where to start from with this issue. by the way i am reading the wooldridge introductory text.
Answer: There've been a couple answers and none of em have touched on what I thought were the most interesting questions asked, the bias and consistency of misspecified linear models. Since it seems pretty clear from the residuals that the model is misspecified with a quadratic term, let's take a look at what happens to our estimates. I'll leave this in terms of a general misspecification instead of solely a quadratic one for funsies.
Suppose we know an oracle who tells us the generating process for the data is $Y=X \beta +Z \alpha +\epsilon$. However, the model we choose to fit is $Y=X \beta+\epsilon$. Take note that the true model contains extra data in the form of Z and extra parameters in the form of the $\alpha $ term. Now, we could think of Z as being data we were unable to or chose not to collect but we could also think of the Z term as being data we collected and chose not to include in our model (like the situation you are in).
Now the typical parameter estimate is $ \hat{ \beta}=(X^{T}X)^{-1}X^{T}Y$. Biasedness relates to the expectation of our estimate and if we want to have consistency, we need that our bias disappears asymptotically. Keeping that in mind, we look at our expectation: $ E [\hat{ \beta}]=(X^{T}X)^{-1}X^{T}E [Y] = \beta +(X^{T}X)^{-1}X^{T}Z \alpha $.
So, if we misspecify, and alpha is not a column of 0's we end up with estimates which will certainly be biased by a factor of $(X^{T}X)^{-1}X^{T}Z \alpha $. Likewise, since consistency depends on asymptotic unbiasedness and our bias term has no reason to disappear asymptotically, we can expect the parameter estimates to fail to be consistent well.
Answer: It seems that your data does not follow a linear model.
Comment: It depends on what you mean by "linear model". Under the typical definition, it isn't clear that this the issue.
Comment: that means, assumption MLR1 (linearity in parameters) is violated.
Comment: with linear i mean the beta - coefficents are linear
Answer: First note that the data look to have a quadratic as opposed to  linear relationship.  This  casts doubt on the linearity assumption:
$$ E[Y\,|\,einkommen] = \beta_{0}+\beta_{1}einkommen$$
My hint to you is this: assume to the contrary that the model is linear, perform the regression (either hypothetically or literally) than check the other assumptions, do they hold?
Extra hint: $E[u]=0$ does not imply $E[u_i|einkommen_i] = 0$ for all $i$.
Comment: thanks for your extra hint. now i see, that MLR4 (zero conditional mean: E(u|x)) is violated.
Answer: The main issue is with assumption #5, i.e. homoscedasticity. Your error variance seems to change with income. It's higher in the middle than at the ends.

Violation of Gauss-Markov assumptions


"cmdline-tools component missing" error in flutter using VSCode

Question: While installing flutter I am getting this error:
Android toolchain - develop for Android devices (Android SDK version 30.0.1)
    X cmdline-tools component is missing
      Run `path/to/sdkmanager --install "cmdline-tools;latest"`

And I saw many solutions but they all use Android Studio, while I am using VSCode.
Comment: Please follow this https://stackoverflow.com/questions/68236007/i-am-getting-this-errors-cmdline-tools-component-is-missing-after-installing-f Possible duplictate of this.
Comment: No its not same, its about Android Studio and so easy to locate in it. I am using VSCode so I am not able to solve it.
Comment: You can install manually from this link depend on the system you are using.
 https://developer.android.com/studio#command-tools   and
https://proandroiddev.com/how-to-setup-android-sdk-without-android-studio-6d60d0f2812a
Comment: Yes thank you, it worked. We need to download the command line tools separately and then place it in our ```\AppData\Local\Android\Sdk``` directory.
Answer: For my case Installing Command-line Tools form sdk manager solved the problem.
Steps to install from sdkmanager:

Open sdk manager in Android Studio
Select SDK Tools tab
Select Android SDK Command-line Tools and then apply

You can download command-line tools manually and place it on sdk folder.
That also should work.


Why linear discriminant analysis is sensitive to cross validation (LDA overfit problem)?

Question: I've a set of 500+ observation (200+ feature vector dimension) of 7 classes and want improve my classification rate (with SVM or KNN).
To reduce the dimension and transform the feature matrix to a lower dimension (due to curse of dimensionality), I'm using LDA. It maps my high dimensional data to lower 6 dimensions. But with applying cross validated LDA it doesn't help and degrade the results dramatically.
When I even use leave one out (LOOCV) to calculate LDA projection matrix, it is calculated by holding out just one observation. My question is why even in this case the projection matrix ($W$) is so over-fitted and sensitive to cross validation? Intuitively I've hold out just one sample but it seems the projection matrix can't map the held out observation correctly.
I'm interested in two parts:

The math behind such experiment.
Some consideration or solution for better cross validated feature transform instead of LDA.

Update

based on @Andrew M, initial response, I've different number of observation per class. For example one class has example 120 observation while the other has only 40.
Comment: LDA has several meanings. What does it mean here?
Comment: @sycorax it means linear discriminant analysis which one can project high dimensional data to lower (C-1) dimension. $C$ is the number of classes.
Answer: Looks like your sample size is not a lot bigger than the dimensionality of the data (feature set size). That can be a problem for LDA and it can overfit. Since it relies on computing the within-class scatter matrix which requires the scenario of N >> p (# samples >> # features).
One quick way to check if you are overfitting with LDA is to look at the projections. As a result of LDA you have C-1 projection vectors. I would try projecting data on those vectors one by one and visualize it. If LDA indeed overfitted - you will see that the classes separate almost perfectly and are clustered around separate points on the projected axis. (In case of p > N all the samples would get projected onto C different points with classes separated perfectly).
This effect was termed "data piling" by J. S. Marron in his paper Distance Weighted Discrimination. For reference of how it might look like you can check the figures in that paper.
So assuming that is what happening I would do one of the following:
1) Use a regularized version of LDA. The simplest idea is probably just adding some constant to the diagonal of within-class scatter matrix in order to increase the variance in all directions. But there are a lot of different way you can regularize LDA.
2) Use another method for dimensionality reduction that is adapted to your scenario of small sample size. Distance Weighted Discrimination (DWD) might be a good choice here.
3) Get more samples (always recommended)
[1] Distance-Weighted Discrimination. J. S. Marron, Michael J. Todd and Jeongyoun Ahn. Journal of the American Statistical Association Vol. 102, No. 480 (Dec., 2007), pp. 1267-1271
Answer:
When I even use leave one out (LOOCV) to calculate LDA projection matrix, it is calculated by holding out just one observation. My question is why even in this case the projection matrix ($W$) is so over-fitted and sensitive to cross validation? Intuitively I've hold out just one sample but it seems the projection matrix can't map the held out observation correctly.

Well, the cross validation is probably doing what it is supposed to do: with almost the same training data, performance is measured. What you observe is that the models are unstable (which is one symptom of overfitting). considering your data situation, it seems totally plausible to me that the full model overfits just as badly.
Cross validation does not in itself guard against overfitting (or improve the situation) - it just tells you that you are overfitting and it is up to you to do something against that.
Keep in mind that the recommended number of training cases where you can be reasonably sure of having a stable fitting for (unregularized) linear classifiers like LDA is n > 3 to 5 p in each class. In your case that would be, say, 200 * 7 * 5 = 7000 cases, so with 500 cases you are more than an order of magnitude below that recommendation.

Suggestions:

As you look at LDA as a projection method, you can also check out PLS (partial least squares). It is related to LDA (Barker & Rayens: Partial least squares for discrimination J Chemom, 2003, 17, 166-173).
In contrast to PCA, PLS takes the dependent variable into account for its projection. But in contrast to LDA (and like PCA) it directly offering regularization.
In small sample size situations where n is barely larger than p, many problems can be solved by linear classification. I'd recommend checking whether the nonlinear 2nd stage in your classification is really necessary.
Unstable models may be improved by switching to an aggregated (ensemble) model. While bagging is the most famous variety, you can also aggregate cross validation LDA (e.g. Beleites, C. & Salzer, R.: Assessing and improving the stability of chemometric models in small sample size situations Anal Bioanal Chem, 2008, 390, 1261-1271.
DOI: 10.1007/s00216-007-1818-6
)
Because of the pooling of the covariance matrix, I'd expect your uneven distribution of cases over the different classes to be less difficult for LDA compared to many other classifiers such as SVM. Of course this comes at the cost that a common covariance matrix may not be a good description of your data. However, if your classes are very unequal (or you even have rather ill-defined negative classes such as "something went wrong with the process") you may want to look into one-class classifiers. They typically need more training cases than discriminative classifiers, but they do have the advantage that recognition of classes where you have sufficient cases will not be compromised by classes with only few training instances, and said ill-defined classes can be described as the case belongs to none of the well-defined classes.
Answer: LDA is optimal when the distribution of features, conditional on the labels is Gaussian with equal, but unstructured covariance matrices.  If conditional Gaussian model doesn't hold approximately, you may not want to use LDA.  The results of your LOO-CV suggests

The conditional Gaussian model is a poor fit and/or
You don't have enough observations to precisely estimate the within-class covariance matrix.
Comment: great. As I updated my question this is likely the case. Then do you have any suggestion instead? We've used PCA prior to LDA but that didn't help improving (while the model seems less over-fitted).
Comment: If you used PCA prior to LDA make sure to reduce the dimensionality in the PCA step (for example take number of PCA components to retain 80% of variance). Otherwise if you use all principal components it will have little effect on LDA.


Hibernate - proper way to update collection which is mapped with cascading type all-delete-orphan

Question: What would be the right and easy way to update the collection if it's mapped with all-delete-orphan  by it's "parent" object?
By updating I don't mean just adding/removing items from collection, but also updating the values of item properties (of course for those items that were previously in the collection).
Scenario is there's a Parent object that has a collections of Child objects and there's one form by which users can edit the Children collection - add/remove children but also edit the children's properties (on the same form).
Basically I want something like this:
Parent parent = session.get(Parent.class, parentUI.getId());
parent.setChildren(parentUI.getChildren());  // parentUI is a DTO
session.saveOrUpdate(parent);

This doesn't work and I understand the reasons why, but as it seems to me this should be a very common situation when using hibernate and developing UI applications, so I'm seeking for a (by the book) solution.
I'm using hibernate 3.6.10 and XML based configuration.
Here's the relevant mapping (I'm using ArrayList for storing children collection):
<list name="children" cascade="all, delete-orphan">
    <key column="parent_id" not-null="true"/>
    <list-index column="ordinal" />
    <one-to-many class="Child" />
</list>

If it matters child objects also have collections mapped in the same way but I don't think it's relevant since that is a problem equal to the one described.
Btw. I've lost a whole day on this and of course checked tens of very similar questions to this, but haven't found a reasonable solution or a pattern for solving this. Perhaps I'm missing something?
Comment: try clearing the children list and then calling the 'setChildren' method
Comment: parent.setChildren(parentUI.getChildren());  If you want the detached objects to be saved, you can try merge() method. This might delete existing values, use it with caution.
Comment: Use saveOrUpdate when you pull the data from the db in the current sesssion and trying to update the values in the same session context.
Comment: @Zeus unfortunately however I try (merge or saveOrUpdate) I get "org.hibernate.HibernateException: A collection with cascade="all-delete-orphan" was no longer referenced by the owning entity instance:".For which I do understand the reason why it is happening,
Comment: @Dav Blanked that won't work - NonUniqueObjectException is thrown since in the case of updating existing children there can be two instances with same identity - one loaded from DB, and the one from UI (it doesn't matter if the collection is cleaned first - child objects are still bound to Hibernate session)
Comment: I think you have to add more cascade types to update, add save_update / merge.
Comment: @Zeus I've tried that (ie. cascade="all, delete-orphan, merge") but with no success
Comment: Its wierd that it is not working, may be you have to query for all the children and save it without the involvement of the parent object. Last time when I was working with JPA, there was a property on the column annotation 'updatable' which used to stop all the updates that I do on the child object even when I have cascade set on it to all. You may want to check you config(On parent) for this type of setting.
Answer: Well since I didn't find a by the book solution I've first solved this manually by creating a custom method on my parent object parent.updateChildren(parentUI.getChildren()) which iterates through the old collection, compares it to the updated one from the UI and updates it manually. Needless to say it's far from ideal.
Then a colleague of mine (Zoran Regvart) gave me an witty idea (considering the technologies I'm using ie. Spring MVC) for improving things a little.
Idea is that, in case of submitting a form which updates the parent, before spring (web) binder does his work we can load the collection from the DB and set it to the command object (parentUI) thus "planting" it to be updated by the spring binder (in other words delegating the collection update process to him - thing that he does anyways).
Here is the (pseudo)code:
@ModelAttribute("parentUI")
public ParentUI initParentUI(HttpServletRequest p_request) {
    ParentUI parentUI = new ParentUI();
    String parentId = p_request.getParameter("id");
    if (parentId != null) { // indicates a form submit
        Parent parent = session.get(Parent.class, parentUI.getId());
        parentUI.setChildren(parent.getChildren());
    }
    return parentUI;
}

This way when spring binder does his work he will be updating the collection that is already bounded to Hibernate session.
This solution also isn't something that I'm too happy with and I haven't tested in many scenarios but for my current needs (for me) it's certainly somewhat of an improvement.
UPDATE: this workaround is convenient only in the case of adding new children or editing their properties. For cases of deleting children or changing their order  it better avoided since it ads complexity.


C# Deserialize text in XML mixed content as custom object?

Question: Is it possible to have an XML, one of which elements has mixed content, and deserialize the text in the mixed element as a custom object instead of as string?
I tried this:
    [XmlText(typeof(textType))]
    [XmlElement("query", typeof(templateBodyQuery))]
    [XmlElement("expand", typeof(expandType))]
    [XmlElement("insert", typeof(expandTypeInsert))]
    public object[] Items { get; set; }

Expecting the text items would be serialized as textType, but I get an 'textType' cannot be used as 'xml text' error.
This is my textType class:
public class textType
{
    [XmlText]
    public string Value { get; set; }
}

Answer: You can't use non primitive types for XmlText.  Also I'm not sure I understand how that xml would be structured as you can't have XmlText and XmlElements under a single node.
I think this is what you're trying to do:
[XmlElement("textType",typeof(textType))]
[XmlElement("query", typeof(templateBodyQuery))]
[XmlElement("expand", typeof(expandType))]
[XmlElement("insert", typeof(expandTypeInsert))]
public object[] Items { get; set; }

which deserializes:
<Test>
    <textType>example</textType>
    <query>...</query>
    <expand>...</expand>
</Test>

To a class Test that has a textType object at the start of the Items array with Value of "example"


Error - Access is denied - deployment to Azure Registration App Services

Question: I tried to alter the dotnet version with the global.json. However, when i run az webappyment source config-zip --resource-group ...
i still get
[Errno 13] Permission denied: 'C:\\Users\\Vag\\Dropbox\\OTHER\\M HCI\\thesis\\4. tutorial and import data\\14.nlp-with-dispa
 Traceback (most recent call last):
   File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-unpacked-wheel-yccaebu4\knack\cli.py", line 233, in invoke
 ...

Answer: Looks like you are trying to access the file that is stored under the user's directory "Vag" (C:\Users\Vag)
In Windows, you will not be able access the other user's directory unless you explicitly run the process with elevated Admin Privileges. You can either run the terminal with "Run as Administrator" or copy to non-user directory
Comment: Even with admin Privileges the result is the same. My issues relates with https://stackoverflow.com/questions/62760206/how-do-i-resolve-access-denied-error-when-trying-to-deploy-echobot-in-azure


What does "in position" mean when referring to scored music?

Question: On Justin Sandercoe's site he recommends a flute book for guitarists, this caught my eye:

Why a flute book? because most sight reading books for guitar are
  written for guitarists and are either in position or are mind numbing
  boring random notes and scales. This book is full of short beautiful
  melodies by the greatest composers so the reading is actually fun! As
  well  as that the melodies are real, not exercises so you get "real"
  experience of reading real melodies. They are also not in position so
  you get used to choosing a position to read in. There are many time
  signatures covered too - so you can develop that skill.

I've never heard of the phrase "in position" or "not in position", can someone explain what it means exactly?
Answer: In playing string instruments, the term "Position" refers to the placement of the left hand along the fretboard/fingerboard. Different instruments might number them differently, but with guitar, I think its the number of the fret that your index finger is would be stopping. So when your fingers are in the "usual" place, at 1st, 2nd, 3rd, and 4th frets, you are in "first position" (or more accurately, your hand is in first position). When you move up the neck, you are playing in a higher position (seconds, third, etc..., for each next fret higher).
As a side note, even in guitars, the word position can be used in slightly different ways (using different numbering schemes). See here for much more details: I don't understand scale positions.
I think what this advice is saying is that guitar practice books are often written with these mechanical aspects in mind, and either are written in such a way as to take advantage of your hands being in a certain position, and/or have the position actually marked on the music. By suggesting flute melodies, where no positions were even considered when written, the guitarist must decide which position to play in while reading the music, thus giving them more practice in learning an additional aspect of guitar playing (and one which the author apparently feels is neglected).
Answer: Having just dug out the flute book in question from my archives (!), it seems like not a bad idea. The first few tunes can be played using open strings and not moving too far up the neck. On guitars, once one learns that there are two octaves available without moving up or down more than 4 or 5 frets, one can play most, if not all of a particular tune in that position. E.g. in A major, start on the 6th string, fret 5, and all the notes you'll need are between fret 4 and fret 7, but some tunes may go higher, and then one may use the next 'position' up.
The idea is good, given that a flute is played at actual pitch, whereas a guitar sounds an octave lower than read. This isn't a problem. The downside is that the lowest note a flute plays is the B found on 5th string, 2nd fret/ 6th string, 7th fret. So one can't practise reading and playing notes lower than this from dedicated flute music.
So, to answer, one needs to look at the whole tune, check highest and lowest notes to be played, and decide where on the guitar is the optimum fret place to play, without having to slide up or down at all, if possible, and generally it is more than a possibility. Obviously, it's o.k. to move to another position for part or all of a tune, maybe to generate a change in tone, using thicker strings, further up the neck, for instance.
So, the term doesn't really refer to the scored music - far more to where a guitarist will want/need to play it.
Comment: There are two different types of "foot joint" that can come with a flute. The (standard?) C foot only goes down to C, while the B foot is about an inch longer, and throws in an extra key that takes the flute down to B.
Comment: On a slight tangent, how does one play that B? I thought Middle C was as low as you could go - basically "press everything!" - so is this B3?


Copula for non-standard distributions in R

Question: I'm trying to model a bivariate distribution using copulas in R. See image below for the pairs plot of the data. Variable 1 can be modeled nicely using a gamma distribution, but variable 2 fails miserably. I think the only way variable 2 could be modeled is by a customized piece-wise distribution?

See the histograms below:
The green bars indicate the distribution of the observed data, and the blue bars indicate the distribution of the sampled data with gamma distributions with rate and shape as in the title of the graph.

I've been folling the tutorial here:
https://www.r-bloggers.com/how-to-fit-a-copula-model-in-r-heavily-revised-part-2-fitting-the-copula/
Using the copula and VineCopula packages, using BiCopSelect, it tells me that I need to use "Rotated Tawn type 1 270 degrees", familycode = 134, parameter1 =  -2.669133 parameter 2= 0.1562118, although I have no idea how to achieve this, "Tawn type" doesn't seem to be one of the standard family names.
So running BiCopSelect again but this time having the input parameter familyset = c(1,2,3,4,5,6,7) , restricting to the standard family types, it tells me I should use Bivariate copula: Frank (par = -0.23, tau = -0.03).
Code I used:
library('VineCopula')
library('copula')

#Build the distribution
my_dist <- mvdc(frankCopula(param = -0.2279837, dim = 2), margins = c("gamma","gamma"), paramMargins = list(list(shape = 0.6524258, rate = 0.01375649), list(shape = 1.637544, rate = 0.01215565)))

# Generate random sample observations from the multivariate distribution
v <- rMvdc(5000, my_dist)
# Compute the density
pdf_mvd <- dMvdc(v, my_dist)
# Compute the CDF
cdf_mvd <- pMvdc(v, my_dist)

# 3D plain scatterplot of the generated bivariate distribution
par(mfrow = c(1, 2))
scatterplot3d(v[,1],v[,2], pdf_mvd, color="red", main="Density", xlab = "u1", ylab="u2", zlab="pMvdc",pch=".")
scatterplot3d(v[,1],v[,2], cdf_mvd, color="red", main="CDF", xlab = "u1", ylab="u2", zlab="pMvdc",pch=".")
persp(my_dist, dMvdc, xlim = c(-4, 4), ylim=c(0, 2), main = "Density")
contour(my_dist, dMvdc, xlim = c(-4, 4), ylim=c(0, 2), main = "Contour plot")
persp(my_dist, pMvdc, xlim = c(-4, 4), ylim=c(0, 2), main = "CDF")
contour(my_dist, pMvdc, xlim = c(-4, 4), ylim=c(0, 2), main = "Contour plot")

Which produced the following plots:

However the density plot doesn't look correct because the density is supposed to be the highest when var1 = 0 and var2 = 0, however the density is the highest when var1 = 0 and var2 is large.
Another problem is that I'm not sure what to do about var2's distribution! It's obviously not correct using gamma, but it is not a negative binomial or some other standard distribution either, and I think the margins field in the function mvdc only accepts strings of the standard distributions. Is there any way of defining my own distribution as input into the mvdc function?
Answer: About the perspective and contour plots looking strange: It's true that the maximum of the density is not at $(0,0)$, but also you are plotting only a tiny part of the distribution. Try different xlim and ylim arguments, e.g.,
persp(my_dist, dMvdc, xlim = c(0, 300), ylim = c(0, 300), n.grid = 51)

About custom marginal distributions for the copula model: That's possible simply defining a density function dsomething, a distribution function psomething, and (if you need sampling) a quantile function qsomething in the global environment of R. Here is an example with a Gaussian mixture distribution; I made up some parameter values:
dgmix <- function(x, p1, mean1, sd1, mean2, sd2) {
  p1 * dnorm(x, mean1, sd1) + (1 - p1) * dnorm(x, mean2, sd2)
}

pgmix <- function(x, p1, mean1, sd1, mean2, sd2) {
  p1 * pnorm(x, mean1, sd1) + (1 - p1) * pnorm(x, mean2, sd2)
}

curve(dgmix(x, p1 = 0.3, mean1 = 0, sd1 = 20, mean2 = 200, sd2 = 100),
      from = -50, to = 300, n = 1001)

paramMargins <- list(list(shape = 0.652, rate = 0.014),
                     list(p1 = 0.3, mean1 = 0, sd1 = 20,
                          mean2 = 200, sd2 = 100))

my_dist <- mvdc(copula = frankCopula(param = -0.228),
                margins = c("gamma", "gmix"),
                paramMargins = paramMargins)

persp(my_dist, dMvdc, xlim = c(0, 300), ylim = c(-50, 300), n.grid = 51)

Comment: A question: How would you go about specifying qgmix? It's basically a case of trying to find the quantile function of the sum of two independent distributions? The only way I can think of how to do this is if we knew the actual formula and integrate?
Comment: Oh wait not integrate, more like summation, because the distribution is discrete. But wouldn't we still need to know the formula representing the distribution?
Comment: Unfortunately, the quantile function of a Gaussian mixture does not have a closed form. You will need to use some numerical method (such as Newton-Raphson) with the distribution function. Actually, there are better ways to sample from a Gaussian mixture, but those are harder to use with the `copula` package for R...
Comment: For more information, see the following questions: https://stats.stackexchange.com/questions/177049/quantile-function-for-a-mixture-model, https://stats.stackexchange.com/questions/73028/inverse-transformation-sampling-for-mixture-distribution-of-two-normal-distribut


How to change the variables in $\frac{1}{(z+1)^{n+1}}=\frac{(-1)^n}{n!}\frac{d^n}{dz^n}\left( \frac{1}{z+1}\right)$?

Question: We know that
$$\frac{1}{(z+1)^{n+1}}=\frac{(-1)^n}{n!}\frac{d^n}{dz^n}\left( \frac{1}{z+1}\right).$$
If we put $z=e^t$ how can we change the variables above equation?
I know that $z\frac{d}{dz}=\frac{d}{dt}$. So how can we write $\frac{d^n}{dz^n}\left( \frac{1}{z+1}\right)$?
Is $z^n \frac{d^n}{dz^n}=\frac{d^n}{dt^n}$?
Comment: $$z^n\frac{d^n}{dz^n}\ne \frac{d^n}{dt^n}=(z\frac{d}{dz})^n$$
Comment: @MarkViola Thank you. So how to write it to obtain $\frac{1}{(e^t+1)^{n+1}}$? Do we need to use Stirling numbers?
Comment: Yes, in general for a $n$ times differentiable function $f$ we have$$\left(z\frac{d}{dz}\right)^n\{f\}=\sum_{k=1}^n  \begin{Bmatrix} n \\ k \end{Bmatrix}z^k\frac{d^k\,f}{dz^k}$$
Answer: In general, if $f(z)$ is $n$ times differentiable, then we have
$$\left(z\frac{d}{dz}\right)^n\{f(z)\}=\sum_{k=1}^n  \begin{Bmatrix} n \\ k \end{Bmatrix}z^k\frac{d^k\,f(z)}{dz^k}$$
where $\begin{Bmatrix} n \\ k \end{Bmatrix}=\frac1{k!}\sum_{j=0}^k (-1)^{k-j}\binom{k}{j}\,j^n$ are the Stirling Numbers of the Second Kind.
For $f(z)=\frac1{z+1}$, we find
$$\begin{align}
\left(z\frac{d}{dz}\right)^n\left(\frac{1}{1+z}\right)=\sum_{k=1}^n  \begin{Bmatrix} n \\ k \end{Bmatrix}z^k\frac{(-1)^k\,k!}{(1+z)^{k+1}}
\end{align}$$
Letting $z=e^t$, we find that
$$\begin{align}
\frac{d^n}{dt^n}\left(\frac{1}{1+e^t}\right)&=\frac{1}{1+e^t}\sum_{k=1}^n  \begin{Bmatrix} n \\ k \end{Bmatrix}(-1)^k\,k! \left(\frac{e^t}{1+e^t}\right)^k\\\\
&=\frac1{1+e^t}\sum_{k=1}^n\sum_{j=0}^k (-1)^j\binom{k}{j}j^n\left(\frac{1}{1+e^{-t}}\right)^k
\end{align}$$
Comment: @SomaWick What do you mean?  We have an explicit formula for the derivative that involves a finite sum with the Stirling coefficients or a double finite sum with the binomial coefficients.
Comment: But from this, we cannot get the formula for $\frac{1}{(e^t+1)^{n+1}}$.
Comment: Thank you. Actually, I want to write an explicit formula for $\frac{1}{(e^t+1)^{n+1}}$. That is my whole intention.
Comment: You're welcome.  It was my pleasure.  And now you have an explicit formula for the $n$th derivative of $\frac1{1+e^t}$.
Comment: And feel free to up vote and accept an answer as you see fit.


DeviceControllerApplicationConnectionFailed in google chromecast

Question: I am integrating Google Chromecast in my videoplayer app. I have referred this link:
https://developers.google.com/cast/docs/ios_sender_integrate
It displays Chromecast device but when I am trying to connect that device it returns an error. Here is the error log:
<code> -[GCKEventLogger logDeviceController:sessionID:application:connectionFailedWithError:]  LOG EVENT: DeviceControllerApplicationConnectionFailed device=<0x1311cc710:GCKDevice> [com.google.cast.CastDevice] 'Chrome Cast IBL' 192.168.1.185:8009 (e8fc847534f5fcb8e8c7190dc05458b6), sessionID=1272110429, appID=F1D64732, error=2
</code>
Any idea what would cause this? Thanks in advance.
Comment: googlecast demo app link please refere it https://github.com/googlecast/CastVideos-ios
Answer: This type Problem occur because of slow internet connection then its take more time to connect with Chromecast so because of timeout its Failed to connect. So you need to reconnect(stop casting and connect again) then it easily connect with chromecast.
Comment: i have satisfied internet speed but i getting same issue with chromecast :(
Answer: If you followed the documentation properly but the error still occurs, try the official troubleshooter. Also make sure that your device has a supported operating system to install the Google Cast extension. You can check on this thread for more workaround that can help you.


What is the insecure orange tag in the modules release pages?

Question: I was checking today the release page for the Admin Toolbar module and see an orange tag with the text Insecure I tried to find an explanation about it without luck, anyone knows what this means?
Answer: It's a tag that is automatically added when a more recent release for the same branch has been tagged as release that fixes security issues. In the case of the 3.0.1 release, it's the 3.0.2 release.

The Security update tag is manually added from the Security Team, and it cannot be removed once added. (Actually, the release type cannot be anymore changed, once Security update is selected.)


Quero ao reconhecer o cpf na tabela, exibir uma pagina com outros dados. Onde estou errando?

Question:
Warning: mysql_num_rows() expects parameter 1 to be resource, object given in C:\xampp\htdocs\solidario\associados.php on line 15

Meu codigo php
<?php

include"conectar.php";

// RECEBENDO OS DADOS PREENCHIDOS DO FORMULÃ?RIO !
// $funct       = $_POST ["funct"]; //atribuição do campo "nome" vindo do formulário para variavel
$cpf = $_POST ["cpf"];  //atribuição do campo "cpf" vindo do formulário para variavel

$query="select cpf from teste where cpf = '" . $cpf . "'";
        $stmt = mysqli_query( $con, $query);
if( $stmt === false) {
    die( print_r( mysqli_error($con), true) );
}
else
    {$rows = mysql_num_rows($stmt);
     if ($rows === true) {
     include('index.php');}
      else
      {include('dr-adesao.php');}
    }

mysqli_close( $con );
?>

Minha conexão está funcionando!
Acredito que o erro seja no arquivo PHP!
Comment: Leia [Por que não devemos usar funções do tipo mysql_*?](https://pt.stackoverflow.com/questions/579). Altere `$rows = mysql_num_rows($stmt);` para `$rows = mysqli_num_rows($stmt);`
Comment: fiz a alteração mas mesmo com o cpf já cadastrado na tabela, ainda me remete a pagina de tabela não afetada!
Comment: Vamos por passos, o erro foi corrigido ? Remove o espaço que tem na linha `$cpf = $_POST ["cpf"]` deixando assim `$cpf = $_POST["cpf"]`
Comment: sim corrigi, mas me mandou para .. else dr-adesao.php e como o cpf já está na tabela, deveria me enviar para index.php
Answer: O erro está acontecendo porque você esta utilizando o método antigo da extensão MySQL mysql_num_rows deve alterar para o novo método mysqli_num_rows.

O método mysqli_num_rows obtém a quantidade de linhas de um resultado e não um valor Booleano, deve alterar a linha:
if ($rows === true)

Para:
if ($rows === 1)

Ou
if ($rows > 0)

Remova o espaço que tem na linha
$cpf = $_POST ["cpf"];
             ^
$cpf = $_POST["cpf"]; // Deixe assim

Para retornar os dados você deve alterar sua Query SQL de:
$query="select cpf from teste where cpf = '" . $cpf . "'";

Para:
$query="select conlunaA, colunaB, colunaC from teste where cpf = '{$cpf}'";

Altere colunaA, colunaB, colunaC para o nome das colunas que contém sua tabela.
Comment: Obrigado wéllingthon! mas eu só tenho uma coluna e esta se chama cpf.
Comment: Entendi, é porque eu fui pelo titulo da pergunta.
Comment: deixa eu te perguntar, será que o erro esta no mysqli_num_rows?
Comment: bom vou tentar ser mais especifico... tenho um número de cpf na tabela, ao digitar na tela o numero da tabela essa tela me envia para uma tela demostrando o restante do cadastro!
Comment: Veja que você começou usando `mysqli_*` na hora que você está retornando o número de linhas que a `query` retornou você está usando `mysql_num_rows` creio que isso cause o problema, não tenho como testar agora.
Comment: eu já troquei está assim agora
Comment:
Comment: Altere a linha `if ($rows === true)` para `if ($rows > 0)`
Comment: Wéllingthon muito obrigado! Me ajudou mesmo!


Mixed effects vs linear regression: accuracy of beta estimation

Question: Let's say you have a response variable and an independent variable. Your data is measured across several levels of a categorical independent variable. One approach in analysing these data would be to use linear regression to estimate a slope at each level of the categorical independent variable. This is the approach I've used here, using sleepstudy dataset from the R lme4 package (I've stored the betas from each model in lmBetas):
library(lme4); library(plyr); library(ggplot2)
lmBetas <- daply(sleepstudy, .(Subject), function(x) coef(lm(Reaction ~ Days, data=x))["Days"])

Another approach in analysing these data would be to use a mixed effects model to estimate slopes for each level of the categorical independent variable, which in this case is Subject. This is the approach I've taken here (I've stored the betas from the model in lmerBetas):
lmerBetas <- coef(lmer(Reaction ~ Days + (Days | Subject), data=sleepstudy))$Subject[,"Days"]

I have learned that a single mixed effects model, as implemented through the lmer function in R, is more accurate at estimating slopes than a multiple linear regression model applied to multilevel data. This can be demonstrated with this plot of betas from the above models.
betas <- data.frame(method.betas = c(lmerBetas, lmBetas))
betas$method <- c(rep("lmer", 18), rep("lm", 18))

ggplot(betas, aes(method.betas)) +
  geom_histogram() +
  facet_grid(method ~ .)

The top histogram shows betas estimated using linear regression, and the bottom histogram shows betas estimated using mixed effects. You can see betas estimated using linear regression are more widely spread than those estimated through the mixed effects model.

So finally, my questions:

Is a mixed effects model's higher accuracy in betas estimation connected with the fact that it models intercepts and slopes for each level of the categorical independent variable under a joint probability distribution?
Generally speaking, why is a mixed effects model more accurate in its betas estimation?
Answer: The graph you have shown does not show that the coefficients in a mixed effects model are more accurate. It just shows that they are closer together in a mixed effects model. This would mean that the estimate is more precise when it would have been some approximation of the sampling distribution of a single fixed parameter, but that is not what is being shown. When you estimate a mixed effects model, you think that the effects differ across groups and you estimate these different effects. It is a well known property of the mixed effects estimator that the individual effects are "shrunken" towards the overall mean. This is a strength and a weakness; it is how one can get reasonably stable estimates even if the number of observations in each subgroup is small, but it is also a source of bias.
You can read more about this in any textbook on multilevel analysis; I like Tom Snijders and Roel Bosker (1999) Multilevel Analysis. An introduction to basic and advanced multilevel modeling. London: Sage.


Backwards Facing Content Grouping

Question: Need to group some pages on my site together but apparently content grouping would only be forward facing. Is there a way to apply content grouping to prior data or create a calculated column as such which would allow GA to filter and group older data?
Answer:
Is there a way to apply content grouping to prior data?

No, content grouping only applies going forward.

or create a calculated column as such which would allow GA to filter
  and group older data?

No, any data you add to GA is only available as of the moment you create it.
What you can do:

GA:

Use Query Filters (not view filters) or segments: filters/segments don't create any data, they just filter it. So if you create 1 filter/segment per group and query the data, you will effectively have the same data as if you had done content grouping
Use Regex: GA supports regular expression which might help you create the filters you need
Use the API: since applying filters/segments might be tedious to do (and repeat) via the UI, you might want to use the API, for instance via the Google Sheets GA API add-on (see further details below)

Example of Google Sheets GA API add-on query to group some content that would match all pages which start with /foo or /bar (see list of API dimensions and metrics, see legacy filters syntax):
ga:pagePath=~^/(foo|bar)

Once you have figured out 1 query for 1 group you can clone them, query all your data, and then reaggregate it.

Google Data Studio:
GDS has a feature called Calculated fields which effectively allows you to create content groupings which apply to both historical and new data. Most likely you want to do this with a CASE statement:
CASE
    WHEN REGEXP_MATCH(Page,'^/(foo|bar)') THEN "Group A"
    WHEN REGEXP_MATCH...
    ELSE "Other"
END

Comment: Nitpicking, calculated fields in Google Analytics do work on historic data (after all they do not add anything, they work on data that's already there), the problem here is that in GA there are only calculated metrics, not calculated dimensions, so they do not help with the use case in the original post. Calculated fields in Data Studio are the solution.
Comment: yes @EikePierstorff indeed I forgot the calculated metrics in GA apply retroactively.

Backwards Facing Content Grouping


Enviar dados para um ficheiro pdf e email

Question: Boa tarde gostaria de guardar dados de um formulário de uma página html quando os users fazem o registo e submissão num ficheiro pdf e ser enviado para um email predefinido mas não sei como fazer isso, tenho o formulário criado da seguinte forma:
    <!doctype html>

<meta charset="utf-8">
<title>Formulário</title>

 Preencha o formulário abaixo para participar no curso de Linux Administração

<form action="Script_do_Formulario.php" method="post">

<fieldset>
 <legend>Dados Pessoais</legend>

    Nome:

    <input type="text" name="email">

    Apelido:

    <input type="text" name="sobrenome">

    Data de Nascimento:

    <input type="text" name="dia" size="4" maxlength="2" value="dd">
   <input type="text" name="mes" size="6" maxlength="2" value="mm">
   <input type="text" name="ano" size="8" maxlength="4" value="aaaa">

    Localidade:

    <input type="text" name="rg" size="13" maxlength="13">

    Código Postal:

    <input type="text" name="cpf" size="9" maxlength="9"> - <input type="text" name="cpf2" size="2" maxlength="2">

</fieldset>

<fieldset>
 <legend>Morada</legend>

    Rua:

    <input type="text" name="rua">

    Numero:

    <input type="text" name="numero" size="4">

    Localidade:

    <input type="text" name="bairro">

    Distrito:

    <select name="estado">
    <option value="av">Aveiro</option>
    <option value="be">Beja</option>
    <option value="br">Braga</option>
    <option value="bg">Bragança</option>
    <option value="cb">Castelo Branco</option>
    <option value="cm">Coimbra</option>
    <option value="ev">Évora</option>
    <option value="fr">Faro</option>
    <option value="gd">Guarda</option>
    <option value="lr">Leiria</option>
    <option value="lx">Lisboa</option>
    <option value="Pg">Portalegre</option>
    <option value="pt">Porto</option>
    <option value="st">Santarém</option>
    <option value="sb">Setúbal</option>
    <option value="vc">Viana do Castelo</option>
    <option value="vr">Vila Real</option>
    <option value="vs">Viseu</option>
    <option value="im">Ilha da Madeira</option>
    <option value="ia">Ilha dos Açores</option>
    </select>

    Cidade:

    <input type="text" name="cidade">

    Código Postal:

    <input type="text" name="cp" size="3" maxlength="4"> - <input type="text" name="cp2" size="2" maxlength="3">

</fieldset>

<fieldset>
 <legend>Contacto Email</legend>

    E-mail:

    <input type="text" name="email">

</fieldset>

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

Answer: Apenas utilizando HTML você não conseguirá fazê-lo de forma fácil (há bibliotecas em JavaScript que poderiam cuidar desta paete) mas algo simples de implementar, mas requerendo um cliente de e-mail instalado e configurado no computador do usuário, é simplesmente fazer:
<form action="mailto:«conta de e-mail»" method="get">
   ...
</form>

Daí os dados do formulário serão enviados para o endereço de e-mail indicado no formulário.
Mas também vi que teu formulário, a princípio, enviaria os dados para um programa em PHP, o "Script_do_Formulario.php", neste caso sua dúvida seria também nesta linguagem?
Então um programa bem simples para receber e enviar os dados do formulário para um endereço específico de e-mail seria mais ou menos assim:
<?php
    /* lê os campos via POST */
    $nome = $_POST['nome'];
    ...

    /* alguma validação */
    ...

    /* monta a mensagem */
    $mensagem = "Ficha de Inscrição\n".
        "- - - - - - - - - - - - - - - - - - - -\n".
        "Nome : ".$nome."\n".
        "- - - - - - - - - - - - - - - - - - - -\n";

    mail('firstname.lastname@example.com','Ficha de Inscrição', $mensagem);
?>

Claro, este programa recupera apenas "nome" do formulário (é possível perceber a lógica para fazer o mesmo com os demais campos) e monta o corpo de uma mensagem para ser enviada pela função mail() do próprio PHP.
Comment: Sim, pois nunca programei em PHP
Comment: Acrescente a tag 'php' na tua pergunta.
Comment: em que sitio em concreto ponho a tag 'php' no meu código? pergunto porque não estou a entender em que sitio


Passar dados para uma janela modal Bootstrap

Question: Não estou conseguindo passar os dados de uma tabela que tenho em uma página .php para uma janela modal que mostre esses dados, que seria para edição.
A única coisa que consigo passar é o id, que por sua vez consegue ser utilizado para realizar o update no banco de dados sem problemas caso eu preencha os inputs.
Gostaria de saber como posso passar esses dados da tabela para os input texts por JavaScript, ou por outro meio se possível.
Trigger para abrir a modal:
<i class="fas fa-edit ml-1" title="Editar" data-toggle="modal" data-target="#modalCliente" id="btnEditar" onclick="editar(<?= $cliente->id ?>)">

Inputs da janela modal:

    Nome do Cliente
    <input class="form-control" type="text" id="nomeCliente" name="nomeCliente">

    CPF
    <input class="form-control" type="text" id="cpfCliente" name="cpfCliente" onkeydown="javascript: fMasc( this, mCPF );">

    CNPJ
    <input class="form-control" type="text" id="cnpjCliente" name="cnpjCliente" onkeydown="javascript: fMasc( this, mCNPJ );">

Tabela que lista os dados:

        Nome
        CPF
        CNPJ
        ID
        Opções

    <? foreach ($listaCliente as $indice => $cliente) { ?>

                <?= $cliente->nome ?>

                <?= $cliente->cpf ?>

                <?= $cliente->cnpj?>

                <?= $cliente->id ?>

                <i class="fas fa-edit ml-1" title="Editar" data-toggle="modal" data-target="#modalCliente" id="btnEditar" onclick="editar(<?= $cliente->id ?>)">

    <? } ?>

Answer: Nos inputs da modal você não informou onde quer passar o id, mas uma forma de preencher os inputs da modal é alterar a forma de chamar a função editar. Primeiro altere o onclick para:
onclick="editar(this)"

O this como argumento representa o elemento clicado. Assim fica fácil de pegar os dados da respectiva linha.
E a função editar ficaria assim para pegar os valores das colunas:
function editar(e){

   var linha = $(e).closest("tr");
   var nome = linha.find("td:eq(0)").text().trim(); // texto da primeira coluna
   var cpf  = linha.find("td:eq(1)").text().trim(); // texto da segunda coluna
   var cnpj = linha.find("td:eq(2)").text().trim(); // texto da terceira coluna
   var id   = linha.find("td:eq(3)").text().trim(); // texto da quarta coluna

   $("#nomeCliente").val(nome);
   $("#cpfCliente").val(cpf);
   $("#cnpjCliente").val(cnpj);

}

Veja:

function editar(e){

   var linha = $(e).closest("tr");
   var nome = linha.find("td:eq(0)").text().trim(); // texto da primeira coluna
   var cpf  = linha.find("td:eq(1)").text().trim(); // texto da segunda coluna
   var cnpj = linha.find("td:eq(2)").text().trim(); // texto da terceira coluna
   var id   = linha.find("td:eq(3)").text().trim(); // texto da quarta coluna

   $("#nomeCliente").val(nome);
   $("#cpfCliente").val(cpf);
   $("#cnpjCliente").val(cnpj);

}

<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.13/css/all.css" integrity="sha384-DNOHZ68U8hZfKXOrtjWvjxusGo9WQnrNx2sqG0tfsghAvtVlRW3tvkXWZh58N9jp" crossorigin="anonymous">

        Nome
        CPF
        CNPJ
        ID
        Opções

                Fulano

                cpf123

                cnpj123

                1

                Ciclano

                cpf456

                cnpj456

                2

Modal title

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

             Nome do Cliente
             <input class="form-control" type="text" id="nomeCliente" name="nomeCliente">

             CPF
             <input class="form-control" type="text" id="cpfCliente" name="cpfCliente" onkeydown="javascript: fMasc( this, mCPF );">

             CNPJ
             <input class="form-control" type="text" id="cnpjCliente" name="cnpjCliente" onkeydown="javascript: fMasc( this, mCNPJ );">

        <button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>

Comment: Era exatamente o que eu queria, o problema acima foi resolvido apenas com isso, que estava quebrando minha cabeça. Agora outro "problema" que surge, é que os dados da table não são todos os que existem na tabela cliente do BD, existem outros atributos como email, telefone, etc. Para isso, eu consigo utilizar da função editar() para acessar o BD e resgatar os esses dados, através do ID ?
Comment: Sim, aí vc teria que usar Ajax.


Do prime solutions to $XY + Z - W$ always occur in threes, modulo the obvious $XY=YX$?

Question: If $ab + c = d$ has a prime solution and $ca + b = e$ is another prime solution.  Then is $bc + a = f$ another prime solution?
Answer: No: for example, $3\cdot 4 + 7 = 19$ and $4\cdot 7 + 3 = 31$ are both prime, but $3\cdot 7 + 4 = 25$ is not.
Or if you want $a$, $b$, and $c$ to be primes as well, then $2\cdot 11 + 7 = 29$ and $7\cdot 11 + 2 = 79$ are both prime, but $2\cdot 7 + 11 = 25$ is not.


Count regression with censored counts that aren't necessarily zero.

Question: Say you have count outcomes $Y_1, ..., Y_n$ out of different population sizes (e.g. offsets in a usual count model) $p_1, ..., p_n$. I want to relate this to a covariate $X_1, ..., X_n$ using a usual log-linear model
$$ {\rm log}(\lambda_i) = \log(p_i) + \beta_0 + \beta_1 X_i $$
where $\lambda_i$ is the poisson rate of $Y_i$. The problem is a decent proportion of the $Y_i$ are censored, e.g. you don't get an exactly value if $Y_i < m$. So, when $Y_i$ is censored, all you know is $Y_i \in \{0, 1, ..., m-1 \}$. If I wrote my own, this could enter directly into the likelihood and fit that way but I don't really want to do that unless I have to.
Is there existing methods for doing this? I'm assuming there's a buzzword I'm missing here (is it "hurdle model"?? Seems like those are all only when the cut off is zero...) that's making it hard for me to find a canned way to do this. Any thoughts are appreciated.
Comment: BTW, a lot of the censored counts probably are zero, so I could just do zero inflation if it really came down to it ...
Answer: Stata has a censored Poisson model (cpoisson) that would allow you to do this pretty easily. It can handle both bottom and top censoring with individual-specific thresholds. Details and references can be found here.
The log-likelihood is pretty straightforward, so it might be be pretty easy to hack together.
Comment: Thanks. Also you're right that the likelihood for the censored data was super simple. I coded it in R and got it to work using `optim()`


solving random walk problem with law of total probability

Question: A drunk man goes right with probability $P$ and left with probability $1-p$
. What's the probability  he will get to $-1$ before getting to $2$ ? (The drunk man starts at 0)
I tried to solve it with law of total probability however my answer is wrong from some reason .
My answer:
Let $P(X)$ be the location of the drunk man
.There are only 2 cases, one where he goes left and one where he goes right .
$P(X=-1)=P(X=-1|Left)P(Left)+P(X=-1|Right)P(Right)$
$P(X=-1|Left)P(Left) =1-p $
$P(X-1|Right)P(Right)=p(1-p)P(X=-1)$ because he goes right with probability $p$ and in order to get to $-1$ he has to go left ($1-p$) and then we are at the starter point $P(X=-1)$
Comment: I assume we start at location 0.  What is your definition of $X$ and what is the meaning of the sentence "Let $P[X=-1]$ the point where he got $-1$"?  (A probability is not a point where someone gets something)
Comment: Yes we start at 0 .
X is location .
$P(x=-1)$ the location$ -1$ .
I will edit the post to clarify .
Comment: Please clarify what you mean by "X is location."  I assume $X$ is supposed to be a random variable.  Is it a random location?  At what time?  Do you really mean that $X_t$ is the location at time $t \in \{0, 1, 2, ...\}$?
Comment: X is a random variable that represents the first time the drunk man visits a point x.
Comment: The drunk man moves.  So, how is $X$ defined as "the location."  The location at what time?
Comment: Can I give you better notation with which you can solve the problem? Are you willing to receive that?
Comment: Yes if possible.
Comment: I think you mean to say that $X_t$ is a random variable that represents the man's location at time $t$.  Your equations should relate $X_{t+1}$ to $X_t.$
Comment: Well Lulu gives an answer below.  If you define $A$ as the event that we get to $-1$ before $2$, and if we use $X_t$ as defined above, her notation is $p(i) = P[A|X_0=i]$.
Answer: I assume he is starting at $0$.
Method I:  Geometric Series
The winning paths all have the form $\gamma_n=(RL)^nL$ for $n\in \{0,1,2,\cdots \}$.
(Here, of course, $R$ denotes a step to the right and $L$ denotes a step to the left.  I am reading the path from left to right, but it's easy to rewrite if you prefer the other convention). The probability that he follows $\gamma_n$ is $(p(1-p))^n(1-p)$
We easily compute the answer to be $$(1-p)\sum_{n=0}^{\infty} (p(1-p))^n=\boxed {\frac {1-p}{p^2-p+1}}$$
Note:  that this method only works so easily because you have a very small number of states to consider.
A method which extends more easily to situations with more states is:
Method II:  Recursion
There are only a few states to consider, according which position the drunk occupies.  For $i\in \{-1,0,1,2\}$ we let $P(i)$ denote the probability that he gets to $-1$ before he gets to $2$ assuming he is starting at $i$.  Of course $P(-1)=1$ and $P(2)=0$.  The answer we want is $P(0)$.
We remark that $$P(0)= (1-p)\times 1 +p\times P(1)$$
and $$P(1)=p\times 0 + (1-p)\times P(0)=(1-p)\times P(0)$$
It follows that $$P(0)=(1-p)+p(1-p)P(0)$$ which implies $$P(0)=\boxed {\frac {1-p}{p^2-p+1}}$$
Sanity checks: if $p=0$ this is $1$.  If $p=1$ this is $0$.  A little more work shows that $0≤P(0)≤1$ for $0≤p≤1$.
Comment: Again, $P(i)$ is defined to be the probability that our drunk gets to $-1$ before getting to $2$, assuming he starts at point $i$.  Since you are assuming he is starting at point $0$ you are asking about $P(0)$.
Comment: You can do it by Geometric Series, since the winning paths all have the form $(RL)^nL$ for some $n$.  I'm not a fan of that method because it really doesn't work if you have more states, but it's a good exercise to check that it works here.
Comment: Why is $P(0)$ the answer . isn't it the probability he gets to point $0$ ?
Comment: I understood the question to be asking "Assume the drunk starts at $0$ and moves right or left with probabilities as stated.  What is the probability that he gets to $-1$ before getting to $2$?".  Did you mean something else?
Comment: You understood correctly ,but I cant seem to understand how is $P(0)$ related to the answer . Aren't we seeking for $P(-1)$?
Comment: Note:  I added the argument by Geometric Series.


angularjs translate-value to get the value from i18n file

Question: I have the following html code to get angular to translate the label from dash.title and the span text from errors.correct.

my errors.correctin the i18n file is like this:
"errors": {
    "correct": "The « {{fieldname}} » is correctly filled out!"
  }

so my fieldname has to get the value from the label, it should be the same as the label text.
Why this setup is not working? what is the solution?
Answer: here is the solution:
translate-values="{ fieldname:'{{'dash.title' | translate}}' }"


How to Write A Ragtime Piano Piece?

Question: I tried writing a ragtime piece several months ago and wasn't successful.
What defines the ragtime style? Are there known go-to theoretical resources that discuss how to compose ragtime music?
My favorite ragtime artist is Scott Joplin. So that's the style I mean when I say ragtime.
EDIT:
Based on the video posted by Flounderer, I attempted to write a rag using exactly the same bass line as the video. I am not sure it qualifies as one, but if it does then future people with this question should watch that video as it goes step by step through what the author considers a rag.
Remark: So far, the only thing I understood about rags from that video was that rag time seems to occasionally involve desynchronizing the melody from the accompaniment.
Click here for sound:
Comment: You really need to revisit your notation.
Comment: A video that really helped me to understand the nature of ragtime is this one: https://www.youtube.com/watch?v=e8IM5-wUdng It explains why many people fail when they try to compose ragtime music.
Comment: @StanShunpike - sad to hear you don't care about notation. You'll find it hard to get people to play / listen to your music. As Gardner Reed said, "if you don't bother to take the time to write it down, why should I bother to take the time to play it?" I don't care how you write it, if you present it, it must be correct.  It's akin to poor grammar - all it does is undermine your intelligence and presents a poor image of you as a "competent" composer. Do your own research to figure out what you need to fix. Three great resources: Gardner Reed, Kurt Stone, Elaine Gould. Look them up.
Comment: Hmm. Perhaps I should take it more seriously. I had no idea it mattered this much. I'll see what I turn up in the sources u mentioned.
Comment: There's a widely-available 'Collected Works'.   But any collection of Joplin pieces will do.   It's an easy style to imitate really.
Comment: @jjmusicnotes It's not something I care about. I don't play. I just write scores using synthesizers. If you have suggestions, just make them and I can correct it if necessary.
Comment: I assume the problem is with the stems directions and the grouping given that everything else looks fine as far as key and the actual notes and articulations are fine. Is there an Elements of Style like Strunk and White but for music?
Comment: Your example shows the basic elements of ragtime - an 'oom-pah' left hand and a syncopated melody in 2/4 time using straight 8s.    Write some more, and look at the Joplin book for ways of developing the texture in the RH.     As mentioned, your rhythmic notation is hard to read.  Group according to the beats as a general rule.
Comment: @LaurencePayne what Joplin book?
Answer: Let's take two archetypal rags - Black and White Rag and The Entertainer.
The left hand mostly plays a steady pattern of a bass note on the 1 and 3, and a chord on the 2 and 4.

          1 2 3 4 1 2 3 4
LH chord    *   *   *   *
LH bass   *   *   *   *

Pretty much all ragtime has this regular oom-pah backing throughout, along with lead-ins and linking patterns.
But lots of musical styles have a backing just like this. What makes it ragtime is the syncopated rhythm of the right hand:
The Black and White Rag melody (ignoring the intro and the anacrusis and going straight to the main melody) is a 3 note pattern of half-notes:

          1 2 3 4 1 2 3 4
High note   *  *  *  * *
Mid note   *  *  *  *   *
Low note  *  *  *  *     *
---------------------------
LH chord    *   *   *   *
LH bass   *   *   *   *

Notice how the melody notes line up with the left hand - it's creating a polyrhythm in which the 3 note "pulse" of the melody comes in and out of phase with the basic left-hand 4/4 rhythm. But, at the end of two bars, the pattern varies, to "reset" and re-anchor the melody to the left-hand.
The first two bars of The Entertainer do the same thing, but with rests in place of some of the melody notes:

          1 2 3 4 1 2 3 4
High note                *
Mid note   *  *  *      *
Low note  *  *  *      *
---------------------------
LH chord    *   *   *   *
LH bass   *   *   *   *

(I've fudged melody, but not the timing, of the last three notes, just to squeeze it into three pitches)
This shows the syncopation more strongly - we hear the two-note pattern once with the first note on the downbeat, once with the first note just after the upbeat (and the second note on the downbeat), once with the first note on the upbeat.
Because the second note is higher, and the tonic, it feels like the accent of the melody, and it comes

first time, half a beat after the downbeat,
second time, on a downbeat,
third time, half a beat before a downbeat.

It's that shifting accent relative to the steady left-hand rhythm that makes ragtime.
I'd suggest working through your favourite rags, to see how the various sections have similar polyrhythms. Then try and replicate that in your own patterns.
Comment: @Slim let me see if I understand: Rag involves that standard LH chord-bass thing. I've seen that recur so it looks pretty characteristic. But the RH not only is syncopated but also tries to time it so that way different notes in the melody occur at key tonal points in the LH part to create a sense of....well rag. But the point is that, it's not just syncopation but also where the key events in the melody land relative to the LH part.
Answer: My favorite ragtime artist is Scott Joplin. So that's the style I mean when I say ragtime.
Well, that's sort of like "how do I compose baroque music?  My favorite baroque artist is J.S. Bach.  So that's the style I mean when I say baroque."
Scott Joplin killed ragtime just like Bach killed baroque music, leaving not much leeway to say anything sufficiently impressive.  You work hard on something in that direction and then you figure out that it does not actually sound as good as those minor Joplin/Bach pieces or finger exercises nobody is really interested in hearing any more these days ("Two part inventions" anybody?).
Well, take revenge on both.  Take some reasonably well-known semi-polyphonic Bach (Toccata D minor BWV565 anybody?) and rag it apart: put a basic sewing machine rhythm in the right hand, organize the left hand to have a semi-walking bass, pull apart all chords in the right hand into clean one-to-three note harmonies, put those parts working with the walking bass line on-beat and the others in between and leave out and fill in material until everything is working out.
It's somewhat akin to putting a violin shuffle on some melody.  Take a look at the  and figure out what it is without hearing the Midi first (unfortunately, it would appear that attaching a Midi file to an answer is not possible without hosting it somewhere, so I am appending the source at the end, and maybe somebody else will put the fragment somewhere).  It's a mixture of "real" material, bass notes and fill-in patterns falling into line.  Of course, starting with "real" material is a bit of cheating but you have to start somewhere.
I seem to remember that Scott Joplin actually wrote some sort of "how to write ragtime" guide.  I may be mistaken about that, but if he did, trying to get a hold of that might be a good idea, too.
And PostScriptum: LilyPond melody fragment source:

    \language "deutsch"

    \version "2.17.20"

    %{
    \paper { #(set-paper-size "a4" 'landscape) }
    #(set-global-staff-size 30)
    %}

    melody = {
       \clef treble
       \set Staff.midiInstrument = "violin"
       \key d \major
       \time 4/4  % s2.. <a fis'>16 <a fis'>
     <a fis'>16 <a fis'> <fis' a'> <a fis'> <a e'> <e' a'> <a d'> <a d'>
     <a fis'>-1-3 <a fis'> <a fis'> <fis' h'> <a fis'> <a fis'> <fis' c''> <a fis'>
     <a fis'> <a fis'> <fis' a'> <a fis'> <a e'> <e' a'> <a d'> <a d'>
     <h fis'> <h fis'> <h fis'> <fis' c''> <h fis'> <h fis'> <fis' h'> <h fis'>
     <h fis'> <h fis'> <g' h'> <h g'> <h fis'> <fis' h'> <h e'> <h e'>
     <cis' e'> <cis' e'> <cis' e'> <e' cis''> <cis' e'> <cis' e'> <e' h'> <cis' e'>
     <cis' a'> <cis' a'> <a' a'> <cis' a'> <cis' g'> <g' a'> <cis' e'> <cis' e'>
     <fis' a'> <c' fis'> <c' fis'> <fis' h'> <h fis'> <h fis'> <fis' a'> <b fis'>
     <a fis'> <a fis'> <fis' a'> <a fis'> <a e'> <e' a'> <a d'> <a d'>
     <a fis'>-1-3 <a fis'> <a fis'> <fis' c''> <a fis'> <a fis'> <fis' h'> <a fis'>
     <a fis'> <a fis'> <fis' a'> <a fis'> <a e'> <e' a'> <a d'> <a d'>
     <h fis'> <h fis'> <h fis'> <fis' h'> <h fis'> <h fis'> <fis' c''> <h fis'>
     <h g'> <h g'> <g' h'> <h g'> <h fis'> <fis' h'> <h e'> <h e'>
     <a' a'>-4-0 <cis' a'>-3-4 <c' a'>-2-4 <a' h'>-4-1 <h a'>-2-4 <b a'>-1-4-1 <a' c''> <h a'>
     <a' h'> <gis' h'> <a' g''> <g' a'> <g' c''> <cis'' g''> <g' c''> <e' dis'>

    }

    \score {
       \new Staff
       \melody
       \layout { }

       \midi {
        \tempo 4 = 60
       }
    }
Answer: Scott Bradlee is a pianist well-known for his ragtime/swing/vintage style arrangements of modern pop songs. He has written an e-book called Ragtimify in which he explains the basics of the ragtime style that he uses in his arrangement process. (Disclaimer: I am in no way financially associated with him or this product.)
Without going into the level of detail found in the book, the basics are (as others have already mentioned) a "stride bass" in the left hand, and a syncopated right hand with some chromatic passing tones. The stride bass refers to the root and fifth of the chord (possibly doubled at the octave) being alternately played on the strong beats (1 & 3) of the measure, while full chords are voiced in the middle of the keyboard (right around middle C) on the weak beats (2 & 4). This means the left hand is constantly hopping around, which can be very tricky to do.
Answer: My answer is short:

"oompah" bass with chords on beats two and four
chromatic mediants
augmented sixth chords (a fan of Joplin will see them everywhere)
heavy right hand syncopation in counterpoint to steady left hand
tuneful melodies
straightforward forms: binary (simple / rounded), ternary, rondo, etc.
tempi typically vary from Andante to Allegro, hardly anything much slower or faster.  If faster, you end up in "stride" piano territory, which is not what you are trying to accomplish.

For what it's worth, the very long post with an original rag does not seem very "rag" like - the left hand sort of abysmally plods along while the right hand leaves enough sky time through which Joplin could fly a plane, or write a second opera.
Comment: I agree. It didn't sound rag. It looks nice but when I actually tried it out in a synthesizer it just played like a very standard piece. It didn't yield a rag feel even though it is a derivative of Joplin. Somewhat surprising.
Answer: "So far, the only thing I understood about rags from that video was that rag time seems to occasionally involve desynchronizing the melody from the accompaniment."
Correct.  March in the left hand, syncopation in the right.  Flounderer posted a good video.  I like this one too:

The Wikipedia article on ragtime talks about its form:
https://en.wikipedia.org/wiki/Ragtime#Musical_form
What you have so far with your composition is a good start, just keep working on improving the melody line.  Maybe change up the rhythm a bit.  (Measures three and four as well as the final three measures all have the same rhythm.)
Maybe practice by taking an existing  piece and turning it into a rag, like what Ron O'Dell did with "Hungarian Rhapsody No. 5" here...
Answer: You can set it up like a march (in 2/4). Use Um-Pa or root then chord for the left hand. But the most important part is to syncopate the rhythm or else it's just a march.

How to Write A Ragtime Piano Piece?


How does a six-sided ring contrast from a four-sided ring?

Question: Total Nonstop Wrestling (TNA) fans recently voted to have the company bring back a six-sided ring(1) for their wrestlers to perform in.
How does a six-sided ring contrast from a four-sided ring? Obviously, one ring has six sides and the other has four sides, but how does this difference change the mechanics of the ring itself? (ie, Does it have more/less give? Is it more/less sturdy? etc.)
Answer: The UFC uses the octagon because it gives the fighters more actual floor area to maneuver in. By contrast a boxing ring is square so that one fighter can cut the ring off from the other fighter and force him up against the ropes as efficiently as possible.
For pro-wresting all this means absolutely nothing since it is strictly entertainment and part of entertaining is climbing up on the ring and jumping off the ropes.
Comment: Didn't think about the strategy part you mention in your first paragraph because of the facts you present in your second paragraph. Still interesting.


What are UI/UX patterns and their pros/cons for 1-to-1 assignments of items from two different sets?

Question: Think of two different "bipartite" sets of items: vehicles and drivers. The user has to make 1-to-1 assignments between these items like so:

Each vehicle can be assigned to 0 or 1 driver.
Each driver can be assigned to 0 or 1 vehicle.

What would be suitable UI/UX patterns for this?
I've already thought about providing three "drag-and-drop" lists: (1) unassigned vehicles, (2) unassigned drivers, and (3) 1-to-1 assignments of vehicles and drivers. But I'm not sure about the "most comfortable" workflows/actions for creating new assignments, flipping vehicles/drivers of two assignments, managing large numbers of items, etc. with as few clicks/actions as possible. Or maybe there is a UI/UX pattern I'm not aware of at all.
Comment: Asking with _Best_ in the title will probably get you close votes, I suggest rewording to ask something like "What are UI/UX patterns and their pros/cons"?
Comment: Thank you for the hint, @AndyDent.
Answer: Important Gotchas

When you're managing multi-list selection you need to be very specific about context - is this going to be on a narrow screen such as a phone or portrait tablet? Narrow screens are often poor for side-by-side lists.
This sounds like quite an industrial application - is it done in a setting where people are standing or walking and may be jostled? Drag-n-drop can lose things half-way.

One idiom is a copy-paste variant where tapping an item in one list selects it and you either can tap another item, or some other cancel zone or tapping in the second list pastes the connection.
If the lists are long, offer an option to show only the free items so you can focus on those left to be assigned. That can be a simple toggle, maybe three-way between All/Free/Set.
Comment: Thank you. The users are expected to use the software on a desktop PC with mouse and keyboard. I actually thought about a drag-and-drop operation of one unassigned item onto the desired item from the other list. This is pretty close to your suggestion, I guess.
Comment: Based on what I already thought of plus some of your suggestions I came up with a small and simple prototype: https://jsfiddle.net/Flinsch/f0ymhv6d/


Is there an easy way to globalize a variable in a class

Question: Im wondering if there is a simple way to globalize a variable in a python class. Im trying this example below but getting this  following error message:
UnboundLocalError: local variable 'gold' referenced before assignment
I dont want to type 'global gold' in every function.
gold = 10
class economy:
    global gold

   def income(self):
        gold+=5

    def expense(self):
        gold-=5

Comment: No there isn't. Python purposefully makes you write `global gold` to discourage you from making a horrible design decision like what you are trying to do right now. The *whole point* of classes is to avoid global, mutable state. There is definitely a better solution.
Comment: Put differently: no, that's not possible, and it really shouldn't be.
Comment: Either make it a class or an instance attribute. Don't make it global.
Comment: `global gold` would *only* apply to the code directly executed in the `class` statement when defining the class. It doesn't apply to any of the methods. Move the `global` statement into *each of the methods*.
Comment: Ok thanks for all the answers! Just wanted to know!
Answer: Better put gold in class, and reference from instance
class economy:
    def __init__(self, gold):
        self.gold = gold
    def income(self):
        self.gold+=5
    def expense(self):
        self.gold-=5

a = economy(90)
a.income()
a.gold # 95
a.expense()
a.gold # 90

Comment: Unless you make sure that `economy` is a singleton (which it currently isn't), then there are multiple `gold` variables: one per instance of `economy`.
Comment: @HannesOvrén but that's fine. This is why people have considered singletons an antipattern: they merely put a thin veneer on mutable, global state
Comment: @juanpa.arrivillaga I am not advocating the use of singletons. It seems like OP wanted `gold` to be global, and this solution makes it non-global, and is thus a bad answer to the question.
Answer: The most accessible variable in the class is an attribute and to use it outside of the class you can create a getVariable function like this :
gold = 10

class economy:
   gold = None

   def __init__(self,gold) :
        self.gold = gold

   def income(self):
        self.gold+=5

    def expense(self):
        self.gold-=5

    def getGold(self) :
        return self.gold

# to get the gold value from the object :
gold = economy(gold).getGold()


Find the least squares approximation g(x) = a0 + a1x of the function f(x) = sqrt(x), 1 <= x <= 4.

Question: HELP!! I'm floundering here....
Find the least squares approximation $g(x) = a_0 + a_1x $of the function $f(x) = \sqrt(x),$
from $1 \le x \le 4$.
I'm not sure how to set up this problem.
The problem does not define the inner product.
So I assumed standard basis ${1,x}$ and $< f , g > = \int(f*g)$ from $1$ to $4$.
Orthogonal basis $-> {1, x - 5/2}$
Orthonormal basis$ -> {1, 2x/3 - 5/3}$
Then by Least Squares approximation theorem $g = < f , w_1 >*w_1 + < f , w_2 >*w_2 + ... + < f , w_n  >*w_n$
$g(x) = 44x/135 + 520/135$ which is nowhere near $\sqrt{x}$.
Comment: [Here's a MathJax tutorial](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) :)
Answer: Hint
I suppose that there is an error in the calculation of $a_0$. $a_1$ is exact. Try to find the error. By the way, $520/135$ is $104/27$ .... and the denominator is good !
By the way, the curves are very close if you shift the straight line down to where it has to be.
I am sure that you can take from here.
Comment: Appreciate the help.
Answer: The normalized constant function is $1/\sqrt{3}$ because, when you integrate its square from 1 to 4 you get 1.
Comment: Thank you! I "assumed" without checking that it was 1.


Give an example of a relation R on $A^2$ which is reflexive, symmetric, and not transitive

Question: I am just looking for some clarification on this exercise:
Let $A = \{a,b,c,d\}$. Give an example of a relation $R$ on $A^2$ which is reflexive, symmetric, and not transitive.
I understand that if I was only dealing with $A$ and and not $A^2$ I could give an answer similar to:
$R = \{(a,a),(a,b),(a,d),(b,a),(b,b),(c,c),(d,a),(d,d)\}$
Here $R$ is reflexive, symmetric, and not transitive.
What is confusing me is the fact that we have $A^2$. I am not sure what I am missing here. I am looking through my book to see if I can figure this out, but if someone could help shed some light on this it would be appreciated.
Thanks,
Tony
Comment: @Tony You know that $A^2=\{\underbrace{(a,a)}_{x_1}, \underbrace{(a,b)}_{x_2}, \ldots ,\underbrace{ (d,d)}_{x_{16}}\}$. So renaming the elements of $A^2$ reduces the problem to one you know how to solve.
Comment: @GitGud I have edited the body of the question to reflect the title, which I think is what was intended (not transitive)
Comment: It doesn't matter what $A$ or $A^2$ looks like. The only binary relation on a set which is both reflexive and not reflexive in the empty relation.
Comment: I wonder if the "$A$" vs "$A^2$" confusion is really that the underlying set is $A$, but the relation is ordered pairs, so $R\subset A\times A$? This is the usual way, isn't it?
Comment: Mark, that is correct. thanks for catching my typo.
Comment: @MPW I believe that when one says a relation on $X$ one means a subset of $X^2$. This is the most common.
Comment: @GitGud: Yes, that's what I was trying to convey. I just wondered if the OP slightly misstated the problem in that regard. Thanks.
Comment: @GitGud: I see what you are saying. Once I explain what $A^2$ is equal to I believe I could use a directed graph and the answer I provided in my question to show a relation $R$ on $A^2$ that is reflexive, symmetric, and not transitive. Is this correct?
Comment: @Tony I wouldn't mess with graphs, but it works for you, great. It is correct. It would be good if you posted an answer to the question yourself, so this doesn't come up as unanswered.
Answer: Based on this feed back I believe the answer is:
Let $A = \{a,b,c,d\}$,
$A^2 = A \times A$ = $\{(a,a),(a,b),(a,c),(a,d),(b,a),(b,b),(b,c),(b,d),(c,a),(c,b),(c,c),(c,d),(d,a),(d,b),(d,c),(d,d)\}$
A relation $R$ on $A^2$ which is reflexive, symmetric, and not transitive is:
$R = \{(a,a),(a,b),(a,d),(b,a),(b,b),(c,c),(d,a),(d,d)\}$
R is reflexive because each element is related to itself.
R is symmetric because when one element is related to a second element that second element is related to the first.
R is not transitive because we have $bRa$ and $aRd$ but we do not have $bRd$.


N balls in r urns

Question: Could someone please explain the difference between these two cases:
1. No. Of ways to arrange n distinguishable balls in r urns.
2. No. Of ways to arrange n balls in r urns when the balls are identical.
It would be great if someone could explain them taking specific values of n and r.
Comment: The difference between the two cases... take two balls and two urns.,  the balls are labeled $A$ and $B$, and the urns are represented by brackets and location.,  $[A][B]$ is considered a different outcome than $[B][A]$.  For the balls being identical, these are considered to be the same outcome as they are both $[\star][\star]$.
Comment: @JMoravitz why not post that as an answer?
Comment: @NathanielMayer because someone will inevitably downvote his perfectly fine answer just because the question is ill worded :/
Comment: @Nathaniel really, if anything it was because that would legitimize this as being a good enough question to properly answer, which I don't think it is.
Comment: Missing from the Question is whether the *urns* are distinguishable or not (i.e. identical urns).
Answer: Hint: We should also consider if urns are distinguishable or not. If this is not explicitly stated, we typically assume they are indistinguishable (but should state this assumption in an answer).  Here is an example with $n=3$ balls and $r=4$ urns.

We think of $N=\{1,2,3\}$ as a set of balls and of $R=\{a,b,c,d\}$ as a set of urns. A function $f:N\rightarrow R$ is considered as  placing each ball into some urn.
We consider four functions $j,k,l,m: N\rightarrow R$ by
  \begin{array}{lclcllcl}
j(1)&=&j(2)&=&a,&\qquad j(3)&=&b\\
k(1)&=&k(3)&=&a,&\qquad k(2)&=&b\\
l(1)&=&l(2)&=&b,&\qquad l(3)&=&d\\
m(2)&=&m(3)&=&b,&\qquad m(1)&=&c\\
\end{array}

Four functions with distinguishable balls and urns:

with balls indistinguishable:

with urns indistinguishable:

with balls and urns indistinguishable:

Note: Some more information is given in this answer.
Answer: In the first case, let's make it simple and consider 2 balls and 2 urns. Have the balls be labeled X and Y, respectfully. Since in the first case the balls are not identical, this means that the probability of choosing X is not equal to choosing Y. The these events are not equally probable, no matter in what urns they are pulled from. In the second case, we have balls X and Y, which are identical. This means that the probability of choosing X then Y is the same as choosing Y then X afterwards. The key thing to remember is the word identical.
Answer: Both the balls and the urns are distinguishable
$n=1,r=1$ gives $1!$ ways
$n=2,r=2$ gives $2!$ ways
$n=6,r=10$ you have a choice of selecting 6 urns from 10 and then put the balls in them that gives you $10\choose6$.$6!$
In case of balls being identical you can disting which ball went in to which urn so if $n=6,r=10$
the answer is just $10\choose 6$
Comment: $10$ urns, $6$ balls, all distinguishable, there are $10^{6}$ ways to arrange.  Balls indistinguishable urns distinguishable there are $\binom{15}{5}$ ways.  Balls distinguishable urns indistinguishable there are $\sum\limits_{r=1}^6\left\{\begin{smallmatrix}10\\r\end{smallmatrix}\right\}$ ways... none of which match your given answers.  Remember that multiple balls can go to the same urn, you are not limited to just one ball per urn.

N balls in r urns


Using AngularJS Provider with GET and SET

Question: In my last question I did search a solution to use a value in AngularJS during .config. I learned I have to use a provider. Now I try to set a value using this provider. It seems there is a limitation with providers, I can set something ONLY during .config ? I get the error "TypeError: appState.setState is not a function", but setState is a function, at least for my understanding. I'm wrong?
The code:
angular
    .module('main', [
        'ngRoute'
    ])

    .provider('appState', function(){
        var appState;

        this.setState = function(newState) {
            appState = newState;
        };

        this.getState = function() {
            return appState;
        };

        this.$get = function() {
            return appState;
        };

        function init() {appState='/home';}
        init();

    })
    .config(function($routeProvider, appStateProvider){

        $routeProvider
            .when('/home', {
                templateUrl: "partials/home"
            })
            .when('/info', {
                templateUrl: "partials/info"
            })
            .otherwise({
                redirectTo: appStateProvider.getState()
            })

    })

    .run(function ($rootScope, appState) {

        $rootScope.$on('$routeChangeStart', function (event, next, current) {
            if (next.$$route) {
                appState.setState(next.originalPath);
                // -> ERROR: "TypeError: appState.setState is not a function"
            }
        })

    })

;

Answer: A Provider is like a two-part service, Its minimum form is like a factory:
aModule.provider('foo', function() {
  this.$get = function() {
    return 1;
  }
});

Then you can inject this in any other service, directive, controller and run function:
aModule.controller('BarCtrl', function(foo) { ... });

Notice how I used foo as the name of the provider.
What this does, is inject into the controller what the $get returns. AKA, if you log foo inside the controller you will get 1.
So what's the point of the provider? Being able to configure the service before the app runs.
aModule.provider('foo', function() {
  var appState;

  this.setState = function(newState) {
    appState = newState;
  }

  this.$get = function() {
    return appState;
  }
});

In this case, apart from the $get function, we have some other functions. How can we use them? We need to inject the provider itself and not the factory within. How can we do that?
aModule.config(function(fooProvider) {
  fooProvider.setState('Hello');
}

Notice how I used this time fooProvider instead of just foo. That says that I am injecting the provider itself. That said, the provider can only be injected into .config functions and other provider's constructors.
Now if you log foo in our controller, we see: hello.
I repeat, what you inject in the controller is what the $get returns and not the other methods outside it. That is why you can't use setState on the run, because what you inject there is what $get returns.
Comment: Thanks very much! Written very clearly .. I got it. So I think I can work with this in general. For my specific problem in the meantime I realised, that I cannot use a dynamic parameter within .config. So far I understand .config is loaded once and then "static". But this is another question .. context is node, jade, i18next and angular. So again, thanks for your clear answer!


get all nodes created in a specific month

Question: I have a custom search form that I posts a year + month, such as
2014-04
I would like to get all nodes created that month, when I create the timestmap I use:
"SELECT .......         AND changed >= 'strtotime($date)'"
This is the code for form date:
$form['aqar_date'] = array(
'#type' => 'date_select',
'#title' => t('Date'),
'#prefix' => '

Node date
',
'#suffix' => '
',
'#date_format' => 'Y-m',
'#default_value' => date('Y-m'),
'#date_year_range' => '-4:+0',
);

This is the form submit:
$start_date = strtotime($date);
$query = "
SELECT `nid` FROM `node`
WHERE
`type` = 'custom'
 AND `changed` >= '$start_date'";

But I'm not getting, I need a way to specify to only this month period not this month and newer!
Thanks!
Comment: Welcome to Drupal Answers! May you show the actual code you are using?
Comment: @kiamlaluno yep sure I just did, any thoughts?
Comment: What's in `$date`?
Comment: @Clive it's actually the date submitted by the form, "2014-04" for instance, it is in the format of 'Y-m'
Comment: But how are you setting `$date`? With `$date = $form_state['values']['aqar_date'];` or something else?
Comment: @Clive yes I fill it that way.
Answer: Here you go with the code.. I have used entity field query to retrieve results.. Code should be self explanatory..  Let me know if you have any difficulty in understanding below code..
<?php

$year_month = "2014-04";
$date = date_parse_from_format ("Y-m" ,  $year_month);
$num = cal_days_in_month(CAL_GREGORIAN, $date['month'], $date['year']);
$first_minute = mktime(0, 0, 0, $date['month'], 1, $date['year']);
$last_minute = mktime(23, 59, 59, $date['month'], $num, $date['year']);
$entity_type = 'node';
$efq = new EntityFieldQuery();
$efq->entityCondition('entity_type', $entity_type);
$efq->propertyCondition('created', array($first_minute, $last_minute), 'BETWEEN');
$result = $efq->execute();
dpm($result);

?>

Comment: Thanks that did the job, though it was hard for me to come up with that it looks shorter than I anticipated :)


DELETE FROM table WHERE UID = x AND CAT = y

Question: I have a very simple table - 3 columns  ID | UID | CAT
I am trying to run a mysql delete to remove the rows where both UID= something AND CAT= something.  But it doesn't work.  How do I do this?
$uid = $_POST['UID'];
$cat = $_POST['CAT'];

mysql_query("DELETE FROM Categories WHERE UID = ".$uid." AND CAT=".$cat."");

Comment: Your script is prone to SQL-Injections. Be sure to properly sanitize your parameters. The best way to do this is using PDO or MySQLi and Preparent Statements.
Comment: Is ether or both of the columns (UID , CAT) a VARCHAR/CHAR column?
Comment: Have you checked that there are matching datasets by echoing the built query and PHPMyAdmin or something similar?
Comment: UID is INT and CAT is VARCHAR
Answer: try this:
mysql_query("DELETE FROM Categories WHERE UID = $uid AND CAT='$cat'");

Comment: Since uid is an integer, should it really be put inside ''?
Comment: No, if it is numeric then it doesn't need to be enclosed with quotes
Comment: Maybe you should edit your post then, because OP said column uid is of type integer.
Answer: $uid = $_POST['UID'];
$cat = $_POST['CAT'];

mysql_query("DELETE FROM Categories WHERE UID = ".$uid." AND CAT=".$cat."");

VARCHAR need to be escaped
mysql_query("DELETE FROM Categories WHERE UID = ".$uid." AND CAT='".$cat."'");

another hint use mysql_real_escape_string or another form of checking user input
$uid = mysql_real_escape_string($_POST['UID']);
$cat = mysql_real_escape_string($_POST['CAT']);

Answer: Do you have an active database connection?  If not, you'll need to create one before calling mysql_query().
Other than that, you may be forgetting single quotes in the query:
mysql_query("DELETE FROM Categories WHERE UID = ".$uid." AND CAT=".$cat."");

Should be:
mysql_query("DELETE FROM Categories WHERE UID = ".$uid." AND CAT='".$cat."'");

Assuming CAT is not a numeric column.
Comment: yes I have an a DB connection earlier in the script.  None of the suggestions have worked.  I can do it WHERE UID= but I can't do it when I try to do an AND.  UID is a INT and CAT is a VARCHAR.
Comment: @JamesAckerman: Did you add the single quotes to the query like I suggested?  Does the data in `$cat` also have single quotes in it?  If so, it will break the query.  Also, please note that your query is vulnerable to SQL injection.