What action was Logan Couture referring to when describing Sidney Crosby as cheating on faceoffs?

Question: I am a huge hockey fan but I am not 100% clear on the rules..
This has to do with the 2016 Stanley Cup Playoffs.
So after last night's overtime victory, goal scored by Conor Sheary.. Crosby was called a cheater by the Sharks player LOGAN COUTURE.

In Game 2, Crosby did not score but he did win 17 of 24 faceoffs, including the game's biggest that earned him a secondary assist on the winner. He is 26-for-40 in the faceoff circle through the first two games of the series.
It's an edge that irks some San Jose Sharks.
"He cheats," Couture said. "He gets away with it. He's Sidney Crosby."
How so?
"He times them and they don't kick him out for some reason, probably because of who he is," Couture complained.

This can be found here.
Again, I am not clear with the rules, but when it comes to face-offs, what is the other way to win face-offs besides trying to time when the referee drops the puck onto the ice? Or my comprehension of how Couture used the word timing is wrong.
Any explanation is appreciated.
Answer: This appears to me as Logan Couture trying to cause the officials to keep a closer look on Crosby. Make them pay more attention to Sidney Crosby and possibly get him off the face offs if he twitches just a tiny bit too fast or at least make the officials think he is moving early. If the refs start chasing him, then it can start to mentally affect Crosby.
You can't cheat per say when it comes to face off, if you do cheat, you get sent off and another player takes your spot on the face off. That is... If the referee calls the infraction.
I'm not well versed in the rules of Face Offs, but Crosby is not cheating. If there was a way to cheat this facet of the game, the Team/Player in question would probably get sanctioned by the league.
Comment: Essentially, yes. False starting and not getting a call.
Comment: How would he cheat? Is Couture just saying Crosby is 'false starting' and the refs aren't calling him on it?
Answer: Winning a face-off is to play the puck in the desired direction before the opponent can do so. It's a race to the touch from a stationary start.
Being first over such a short distance with such high speeds means that the first person to go will most likely win. But going early is (hopefully) penalised so just doing it every time will lead to worse outcomes later.
For the player who wants to avoid this, then, there are two choices: being reactive and being proactive. The first is self-explanatory: reacting to the instant of the drop. He who reacts faster, acts faster, and wins.
The proactive player instead tries to predict when the instant of the drop will occur, and time their action accordingly. This eliminates the time needed to react, which as we suggest, is the biggest contributor to the total time, thereby granting a great advantage to the proactive player over the reactive player - assuming the former has practised the prediction and has similar physical speed.
Now, the puck is often not just dropped, but given a bit of additional speed downward by the official. Muscle movements are typically preceded by a tightening which causes some "backswing" of the arm (leg, head, ...). Observing this backswing effect can, with practise, lead to having a reaction time of effectively zero.
Finally: is this cheating? Well, the rule says, in more words, that players can't move until the puck has dropped. But if the player has predicted well, they are only moving exactly when the puck is dropped, and therefore not breaching the rule.
What's really the problem? Crosby has a skill that gives him an obvious advantage. Some players see the use of such skills as invalid, for a number of reasons. To of have a skill is to be a worse player than the opponent, and that's not often an acceptable thought. So, he rationalises: the only way he could be better is by cheating. Regardless of whether or not that is the case!


IIS - Acesso negado a diretório

Question: Estou utilizando windows server 2008 e IIS 6.1, tenho um serviço que precisa acessar arquivos em um determinado diretório, mas não tenho acesso.
O que preciso configurar para obter acesso?

Depois de adicionar Administrator como o usuário, a aplicação diz que o diretório não existe.
    List<FileInfo> files = new List<FileInfo>();

    if (Directory.Exists(@"C:\Users\Administrator\Documents\MovieCollector\PacotesSerializados"))
    {
        foreach (string file in Directory.GetFiles(dataFilePath))
        {
            FileInfo fileInfo = new FileInfo(file);
            files.Add(fileInfo);
        }
    }
    else
    {
        throw new Exception(dataFilePath+ " não lexiste");
    }

    files.Sort((x, y) => y.CreationTime.CompareTo(x.CreationTime));

    if (files.Count == 0)
    {
        throw new Exception("Lista vazia");
    }

Comment: Se você tem algum usuário que tenha acesso a esse diretório, você pode dar permissão ao usuário que executa no IIS. Ou ainda não tenho certeza se é assim que funciona nessa versão do IIS, mas você pode definir o usuário que você quer conectar seu aplicativo no IIS, no IIS8 é a opção "Conectar como...", então ali defina um usuário com os privilégios no diretório em questão. (Talvez seja uma opção similar (Não tenho um IIS 6.1, para testar))
Comment: Adicionei `Administrator` como o usuário, mas diz que o diretório não existe. Adicionei uma imagem que mostra o erro no cliente e o diretório no servidor.
Comment: Qual o código executado para gerar a exceção indicada?
Comment: Adicionado o código utilizado para recuperar os arquivos.
Comment: Já experimentou adicionar o grupo `everyone` com leitura e escrita nesse diretório?
Answer: Italo você já deu permissão total para o usuário IIS_IUSRS na pasta PacotesSerializados. Veja também se existe o Tipo de MIME .xml ou extensão utilizada no IIS.

IIS - Acesso negado a diretório


Operations on Random Variables vs Distributions vs Random Samples

Question: What is the difference between i) random variables, ii) distributions of random variables, and iii) random samples?
While trying to figure out how to average random samples from various random variables I learned that the operations summation for random variables and distributions of random variables are different. I would like to make sure I have these terms straight and I would like to make sure the operations are valid for each term.

Random variables: I think of these, non-formally, as functions. They are functions that can generate infinitely long vectors of numbers. In R, I think of random variables as rnorm or rexp. Random variables are functions that spit out numbers as defined by their distribution.

Distributions of Random Variables: In text books these are functions (PDFs). In R these would be dnorm and dexp. An example realization of a continuous distribution on a grid of evenly spaced values would be a two column set of data where one column represents an input value and the other column represents an output frequency of the associated value.

Random Samples: This is a vector of values output from a random variable. For example, if rnorm(n=10, 5, 1) is the random variable then the resulting vector of data is a random sample. In other words, the 10 random numbers generated from the function are the random samples. This is in contrast to random variables and distributions of random variables which are represented as functions. I do not believe that random samples must be generated from a named probability distribution. They can just be a random heap of numbers.

Operations
Random Variables

For Random Variables there is a wikipedia page Algebra Of Random Variables.
Considering two random variables X and Y, the following algebraic operations are possible:

Addition: $Z=X+Y=Y+X$
Subtraction: $Z=X-Y=-Y+X$
Multiplication: $Z=XY=YX$
Division (mathematics)|Division: $Z=X / Y=X \cdot (1/Y)=(1/Y) \cdot X$
Exponentiation: $Z=X^Y=e^{Y\ln(X)}$

This notation does not seem useful. This is because I know that to sum two normals I would not just add realizations like the notations seem to indicate.
For example, to obtain a random variable $C = \frac{(A+B)}{2}$ where the random variable $A$ is :$f_A(x) = \int_{y=\infty}^{x} N(y\mid 10, 5) \, dy$ and the random variable B is:$
f_B(x) = \int_{y=\infty}^{x} N(y\mid 20, 5) \, dy$. The notation does not let the user know how to treat the parameters $\mu$ or $\sigma$ in $N(y \mid \mu, \sigma)$. It turns out that the $\mu_C$ is the average of $\mu_A$ and $\mu_C$ while the $\sigma_{C}$ is $\sigma_A$ divided by $\sqrt{2}$. The resulting random variable $C$ is $f_C(x) = \int_{y=\infty}^{x} N(y\mid 15,\frac{5}{\sqrt{2}}) \, dy$. I would not say the operations on the wikipedia page were useful to help determine the resulting random variable $C$.
So it seems that the proper, technical, way to interact with random variables is to interact with them on the distribution level as shown the in next section.
Distributions of Random Variables (PDFs or PMFs)

Given that there exists some density it is possible to use Convolutions to sum the random variables. There is a list of convolutions of probability distributions.
From Why is the sum of two random variables a convolution? the accepted answer states that how one sums random variables depends on how the random variables are represented.

In terms of probability mass functions
(pmf) or probability density
functions
(pdf), it is the operation of
convolution.

In terms of moment generating functions
(mgf), it is the (elementwise) product.

In terms of (cumulative) distribution functions
(cdf), it is an operation closely related to the convolution.  (See
the references.)

In terms of characteristic functions
(cf) it is the (elementwise) product.

In terms of cumulant generating functions (cgf) it is the
sum.

The first two of these are special insofar as the box might not have a
pmf, pdf, or mgf, but it always has a cdf, cf, and cgf.

Because it is rare for me to have a need to operate on named random variables I do not tend to have a need for these operations.
What I do have a need to interact with often is random samples or realizations of random variables.
Random Samples

I do not know how to perform operations such as summation, averaging, etc. on random samples.
Example 1
Consider random sample $\textbf{a}$ and $\textbf{b}$. The data points in these random samples are $a = [1,10,100]$ and $b = [100, 10, 1]$ there are a number of ways to sum.
The way np.sum() treats the problem is that it will match the index in the summation. a[0] + b[0] then a[1] + b[1] then a[2] + b[2],$a_i + b_i$, but this misses on the tails for example a[2] + b[0] = 200. The cartesian product would capture the full width of the final distribution.
I thought of a couple ways to go about this:

The Cartesian product
The bootstrap approximation

The Cartesian product gets computationally harder for larger $n$ it also can't accept different mapping structures like covariance or past errors.
As far as I know there is not a lot of guidance on working with random samples.
The Cartesian product and the bootstrap approximation was something I thought of on the fly. Does something more rigorous exist? I am basically looking for a reference for operations on random samples.
Summary of my questions

Am I grasping the terms i) random variables, ii) distributions of random variables, and iii) random samples properly?
Am I grasping operations on i) random variables, ii) distributions of random variables properly?
How can I perform operations such as adding, averaging, etc. on random samples? To the best of my knowledge the Cartesian product and bootstrap approximations may be possible ways to go about summing and averaging many independent random samples.
Answer: Random variables and their distributions cannot be considered separately. One defines another. To find the distribution of the function of random variables (e.g. algebraic operations) you require convolutions, as you described in your second section on the distributions.
How are the algebraic operations on random variables themselves useful? This is explained in the very first sentence of the Wikipedia article

The algebra of random variables in statistics, provides rules for the symbolic manipulation of random variables, while avoiding delving too deeply into the mathematically sophisticated ideas of probability theory. [...]

So you can do the algebraic operations on a symbolic level without bothering about the "implementation details" while having guarantees that it works as you would expect.
As for random samples, what you are describing is not correct. To find the distribution of an operation on random variables, e.g. sum, you would need to consider their joint distribution. If you used a cartesian product, you would assume that each combination of the values has equal probability. Bootstrap approximation of the distribution using the three samples you mentioned would just give you probabilities for the values $\Pr(a + b = 101) = 2/3$ and $\Pr(a + b = 20) = 1/3$, that is not the "full width" of the distribution because you would just be randomly sampling the $(a_i, b_i)$ pairs. If you meant randomly permuting the combinations, again you would be assuming that the probabilities of each combination are equally likely.
Consider the simple joint distribution
$$\begin{align}
\Pr(a=0, b=0) &= 0.2 \\
\Pr(a=0, b=1) &= 0.5 \\
\Pr(a=1, b=0) &= 0.3 \\
\Pr(a=1, b=1) &= 0 \\
\end{align}$$
In such a case you cannot claim that $\Pr(a+b = 2) > 0$, as using the proposed cartesian product approach or using random permutations, would.
With random samples, you cannot directly get the "full width" of the distribution. Depending on the problem, you could approximate the distribution of the function of the samples using some statistical model. Your example considers only three samples with two unique values for the sum, so there is not much room to build any reasonable statistical model using such data.
If you had enough data, their empirical distribution approximates the true distribution. In such a case, the distribution of the empirical results of evaluating some function over the samples would approximate the distribution of the function of the random variable. But you cannot easily go out-of-sample as you suggested.
Comment: Your initial statement has it backwards: *distributions* are defined in terms of random variables, not the other way around.  Algebraic operations on random variables are identical to operations on any function.  Ordinarily they would *not* use convolutions, which are operations on distribution functions.  See https://stats.stackexchange.com/a/392506/919 for a full discussion.
Comment: @Alex they are useful. If you have enough data, their empirical distribution approximates the true distribution. In such a case, the distribution of the empirical results of evaluating some function over the samples would approximate the distribution of the function of the random variable. But you cannot easily go out-of-sample as you suggested.
Comment: @whuber I fixed the wording.
Comment: In an attempt to restate what you are saying, random samples (even if you have 100s of them) are not something that is possible to operate on. This would include two posterior samples from to separate Bayesian models, random numbers, draws from `rnorm()`. If you make no assumptions about the distribution of the random variables then there is no way to say anything about the "full width" of their sums or averages. I think that makes sense. For some reason I thought random samples were more useful.
Comment: @Tim Thanks. I just want to make sure I understand what you are saying. Say I have a few sets of random samples each with 1000 data points -- they seem to converge well. If I wanted to sum or average those random samples it is not possible. I have to define a named distribution. This is easier with more samples, but more samples does not allow one to side step the fact that a distribution is neccesary. Is that what you are saying? No matter what I need a distributional fit of some sort, something like a lognormal, Weibull , Negative Binomial, Pearson, etc.
Comment: Your second statement, "Algebraic operations on the random variables would use convolutions," is still misleading.  The natural algebraic operations are the ones induced  by the arithmetic operations on the ranges of the variables: namely, the real numbers.  Some of these are enumerated in the question.  Because the OP is doubtful about their "usefulness," don't you think it would be better to be perfectly clear about this algebra as well as its utility?
Answer: In questions like these it is best to keep everything as elementary as possible. We will assume that everything is finite, if you are not sure what I mean by that, then the examples will illustrate.

Let us first begin by defining a "random experiment". This is any experiment whose outcome cannot be determined until it is done. For example, if you have a coin and you measure how long it takes for the coin to fall and reach the floor from 1 meter height, then the answer will (roughly) by always the same no matter how many times you do it. There are deterministic laws which tell us exactly what will happen and we can predict ahead of time of what will happen. An experiment is "random" if its outcome cannot be predicted in any consistent manner. Going back to the coin, if instead we wish to determine whether the coin lands head/tails, then that cannot be predicted at all. Hence we call it "random".
We define the "sample space", commonly denoted as $\Omega$, to be the set of all possible outcomes that can occur under some random experiment. For example, if we have two coins, a quarter and a dime, then we have 4 outcomes that can happen, $hH$, $hT$, $tH$, $tT$, where the little letter is for the dime and the big letter is for the quarter, i.e. $hT$ represents that the dime lands on heads and the quarter lands on tails. Therefore, $\Omega = \{ hH, hT, tH, tT\}$. This is our "sample space" of the random experiment, anything that can happen is contained in that universe of possibilities.

Now let us define a ``random variable''. A random variable, let us denote it as $X$, is a mapping which assigns a numerical quantity for each sample point in $\Omega$. If $\omega\in \Omega$ then $X(\omega)$ is the assigned value to that sample point $\omega$. For example, let us go back to our dime/quarter sample space. A simple example of a random variable $X$ on that sample space is simply the monetary value (in cents) of that outcome of heads only. So, for instance, $X(hT) = 10$ and $X(hH) = 35$, ect.
The purpose of a "random variable" is to quantify the sample space. As we can see in our example, $\Omega$ is not a set of numbers, it is just a set of symbolics, a random variable simply assigns numerical values to each of those.

Now observe something very important. If you were to do the random experiment, over and over and over again, many many times, the value of $X$ (the random variable) will be ``random''. It will be unpredictable. This is what we call "random samples" from $X$. It is a list of random outcomes that the random variable $X$ produced. For example, here is a list of random samples:
$$ 0, 10, 25, 0, 25, 25, 35, 10 $$
What this means is that on the first random experiment the value of $X$ was 0 cents. On the second time you did the experiment it was 10 cents, ect.

Finally let us get to what is known as the "distribution" of $X$. This is were probability comes in. It would be inappropriate to ask "what is $X$ equal to?", since that cannot be predicted. Instead, we can ask, "what is the probability that $X$ is equal to $0$ cents?". Then we see that this outcome, of zero cents, only happens at the sample point $tT$, so $P(X = 0) = \tfrac{1}{4}$.
The way we find the distribution is that we first determine what is the set of all possible outcomes of $X$ (sorta like, a sample space for $X$ values) and we see that  this is equal to $\{0, 10, 25, 35\}$. We call that the "support" of $X$. We use the notation, $\text{supp}(X) = \{0,10,25,35\}$. Next we determine the probability that our random variable $X$ will be equal to any one of those four, in our simple example, $P(X = n) = \tfrac{1}{4}$ if $n \in \text{supp}(X)$ and $P(X=n) = 0$ if $n\not \in \text{supp}(X)$. The "distribution" of $X$ is a function (not a random variable!), let us denote it as $f_X(\cdot)$, which is defined as,
$$ f_X(n) = \left\{ \begin{array}{ccc} 0.25 & \text{ if } & n = 0,10,25,35 \\ 0 & \text{ if } & \text{otherwise} \end{array} \right. $$
The purpose of the distribution $f_X(\cdot)$ is that is computes the probabilities associated with the behavior of the random variable $X$.


Como trazer somente resultados dos últimos 30 minutos

Question: Tenho uma tabela no sqlserver que serão registrados logs de erros no qual contem os seguintes campos:
sequência \ data \ mensagem
Gostaria de saber como faço para pegar os resultados dos últimos 30 minutos de acordo com a data atual que rodar o job exemplo:
data: 08/10/2014 10:00
10:08/2014 09:30
Supondo que o job rodará às 10:30 ele deverá trazer somente o erro ocorrido às 10:00
Como posso montar uma query para obter esse resultado.
Observação: já consegui montar o código que colocará esse registro em uma tabela só preciso mesmo extrair os registros dos últimos 30 minutos a cada vez que for executado.
Comment: use functions como DATEADD E GETDATE  http://technet.microsoft.com/en-us/library/aa258863%28v=sql.80%29.aspx
Comment: Muito obrigado Motta, perfeita a sua explicação e solução.
Comment: Não, o Omni que deu a solução eu só indiquei a fonte.
Comment: @Motta colocamos ao mesmo tempo. Vou editar a resposta e colocar o teu link para quem quiser aprofundar o conhecimento sobre essas funções.
Answer: Utilizando DATEADD():
select dateadd(minute, -30, getdate())

Logo no seu caso a sua query ficara algo como:
select *
from tabela
where data >= dateadd(minute, -30, getdate())

Exemplo no SQLFiddle
EDIT:
Mais informações sobre as funções que lidam com datas e tempo em T-SQL aqui.
(Obrigado Motta pelo link).


Particle filter: Evaluating Optimal importance density

Question: NOTE I posted this in the math stack exchange but I realized this may be the more appropriate place, old post here. I'm not sure if I should delete one of them so I just linked them in both?
I am reading about particle filtering and I am having a hard time understanding the importance density step. I understand the necessity but can't quite understand the optimal proposal density, I'll introduce an example below. The math regarding the proposal density stuff comes from Beyond the Kalman Filter: Particle Filters for Tracking Applications
Assuming a state space model
$$
x_{k+1} = f(x_{k}, u_k, w_k)
$$
$$
y_k = H x_k + v_k
$$
where the measurement function is assumed linear and Gaussian and the state transition is not necessarily linear nor Gaussian. In this case the optimal proposal density $q(x_k|x_{k-1}^i,z_k)=p(x_k|x_{k-1},z_k)$ is possible. With this the weight update becomes
$$
w_k^i \propto w_{k-1}^i p(z_k|x_{k-1}^i)
$$
I am not sure how to evaluate this.
I would imagine that it would look like this in a pseudo-code example
<code>initialize pf
for i=1:num_time
    % measurement update
    residual = meas-H*particles
    w = normpdf(residual, 0, meas_noise) % multivariate gaussian, 0 mean and meas_noise covariance
    w = w/sum(w)

    % importance sampling
    if (1/sum(w^2)<0.5*num_particles)
        resample

    % sample from transitional
    particles = state_trans_fcn(particles, input)
</code>
Because as far as I understand sampling from the transitional prior $x^i_k \sim p(x_k|x_{k-1})$ is just applying the mapping $f$ to the particle cloud. Calculating the measurement likelihood $p(z_k|x_{k-1}^i)$ is what really confuses me, because the calculation in the pseudo-code to me feels more like the calculation of $p(x_k|z_k)$?
Comment: Please remove one of the two questions, more likely the one on math exchange.
Comment: Okay I'll remove that one.
Answer: You're mistaken about a few things (and that's okay!).

In this case the optimal proposal density...is [available].

I believe this is only true if $f$, the state transition is Gaussian. It can be nonlinear, which precludes closed-form Kalman filtering, but it must be Gaussian to exploit Gaussian-Gaussian conjugacy. In this case, the proposal
$$
p(x_k|x_{k-1},z_k) \propto f(x_k \mid x_{k-1})p(z_k \mid x_k) .
$$
You can derive that this is Gaussian using standard Bayesian techniques related to identifying conjugate distributions. In this case, the multiplicative adjustment to the weights are not even functions of the current samples you're simulating because there will be significant cancellations in the numerator and the denominator of the importance weight adjustment.

Because as far as I understand sampling from the transitional prior...

You aren't sampling from the state transition prior. That algorithm would be called the bootstrap filter. There, the importance weight updates would be functions of your current samples, and so they would end up having higher variance. The upside to this algorithm is that the weight updates would only require that you can evaluate the observation density. This would be handy for when you cannot evaluate the state transition density (but you can sample from it). Different algorithm, though.

Calculating the measurement likelihood $p(z_k \mid x_{k-1})$ is what
  really confuses me

That is not the measurement density! You are conditioning on the previous time's state, not the current state! This is only evaluate-able if you derive it by solving the following integral:
$$
p(z_k \mid x_{k-1}) = \int \underbrace{p(z_k \mid x_{k})}_{\text{observation density}} \underbrace{f(x_k \mid x_{k-1})}_{\text{state transition}} dx_k.
$$
By the way, this example is discussed in Inference in Hidden Markov Models on page 220/221.
Comment: Regarding your first comment, yes that's correct. If you're proposal is the same distribution as he state transition, then you only need to evaluate the normal observation density on each sample. Regarding your second, yes, that's a typo. Thank you. It's now corrected :)
Comment: I am confused about your explanation regarding the transitional prior. The reason I suggested was because the book Beyond the Kalman Filter: Particle Filters for Tracking Applications introduces it as the most common suboptimal proposal density.

For argument sake, if we assume that the process noise cannot be assumed to be Gaussian this would be a potential candidate for the proposal distribution. This would lead to the weight update equation: $w_k^i \propto w_{k-1}^i p(z_k|x_k^i)$.
Comment: So in short I am still kind of uncertain how to evaluate each of the two weight updates. It looks as though $p(z_k|x_{k-1}^i) = \int p(z_k|x_{k}^i) f(x_k|x_{k-1}^i)$ (I think you made a typo?).

Does this then mean that evaluating the measurement with respect to the particles, `normpdf(meas-particles,0,meas_noise)`, on a multivariate Gaussian, like in the pseudo-code, is how one would calculate $p(z_k|x_k^i)$?
Comment: I can't edit my previous comment, but to keep things are clear as possible I should have wrote `normpdf(particles,meas,meas_noise)` to clarify that the $\mu=\text{meas}$ and $\Sigma=\text{meas_noise}$ when evaluating the multivariate normal as [here](https://i.ytimg.com/vi/eho8xH3E6mE/hqdefault.jpg).
Comment: If using the transitional prior as proposal density could one still call it an SIS PF, or is it most accurately then referred to as boostrap? Also assuming Gaussian measurement with noise $R$, is $p(z_k|x_k^i) = normpdf(x_k^i, z_k, R)$ true?
Comment: This sounds like a separate question. I think it'd be easier to answer this in a separate thread, so we don't pack the comment section full of stuff. But I wouldn't call it SIS particle filtering because it doesn't have resampling. To answe your other question, that depends on what the function signature is, but probably no because you're forgetting H
Comment: The pseudo code still technically has resampling? I formatted the rest into a different question following your advice, [link](https://stats.stackexchange.com/questions/443236/calculating-the-observation-density).


Existence of tree for a given degree sequence.

Question: Let $(d_1,..., d_n)$ be a sequence of positive integers with $\sum_{i=1}^n d_i=2(n-1)$. Then there exists a tree $T$ with vertex set $v_1,..., v_n$ and $d(v_i)= d_i ,
1\leq i \leq n$.
My attempt:- For $n=1$ result is vaccously true.
Assume result true for $n=k$, that is Let $(d_1,..., d_k)$ be a sequence of positive integers with $\sum_{i=1}^k d_i=2(k-1)$. Then there exists a tree $T$ with vertex set $v_1,..., v_k$ and $d(v_i)= d_i ,
1\leq i \leq k$.
 we want to prove the result for $n=k+1$,  Let $(d_1,..., d_{k+1})$ be a sequence of positive integers with $\sum_{i=1}^{k+1} d_i=2(k-1)+2=\sum_{i=1}^k d_i+2$. So, $d_{k+1}=2$
Let $(d_1,..., d_k)$ be a sequence of positive integers with $\sum_{i=1}^k d_i=2(k-1)$. Then there exists a tree $T$ with vertex set $v_1,..., v_k$ and $d(v_i)= d_i ,
1\leq i \leq k$.
Let $T$ be the required tree. If we add a vertex then degee must be equalls to two. Since $T$ is a tree the it must have atleast two pendant vertices. choose one of the pendant vertex, $x$(say). If we add a verex here and attach an edge to $x$ degree of $x$ changes to two. interchange the adding vertex and pendant vertex. we get the desired tree. Is my arguments correct?
Comment: You cannot do that induction step. For instance, if $n = 4$, there is a sequence $(1,1,1,3)$ which does not contain $2$.
Answer: Even better, this is an if and only if statement.
Let $v_1,...,v_n$ be positive integers with $n\geq 2$.
Proof: ($\Rightarrow$)  Assume that there exists a tree $T$ with degree sequence $v_1,...,v_n$. Since $T$ is a graph, we use the Degree-Sum Formula to have $\sum_{i=1}^n(d_i)=2e(T)$.
Since $T$ is a tree, we know that there are $n-1$ edges in $T$.
Hence, $\sum_{i=1}^n(d_i)=2(n-1)$.
Thus, if $T$ has a degree sequence of $v_1,...,v_n$, then $\sum_{i=1}^n(d_i)=2n-2$.
($\Leftarrow$) Assume that $\sum d_i=2n-2$. We show by induction on $n$ that there exists a tree with vertex degrees $v_1,...,v_n$.
Basis Step: $n=2$. $\sum d_i=2(2)-2=2$. Since $n=2$, there exist two positive integers, neither of which can be greater than $2$, as then adding the two numbers together would be greater than $2$. Since $0<d_1<2$, and $0<d_2<2$, and both are integers, it must be the case that $d_1=1$, and $d_2=1$. Consider these two numbers as vertices with degree $1$, hence they are adjacent to each other. This creates the path $P_2$, and therefore exists a tree.
Induction Step: $n>2$. We assume that the claim holds for $n-1$ positive integers $v_1,...,v_{n-1}$. Let $G$ be an arbitrary graph with $n$ vertices such that the degree sequence of $G$ is $v_1,...,v_n$. We know that such a graph $G$ exists as the sum of the degree sequence is even. In addition, it must be the case that there exists at least one vertex $v$ with $d(v)=1$. To show this, suppose on the contrary that $d(i)\geq 2$ for all $i\in [n]$. Thus, the sum of degrees $$\sum\limits_{i=1}^nd(i)\geq 2n>2n-2$$ which is a contradiction. Consider the subgraph $G-v$. By deleting such a vertex of degree one, we delete one edge from $G$. This means that the resulting graph $G-v$ has $n-1$ vertices and the sum of degrees is $2n-4=2(n-1)-2$. Thus, it is possible that $G-v$ is constructed in such a way that it is a tree. Hence, adding the leaf $v$ back to $G-v$ when $G-v$ is constructed as a tree, results in $G$ being a tree. Thus, if $\sum d_i=2n-2$, there exists a tree with vertex degrees $v_1,...,v_n$.
Therefore, there exists a tree $T$ with vertex degrees $v_1,...,v_n$ if and only if $\sum d_i=2n-2$.
Answer: No, you cannot assume that $\sum_{i=1}^k d_i=2(k-1)$ in the induction step, so the argument that $d_{k+1} = 2$ is invalid.


Visual Studio intellisense not working with DHTMLX suite 5

Question: Since I updated my DHTMLX Suite to version 5.0 I don't get intellisense suggestions when typing dhtmlx functions in Visual studio Community 2015 version 14.0.24720.00 update 1.
The functions all work but I have to type them manually and I don't get any feedback on function parameter etc. All non-dhtmlx related functions work as normal with intellisense.
I use my DHTMLX Suite in a MVC project, the dhtmlx.js file is located under "~/codebase/" and the View using the js is located under ~/Views/Home/Index
I use a custom Layout with  in it's header. The View runs the scipts inside  tags.
Intellisense did work with DHTMLX Suite 4.6 but not with DHTMLX Suite 5.0. Am I missing something?
Answer: I found the answer to be similar to the accepted answer in this question.
Adding the dhtmlx.js as a reference to current group did the trick. To add the reference, select

Tools > Options

Under

Text Editor > JavaScript > IntelliSense > References

Find the dhtmlx.js file and write the file path to Add a reference to current group and press Add.


Show a statistic is not sufficient

Question: Let $T$ be a sufficient statistic. Suppose $f(T)$ is not a one-to-one function of $T$.
Show $f(T)$ is not a sufficient statistic.
I think this should be proved by contradiction. Since $f$ is not one-to-one, $\exists t_1 \ne t_2 \ni g(t_1)=g(t_2)$. I sough a contradiction in the factorization theorem by writing $f_\theta(x)=h(x)g_\theta(f^{-1}\circ f(T(X)))$. But, I didn't succeed. I tried from the definition of a sufficient statistic, but I don't see a way there too.
I think, the proof can be done without specifying a distribution for the sample. If that's not the case, we may assume, the sample comes from a $\operatorname{Bernouilli}(\theta)$.
Comment: The intuition is that if $\mathbb P(X \mid T,\theta) = \mathbb P(X \mid T)$, then $\mathbb P(X \mid f(T),\theta) \neq \mathbb P(X \mid f(T))$ because you've lost information since $f$ is not injective.
Answer: The statement as it stands is not true.
If, as you request, we look at the sample $\mathbf{X} =(X_1, X_2,\ldots, X_n)$ representing $n$ i.i.d. $\operatorname{Bernouilli}(\theta)$ random variables taking the values $0$ or $1$, then $\mathbf{X}$ is a sufficient statistic for itself in the sense that $$\Pr(\mathbf{X}=\mathbf{x}\mid \mathbf{X}=\mathbf{x},\theta)=\Pr(\mathbf{X}=\mathbf{x}\mid\mathbf{X}=\mathbf{x})=1$$
but letting $f(\mathbf{x}) = \sum x_i$, then $f(\mathbf{X})$ is also a sufficient statistic for $\mathbf{X}$ as $$\Pr(\mathbf{X}=\mathbf{x}\mid f(\mathbf{X})=f(\mathbf{x}),\theta)=\Pr(\mathbf{X}=\mathbf{x}\mid f(\mathbf{X})=f(\mathbf{x}))=\frac{1}{n \choose f(\mathbf{x})}.$$
Clearly if $f(\mathbf{X})$ is not always either $0$ or $n$, then $f$ is not injective, i.e. is not a one-to-one function.
Perhaps the statement should have been

Let T be a minimal sufficient statistic. Suppose f(T) is not a one-to-one function of T. Show f(T) is not a sufficient statistic.
Comment: @NicolasEssis-Breton: I wouldn't call the statement of the question ill-posed. I'd just call it *false*. :) (+1 Henry for the nice answer).
Comment: You have a very good point Henry. I picked this question during a class as is. I'm surprised it's ill-posed. I think your amended statement is the right one. But, I will not correct my question. Your answer made me learn a lot. Maybe it will benefits others. Thanks.

Show a statistic is not sufficient


What is wrong with the limits of this triple integral?

Question: I need to integrate using cilindrical coordinates some function on the region $E$ under the paraboloid $z = 4 - x^2 - y^2$ and the first octant, so I say $$E = \{ (r, \theta, z): 0 \leq r \leq 4 - z, 0 \leq \theta \leq \frac{\pi}{2}, 0 \leq z \leq 4  \}.$$ But I integrate and my answer is not the one provided in the book. I checked the integral with Wolfram Alpha and the my result is correct, so I have to have something wrong in the way I determined $E,$ but have no Idea what could be. Can someone help me?
Comment: We can't actually help you until you tell us what the answer in your book is and what is the integral you set up.
Comment: How did you come up with the bounds on $r$? The upper one is not correct. In fact, it might be simpler if you integrate with respect to $z$ on the inside instead of $r$.
Comment: Guys, the OP *did* state his region of integration: "under the paraboloid $z=4-x^2-y^2$ in the first octant".
Answer: Your relation: $r=4-z$ is incorrect. If $z=4-x^2-y^2$, then $z=4-r^2$ so that $r^2=4-z$ and thus $r=\sqrt{4-z}$.
Anyway, it is usually better (and easier) to set up the bounds beginning with $z$ instead of $r$. So you know that the "bottom" of your region is determined by the $xy$-plane (i.e. $z=0$) and the "top" is determined by $z=4-x^2-y^2=4-r^2$. Thus your $z$-bounds are $z=0$ and $z=4-r^2$.
Next, intersect the top and bottom to find bounds for $r$: $0=z=4-r^2$ implies $r=2$. So $0 \leq r \leq 2$ and then you've got the angles right (since you're operating in the first octant  - containing to the first quadrant of the $xy$-plane.
So your bounds are: $0 \leq z \leq 4-r^2$, $0 \leq r \leq 2$, and $0 \leq \theta \leq \pi/2$. You were close. :)


joining on another table causes sum to be greater

Question: when i join two tables together and get the sum, i am getting the correct figure:
select
    d.accn_id,
    cast(d.load_date as DATE) as LoadDate,
    cast (d.final_rpt_date as DATE) as FinalReportDate,
    sum(p.paid_amt) as SumPaidAmt

from
    accn_demographics d
join
    accn_payments p
on
    d.ACCN_ID=p.ACCN_ID
where
    p.POSTED='y'
    and p.PMT_DATE between '20120501' and '20120531'

group by
    d.accn_id,
    d.load_date,
    d.final_rpt_date

however after i join ANOTHER table accn_payors:
select
    d.accn_id,
    cast(d.load_date as DATE) as LoadDate,
    cast (d.final_rpt_date as DATE) as FinalReportDate,
    sum(p.paid_amt) as SumPaidAmt
    ,payors.PAYOR_ID
from
    accn_demographics d
join
    accn_payments p
on
    d.ACCN_ID=p.ACCN_ID
left join
    accn_payors payors
on
    payors.X_PAYOR_ID=p.X_PRICED_PAYOR_ID
    and payors.ACCN_ID = p.ACCN_ID
where
    p.POSTED='y'
    and p.PMT_DATE between '20120501' and '20120531'

group by
    d.accn_id,
    d.load_date,
    d.final_rpt_date
    ,payors.PAYOR_ID

i am getting an overstatement of sum(p.paid_amt)
the question is how can i adjust my join so that i am not joining multiple times?
Comment: Well, the problem is that your join is returning multiple rows from payor for rows in accn_payments.  Can a payment have more than one payor?
Comment: jim, yes i guess, it can, how can i just grab the first one?
Answer: This might work, but I don't know what would determine which payor_id you would want to get, so min() may not be the right function for you, maybe max() would?
SELECT *

FROM (

select
    d.accn_id,
    cast(d.load_date as DATE) as LoadDate,
    cast (d.final_rpt_date as DATE) as FinalReportDate,
    sum(p.paid_amt) as SumPaidAmt,
    min(p.X_PRICED_PAYOR_ID)

from
    accn_demographics d
join
    accn_payments p
on
    d.ACCN_ID=p.ACCN_ID
where
    p.POSTED='y'
    and p.PMT_DATE between '20120501' and '20120531'

group by
    d.accn_id,
    d.load_date,
    d.final_rpt_date
) payments
LEFT JOIN accn_payors payors
on
    payors.X_PAYOR_ID=payments.X_PRICED_PAYOR_ID
    and payors.ACCN_ID = payments.ACCN_ID

Answer: Instead of joining on accn_payors, you need to join on a SELECT statement that returns one row per accn_id. Depending on your requirements, this might work.
select accn_id, min(x_payor_id) x_payor_id
from payors
group by accn_id

Aliasing min(x_payor_id) with the same name lets the rest of the code work without modification. That might or might not be a good idea. It's a little misleading.
So instead of this . . .
left join
    accn_payors payors
on
    payors.X_PAYOR_ID=p.X_PRICED_PAYOR_ID
    and payors.ACCN_ID = p.ACCN_ID

you'd do this . . .
left join
    (select accn_id, min(x_payor_id)
     from payors
     group by accn_id) payors
on
    payors.x_payor_id = p.x_priced_payor_id
    and payors.accn_id = p.accn_id


How to do "metal" harmonics (pinch etc)

Question: I've always struggled with this, tried watching Youtube tutorials, but can't get it to work.
Should you hold the pick in any particular way? I've always held my picks with three fingers, for stability, but have a feeling that won't work here.
Does it work for all notes? As I understood it you have to hit the string at some particular points, but can I use it for all notes?
Thanks! Final question: How did you learn it?
Comment: Gibbons is famous for using custom-made extremely light-gauge strings (.008s or .007s I believe), a lot of amp gain to compensate for the lack of output from his very thin strings, and using a Mexican peso coin or an American quarter as a pick. This must mean that he picks and strums with an *extremely* light touch, and that harmonics squeal out of his playing very readily because of the heavy gain boost.
Comment: I always hated the term "pinch" because you are really dampening it slightly, not actually pinching it with your fingers.
Answer: (Just in case of any confusion, this answer was originally in response to a duplicate question about pinch harmonics used by Billy Gibbons of ZZTop - thanks for the merge, Dr Mayhem!)
These are probably pinch harmonics. In which case, they are not produced by a particular amp or effects setting, but are produced by the picking hand while playing (although they are much easier to produce when using a lot of overdrive/distortion).
Pinch harmonics are produced by creating a node with the picking hand as it picks, rather than creating a node above one of the frets (eg. 12, 9, 7, 5) with the fretting hand, which are natural harmonics. (See the end of this post, for an explanation of what nodes are and how to find and create them.) There are several ways to do this. Most players do pinch harmonics using the thumb of the picking hand; I touch lightly with the nail of my ring finger (3rd) on my picking hand. Either way, the thumb or finger should touch at exactly the same time as the pick and then move away from the string at the same time as the pick. You will need to experiment with moving your pick position along the string, to find different node positions for different pitches (and, of course, these change, depending upon which fret your L.H. is fretting).
Like many players, I suspect, I first "discovered" pinch harmonics by accident (usually while using distortion). With a bit of practice, though, it becomes easy to create pinch harmonics for any fretted note. I must confess, I take a rather "non-scientific" approach to pinch harmonics, being able to find them somewhat intuitively. However, there are plenty of guitarists who know exactly where to create the R.H. node to create exactly the harmonics they want for any particular fretted note.
Another term for harmonics created when playing fretted notes is artificial harmonics. In particular, this term is used when playing classical guitar. Obviously, no pick is used for classical guitar, so the method of production is different. The node is created by the R.H. index finger; the string is then usually played with the R.H. ring finger. (Although, this may need to be different if playing chords containing an artificial harmonic.) When producing these kind of artificial harmonics on classical guitar a hit-and-miss approach is not useful; the R.H. index finger needs to be placed exactly at the node point on the string (usually half the length of the fretted string, to produce a harmonic an octave higher than the fretted note, although other harmonics can be effectively produced too). The lack of distortion and volume when playing classical guitar means that only "exact" harmonics sound effectively, whereas, with plenty of volume and distortion, pinch harmonics can almost be produced accidentally as a kind of "effect" when playing electric guitar.
ADDITIONAL INFO: What are nodes? How do I find and create them, to produce harmonics?
As requested, here is some additional info about finding node points on strings to create harmonics.
Node points for harmonics can be found at points along a string by dividing the total length by an integer (whole number) value. For instance, there is a node point at 1/2 way along the string (in other words, it is found by dividing the total length by 2). Dividing the total string length by 3 gives two node points, producing the same harmonic; one is a 1/3 of the string length from the nut, the other is a 1/3 of the string length from the bridge.
If a vibrating string is touched at a node point (while or after it is plucked) the string vibrates "in sections", with the node point (and other equal node points) being still. This creates a harmonic, a higher pitched overtone, present in the open or fretted pitch (the fundamental frequency).
The pitch of the harmonic is directly related to the integer value of the string division. For instance, playing the harmonic with a node at the halfway point along the string doubles the frequency, which makes it an octave higher. If the node point is found by dividing the string length by 3, the frequency is 3 times the fundamental frequency, which makes it an octave and a fifth higher. The wikipedia article here gives a good, detailed explanation (and illustration) of how strings vibrate when touched at these different node points, and how this affects the frequency of the harmonics produced.
How does this relate to playing pinch/artificial harmonics on guitar?
When playing an artificial or pinch harmonic, the node points are now a division of the fretted length of the string; in other words, the distance between the bridge and the fret being pressed with the fretting hand.
If using the R.H. thumb to play pinch harmonics, the point of the thumb closest to the string (usually the left side of the thumb's tip), touches the string at a node point, at the same time as the pick touches the string. The pick will be plucking the string slightly to the right of where the thumb touches the string. The images at this webpage illustrate this well.
If using a R.H. finger to play pinch harmonics, it's tip (or nail) will again touch at a harmonic node-point, but the pick will now be plucking to the left of where the finger touches the string. I use my R.H. ring finger to do this, but it is possible to use the index, middle or little fingers, too.
To produce artificial harmonics on classical guitar, the R.H. index finger usually touches the node point (by "pointing" somewhat towards the neck), while the R.H. ring finger plucks the string. The image below illustrates this well:

EDIT: one last point. The technique of using the ring finger to pluck the string is helpful on classical guitar, as it means you pluck the string some distance from where you touch the node. As classical guitar is acoustic (and so, obviously, doesn't use distortion either!) it is harder to produce a strong harmonic. Plucking further from the node helps to do this. I illustrate this in my answer to another question, here.
Comment: If you find you can't get the pinch right, you could also try "tap harmonics" - play the string normally, then create the node by lightly tapping the string with your right hand. It's a different sound, but also a good way to explore where the nodes exist.
Comment: My personal way to do a pinch is to hit the string with the fleshy part of my thumb right as I pick the note. It's incredibly easy but it takes practice. Also, note that where you pick the string actually matters. It will change the note if you pick closer or farther from the bridge.
Comment: @GGMG On a theoretical string, there are infinite nodes of vibration, so when playing a pinch anywhere, you are exactly over a node. However, if you've just divided the string into 27 or some other small division, you won't have enough energy and clean enough technique to sound the note audibly. Playing a note takes energy, and the hand, when dampening the string, stops the string from vibrating at a high enough volume at that node.
Comment: @GGMG That's why higher and higher harmonics on the same string are harder and harder to play. With a fingertip that tapers down to a point with zero area, this would be much easier. Also, you don't have to be *perfectly* over the node. The farther from the node you get, the quieter and more muffled the harmonic will be. So it's unlikely you'd really be able to divide the string into 128/257; you'd be so close to the node dividing it in 1/2 that any sound you made would be the harmonic at the node cutting the string in half.
Comment: This is a great answer but if I were a newbie (as per OP)  I don't think I'd really understand the technique of using thumb or finger. Could you explain that in a bit more detail ?
Comment: @user2808054, I added in quite a bit of info about harmonics, nodes and how to find and play them, at the end of my answer - hopefully this helps!
Comment: @BobBroadley I'm sure it's just simplification on your part, but I'm not following the idea that I can split the string using an integer and have that many node points. I feel like there would have to be a limit on that, otherwise we'd have infinite node points and no way to possible miss any of them.
Answer: You need to change your finger position on the pick so that your index finger or thumb is slightly over hanging the side of the pick. Strike the note with the pick and then brush with the flesh of your finger or thumb (depending on whether it's an up or down stroke). Notes / strings will get different harmonics at slightly different places. Use your pick ups as a visual indicator of where your pick should be. Experiment with lots of different picking positions.
This is a hard technique to master. Good luck.
Answer: Harmonics occur on the string at points that divide the string into equal parts.  Lightly touch a string right above the 12th fret bar and while doing so strum the string -- you'll notice that the string sounds an octave higher, though different from just fretting the 12th.  What you're doing is dampening the fundamental frequency and "odd" harmonics (3x, 5x, etc.) of open string, leaving the "even" harmonics (the predominant one being 2x the frequency of the fundamental, which is an octave higher).  Notice that the 12th fret is exactly halfway the length of the string.  You can do the same as the 7th fret (1/3 of the string) and the 5th fret (1/4 of the string), for example.
Now pick a note, say the 12th fret on the D string. Fret that note, and pick the string exactly halfway between that fret and the end of the string (the end on the body of the guitar of course, not the neck).  You might have to experiment a little to find the exact halfway point to pick, since it's not over a handy fret marker.  You'll notice a similar effect to the above harmonics.  You can do this for any note.  Pick another fret, find the halfway point between that fret and the end of the string, and pick the string.  Same effect.
To intensify the effect, you need to lightly touch the string at this point as quickly as possible after picking (see yossarian's answer).  This will bring out the harmonic more instead and keep the fundamental frequency dampened.
Just like with regular harmonics, you can also pick a point 1/3 or 1/4 of the way along the string instead of 1/2 of the way, although this is more difficult.
Comment: Another interesting harmonic is whilst playing a note, lightly touch the same string a full octave up (same note); this works for any note
Comment: @DRL That's actually the same as the halfway-point harmonic :)
Comment: I know, its just better to think of it in terms of an octave, instead of a halfway point :)
Comment: @DRL I agree, but I'm assuming (possibly incorrectly) that Znarkus does not have much music theory behind him.  Thanks for your comment though -- having it explained both ways will make it easy for everyone to understand this answer.
Answer: Pretty easily; play the note on a downstroke, make sure you catch it well, on the way out (after sounding the note) catch the string slightly with the skin of your thumb, not too much or you will kill the note, note too little or the harmonic will not sound.
Practice this; and you'll have it in no time; try playing a minor pentatonic all in pinched harmonics.
Answer: There are 'sweet spots' along the length of each string. When a string is played and is vibrating, a light tap on the sweet spot can cause a harmoinic sound. This happens because the tap slightly alters the way the string vibrates.
A usual sweet spot is just above the first pickup. To hit a pinch harmonic, pick the note and almost immediately afterwards, touch the string lightly with the edge of your thumb on your picking hand.
Think of it as picking and 'brushing' the stri in one motion.
It will take a lot of practise but over time you'll get better.
To add some attitude, you can give the note a lot of vibrato just after hitting the harmonic.
Answer: Pinch harmonics are harmonics, and harmonics come with less volume than the fundamental. You need some sort of compression or boost to offset that. If you aren't compressing or turning up or stomping a distortion pedal, you won't get the result you want. The rest of what everyone says (not a lot of pick sticking out from the thumb, knowing the right spots to pick) are important, but some gain or compression is crucial.
Comment: Also a hot pickup helps a lot. Even the best harmonics merchants will struggle with a quiet passive pickup.
Answer: I followed this tutorial... at first it was hard... very hard indeed... it sounded awful... but with lots-o-opractice it started to sound good
Pinch TUTORIAL
Answer: See: Dance the Night Away - Van Halen - another way, apart from putting the fleshy part of your index finger lightly over the note ( as explained above) and then plucking with your third finger: Point and Pluck, is to tap the note you want to play as a False Harmonic.  Again watch Eddie Play the solo to Dance the Night Away....
Answer: For me the pick with sharpend end (sometimes this is called jazz shape) helped in mastering this technique.
It was instantly change: Standard pick = i can't do this and then sharpend pick = i can:)
Maybe You could try to change Your pick/it's shape?
Answer: I usually hold my pick like this (with slight variations depending on what needs to be played:
(That's not me btw :P )
http://www.guitarlearningtips.org/wp-content/uploads/2012/01/pinch-harmonics-3rd-position.jpg
I find that the bulge on your thumb at the knuckle can be used to easily pull of a pinch, without having to move your hand clumsily.
I learnt by watching a couple of videos on YouTube. Doesn't matter which ones, they'll all basically tell you the same thing.
Theoretically, you can pull it off at any note, any string.
Practically, however, it depends on many things like the thickness of the string, how a high a note you're holding, and well, how good you are.
Yes, you have to hit the string at particular points. You can find out where exactly by, as yossarian already said, by using your pickups as a reference point.
On a side note, I advise against holding your pick with three fingers. It makes it more difficult to switch between the lower (6th, 5th) strings and the higher ones (1st, 2nd). You would have to displace your hand. If you use only two fingers, as seen in the above link, it's much easier.
I think you should start migrating to two fingers.
The only way to get good at squealies is to understand how exactly to do it, and keep trying. I know it's frustrating in the beginning, you don't know what exactly people are talking about, how to move your finger, you're hurting the side of your thumb, and you just wanna snap your strings but trust me, once you pull it off and get the hang of it and realize you CAN sound like Dimebag... It's gonna be totally worth :)
Keep it metal \m/
Answer: Just feel it.
You'll get it one day and never lose it. Playing squealies and dive bombs with the whammy bar on my old Yamaha was a defining achievement in my existence on this planet.

How to do "metal" harmonics (pinch etc)


When creating a RAR file through CMD am getting "Access is denied"

Question: I have a set of files in my system which am creating a RAR file by using a task scheduler and executing a bat file.
This is my bat file
TITLE Covert_To_war
cd D:\RarFolder\Current
"C:\Program Files\WinRAR\Rar.exe" a -ep1 -idq -r -y "Current" "E:\Folder1\backup"

When I execute this bat file alone this function works properly and the Rar file is created. However when I run this from a task scheduler. This throws off an error
Cannot create Current.rar
Access is denied
When I tried to compare the two procedures I found out that the first line in the bat file
cd D:\RarFolder\Current

works when I execute it alone as a bat file. However, when I run it from a task scheduler that line is not executing and the directory hasn't been changed. Can anyone help me out here? Why is the Cd command not working when I execute it from a task scheduler and why does it say Cannot create Current.rar and access is denied.
enter code here
Comment: Change `cd D:\RarFolder\Current` to `cd /D "D:\RarFolder\Current"` to change the drive as well…
Comment: You could also discard the batch file and configure the scheduled task to run `"C:\Program Files\WinRAR\Rar.exe"` with the arguments `a -ep1 -idq -r -y "D:\RarFolder\Current\Current.rar" "E:\Folder1\backup"` as there is no need to run `cmd.exe` to just run `rar.exe`.
Answer: You need to list your Task Scheduler settings. If they are anything other than Only Run When User Logged On then the script won't have access to mapped drives by drive letter as drive letters are mapped by security token. You may use UNC \\servername\sharename\folder\file.ext.
Answer: I figured this one out. In the windows task scheduler under actions, I just configured the "start in" field to point out the directory I want the operations to be done.
I had got the access denied error because the first line "CD.." command hadn't been carried out.


Migration not found - D8

Question: Following this I have created a module to migrate d7 users to d8. I have enabled all mandatory modules needed to run migration. But when I do drush migrate-import {mymigrationid} ; it says : Migration not found.
But When I did "drush config-list|grep migrate" , it is showing that particular migration:

migrate.migration.d7vm_users
migrate_plus.migration.custom_user

But when I'm doing drush migrate-status, these migrations are not listing up there.
Can anyone tell what's supposed to get missed?
Here is my mymodule/config/install/vm.yml file
id: d7vm_users
label: User accounts
migration_tags:
  - Drupal 7
dependencies:
  enforced:
    module:
      - mymodule
source:
  plugin: d7vm_users
destination:
  plugin: entity:user
process:
  uid: uid
  name: name
  pass: pass
  mail: mail
  created: created
  access: access
  login: login
  status: status
  timezone: timezone
  langcode: language
  init: init

and src/Plugin/migrate/source/User.php
<?php
/**
 * @file
 * Contains \Drupal\mymodule\Plugin\migrate\source\User.
 */

namespace Drupal\mymodule\Plugin\migrate\source;

use Drupal\migrate\Plugin\migrate\source\SqlBase;

/**
 * Extract users from Drupal 7 database.
 *
 * @MigrateSource(
 *   id = "d7vm_users"
 * )
 */
class User extends SqlBase {

  /**
   * {@inheritdoc}
   */
  public function query() {
    return $this->select('users', 'dcf_u')
      ->fields('dcf_u', ['uid', 'status', 'created','access', 'login',    'name',
        'pass', 'mail', 'init', 'language']);
  }

  /**
   * {@inheritdoc}
   */
  public function fields() {
    $fields = [
      'uid' => $this->t('Account ID'),
      'status' => $this->t('Blocked/Allowed'),
      'created' => $this->t('Registered date'),
      'access' => $this->t('Time of last access'),
      'login' => $this->t('Time of last login'),
      'name' => $this->t('Account name (for login)'),
      'pass' => $this->t('Account password (raw)'),
      'mail' => $this->t('Account email'),
      'init' => $this->t('init'),
      'language' => $this->t('language'),
    ];

    return $fields;
  }

  /**
   * {@inheritdoc}
   */
  public function getIds() {
    return [
      'uid' => [
        'type' => 'integer',
        'alias' => 'dcf_u',
      ],
    ];
  }

}
?>

Answer: If your source plugin extends SqlBase, you need to make sure you have the database configuration set up correctly. Otherwise Migrate will silently ignore the migration.
In your settings.php or settings.local.php, add the following database configuration:
$databases['migrate']['default'] = array(
  'driver' => 'mysql',
  'database' => 'NAME OF YOUR SOURCE DB',
  'username' => 'YOUR DB USER',
  'password' => 'YOUR DB PASSWORD',
  'host' => 'localhost',  // change this as necessary
);

By default, Migrate looks for a DB connection named "migrate". If you use any other name, the migrations won't appear when you run drush migrate-status.
Note: The "migrate" connection is in addition to your "default" connection. You should have two connections in your settings if you're migrating from a MySQL database.
In case anyone's curious, the DB connection check occurs in the method SqlBase::getDatabase() in drupal/core/modules/migrate/src/Plugin/migrate/source/SqlBase.php.
This is documented in https://www.drupal.org/node/2830031 and apparently will be fixed in Drupal 8.4.

Migration not found - D8


Trying to publish swagger.json file to atlassian wiki page

Question: I am trying to publish swagger.json file to atlassian wiki page using swagger-confluence-cli-all-2.2-RELEASE.jar
Command used
java -jar swagger-confluence-cli-all-2.2-RELEASE.jar -u "<atlassian wiki url>" -b "<base64 encode username:password>" -a "35273" -k "TestPage" -g "true" -i "true" -s "swagger.json file" -t "Test1" -m "single"

But below exception I am getting
2017-04-13 10:52:47.215  INFO - [main] n.s.s.c.s.i.SwaggerToAsciiDocServiceImpl : Converting Swagger Schema to Ascii Doc...
Exception in thread "main" java.lang.IllegalArgumentException: text must not be blank
at org.apache.commons.lang3.Validate.notBlank(Validate.java:451)
at io.github.swagger2markup.markup.builder.internal.asciidoc.AsciiDocBuilder.paragraph(AsciiDocBuilder.java:91)
at io.github.swagger2markup.internal.document.builder.OverviewDocumentBuilder.buildContactInfoSection(OverviewDocumentBuilder.java:127)
at io.github.swagger2markup.internal.document.builder.OverviewDocumentBuilder.build(OverviewDocumentBuilder.java:88)
at io.github.swagger2markup.Swagger2MarkupConverter.toString(Swagger2MarkupConverter.java:233)
at net.slkdev.swagger.confluence.service.impl.SwaggerToAsciiDocServiceImpl.convertSwaggerToAsciiDoc(SwaggerToAsciiDocServiceImpl.java:67)
at net.slkdev.swagger.confluence.service.impl.SwaggerToConfluenceServiceImpl.convertSwaggerToConfluence(SwaggerToConfluenceServiceImpl.java:73)
at net.slkdev.swagger.confluence.cli.SwaggerConfluence.runCLI(SwaggerConfluence.java:63)

Answer: If you try debugging mode, you'll see your swagger.json file has an empty object, called contact. So, you should fill in some of its properties, like name, url and/or email.
Comment: Thanks for answering but i solved  that day only , the problem was with confluence indexing page
Comment: The problem was the space key? How do you resolved the issue?


Equivalence of norms in $L_p$ spaces.

Question: Let $(f,g) \in {W_0}^{1,p}(0,1) \times {L^p}(0,1), p\in[1,\infty]$. I want to prove the equivalence of the two norms $${\left\| {{{{f_x} - g} \over 2}} \right\|_p} + {\left\| {{{{f_x} + g} \over 2}} \right\|_p}$$
and the usual one $${\left\| {{f_x}} \right\|_p} + {\left\| g \right\|_p}.$$
The proof is straighforward if $p=2$. Wht about an arbitrary $p$. Is that seems right?. Thank you.
Answer: Let $M=\left\|\dfrac{a+b}{2}\right\|_{L^{p}}+\left\|\dfrac{a-b}{2}\right\|_{L^{p}}$, then Minkowski's inequality gives $M\leq\left\|\dfrac{a}{2}\right\|_{L^{p}}+\left\|\dfrac{b}{2}\right\|_{L^{p}}+\left\|\dfrac{a}{2}\right\|_{L^{p}}+\left\|\dfrac{-b}{2}\right\|_{L^{p}}=\|a\|_{L^{p}}+\|b\|_{L^{p}}$.
On the other hand, $\|a\|_{L^{p}}=\left\|\dfrac{a+b}{2}+\dfrac{a-b}{2}\right\|_{L^{p}}\leq\left\|\dfrac{a+b}{2}\right\|_{L^{p}}+\left\|\dfrac{a-b}{2}\right\|_{L^{p}}$, and $\|b\|_{L^{p}}=\left\|\dfrac{a+b}{2}-\dfrac{a-b}{2}\right\|_{L^{p}}\leq\left\|\dfrac{a+b}{2}\right\|_{L^{p}}+\left\|\dfrac{a-b}{2}\right\|_{L^{p}}$, so $\|a\|_{L^{p}}+\|b\|_{L^{p}}\leq 2\left(\left\|\dfrac{a+b}{2}\right\|_{L^{p}}+\left\|\dfrac{a-b}{2}\right\|_{L^{p}}\right)$.
Comment: Thank you sir for the answer.

Equivalence of norms in $L_p$ spaces.


is it possible to reload httpd from php

Question: I have a LAMP server running on CentOS 5.5 64-bit and would like to reload my httpd service after making new subdomains.
I have 3 servers mounted onto my web server, and depending on what resources each mounted server has i create new user accounts and add them to the available server.
for instance when a user registers and needs 5gb of space then my PHP scripts searches through my mounted servers to see if they have an allocation slot open for a new user. if not then it moves to the next server and so on. So depending on the server they end up in i create a new conf files to reflect that server as their DocumentRoot
the issue is that i need to reload the httpd service manually after each subdomain is created for a particular user.
I am trying to find a way to have the httpd service reloaded as soon as a user registers.
currently i am trying this:
system("/bin/echo '/sbin/service httpd reload > /dev/null 2>&1' | /usr/bin/at now");

my httpd service is located at /etc/init.d/httpd
Answer: Execute commands requires root from PHP is not good idea. I would suggest you monitoring the /etc/httpd/conf.d folder and reload Apache whenever it changes. Take a look at incron.

Install it from rpmforge repository:
# yum -y install incron

Edit root's crontab with incrontab -e:
/etc/httpd/conf.d/ IN_CREATE,IN_DELETE,IN_MODIFY /etc/init.d/httpd reload

Start it:
# service incrond start
# chkconfig incrond on

and create a .conf file in /etc/httpd/conf.d and take a look at /var/log/cron to see what happens.
Comment: do you have any live examples on how to use incron?
Comment: Check out my above example (I've not tested).
Comment: oh wow, easier than i thought! let me try
Comment: `rpmforge` repo.
Comment: ok got it installed and added the example provided then loaded up `incrontab /helix/cron_conf.txt` the started the service. i did make a new conf file but when i check the logs it didn't log anythin
Comment: You did wrong. Login as root, type `incrontab -e` and insert the above line into.
Comment: i am in as root, and when i run `incrontab -e` i get `editor finished with error: No such file or directory` so i ran this `incrontab -u root /helix/conf_cron.txt`
Comment: @s2xi let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/1241/discussion-between-quanta-and-s2xi)
Answer: The PHP script could invoke "apachectl restart" via sudo (ie, sudo /usr/sbin/apachectl restart), and sudo could be configured to permit the user that runs httpd (and therefore, presumably, the PHP script) to run that command without password.  This line of sudoers code would achieve that:
apache  ALL=(root) NOPASSWD: /usr/sbin/apachectl restart

Obviously, you will need to ensure that the user and path there are correct for your environment; mine are taken from a CentOS 5 system.
Comment: Both; it is suitable for use as a bash command, and therefore also something you could invoke with the **system()** call.
Comment: is that a bash command or something i would run system or exec functions with?
Comment: when you say apache is that the user or group your trying to run the command in?
Comment: The user. (filler text)
Comment: when i run this in the terminal it returns `-bash: syntax error near unexpected token ('`
Comment: Let me be clear.  The command you want to run is `sudo apachectl restart`.  The line starting `apache ALL=...` is a sudoers entry; that is, a line that you will have to put in your sudoers file with the `visudo` command in order to enable the `sudo apachectl restart` to run from the apache account.  Assuming you have the `sudo` tool installed, a quick perusal of `man sudo` and `man sudoers` may be helpful for you at this point.
Answer: I would do this by having php create a directory somewhere in the filesystem and then have a cron script run as root that would check for the existence of the directory and restart the HTTP server if it exists and remove the directory. This way at least you are not giving the httpd user too much privilege.
Comment: Lazy is the mother of security breach.
Comment: hmmm, let me look into that. I thought of that at some point but i think i just got lazy with thinking of how i would approach that from a programming stand point.
Comment: i know, but still human nature to want to take shortcuts when you feel that end is in sight ;)

is it possible to reload httpd from php


Trouble proving that an expression is a norm in $H^2(\mathbb{R}^N)$

Question: I'm studying some theory about the Sobolev Space $H^2(\mathbb{R}^N)$ and I was abble to understand the proof that
$$H^2(\mathbb{R}^N)=\{f \in L^2(\mathbb{R}^N): |\xi|^2\hat{f}(\xi) \in L^2(\mathbb{R}^N)\}, $$
where $\hat{f}$ denotes the Fourier transform of $f$.
Next, the text says that the expression defined for $f \in H^2(\mathbb{R}^N)$ by
$$\lVert f \rVert_{H_2}=\left(\int_{\mathbb{R}^N}(1+|\xi|^4)|\hat{f}(\xi)|^2 d \xi\right)^{\frac{1}{2}}$$
defines a norm in $H^2$. I don't have any trouble in prove all the properties of norm, except the triangle inequality. For the triangle inequality I've tried using the Holder inequality to help me and the triangle inequality of $|.|_2$ norm, but I'm having no success.
Anyone can give me please some hint on how to proceed in prove the triangle inequality? Any help will be very valuable, this is the last the part that I need to fully understand this beautiful theorem of my text :)
Answer: I think it's just  Minkowski's inequality for the following measure  $d\mu =(1+|\xi|^4 ) d\xi.$


QDA number of parameters

Question: If we include to Linear Discriminant Analysis quadratic parameters we get Quadratic Discriminant Analysis classifier. Number of parameters is $(K-1)\times[(p\times(p+3)/2) + 1]$ where K is number of classes and p is number of features.
Why $K-1$? In the book it is said that we only need to compare $\delta_{k}(x) - \delta_{K}(x)$ of discriminant functions of some prespecified class K, but why do we do that and how it works?
$(p\times(p+3)/2) + 1$ is number of factors in multivariate quadratic function how is it calculated?
Answer: First, for one klass $k$ we need to calculate the following parameters:

1 probability prior; $\hat \pi_k = N_k/N$,
$p$ class means; $\hat \mu_k = \sum_{g_1 = k} x_i/N_k$ and
$p(p+1)/2$ parameters for the covariance matrix.

Where $N_k$ is the number of class-$k$ observations and $N$ the total number of observations.
Putting this together gives us $1 + p + p(p+1)/2 = p(p+3)/2 + 1$ total parameters to estimate for each class.
Note that in QDA (unlike LDA) we do not assume that the covariance matrices are the same between classes and thus need to estimate it for each class.
Now, this is the number of parameters for each class but we have $K$ classes. However, since every observation belongs to one class it is enough to estimate $K-1$ classes. Any observation that is not in any of these $K-1$ classes will be in the $K$:th class.
Thus, the total number of parameters in QDA is
$$ (K-1) \cdot \left( \frac{p(p+3)}{2} + 1 \right) $$

QDA number of parameters


Couldn't install RVM and Ruby on Mountain Lion

Question: I tried all of the solution at StackOverflow and none of them worked for me. I tried with following command:
rvm get head; rvm install 1.9.3 --debug

and the output can be found here: http://pastie.org/7189647
Thanks in advance for the help.
Comment: what is in `/Users/aslam/.rvm/log/ruby-1.9.3-p392/make.log` also your problem looks like you use `zsh` and hit known bug: https://github.com/wayneeseguin/rvm/issues/1665 - temporary switching to `bash` would show the real problem and break the installer earlier.
Answer: Did you try the two commands separately? It appears the rvm get head portion of the command worked. Try running rvm install 1.9.3 or rvm install 1.9.3-p392.
Answer: Finally I fixed the problem.

Open the Xcode 4.6 or 4.6.1 and go to Preference -> Downloads and install 'Commandline tools".
Open the terminal and type
\curl -L https://get.rvm.io | bash -s stable --rails --autolibs=enabled

as instructed in the RVM site. It works like flawless.


Imprimir letras que estão fora do collections.Counter

Question: Fiz um código que retorna a recorrência de caracteres de um arquivo.
from collections import Counter

with open('hino.txt', 'r', encoding='utf8') as f:
    conteudo = f.read()
    counter = Counter(conteudo)
    print(counter)

E essa foi a saída dele:
Counter({' ': 138, 'e': 97, 'a': 87, 'o': 80, 'r': 65, 's': 54, 'd': 42, '\n': 38, 'i': 31, 't': 31, 'n': 28, 'm': 28, 'l': 27, 'u': 27, ',': 20, 'p': 15, 'b': 13, 'v': 10, 'c': 9, 'f': 8, 'E': 8, 'í': 6, 'z': 6, '!': 6, 'B': 6, 'ç': 5, 'S': 4, 'g': 4, 'P': 4, 'R': 4, 'q': 4, 'j': 4, 'Q': 4, 'D': 4, 'ã': 3, 'A': 3, '.': 3, 'C': 3, 'h': 3, 'á': 2, 'N': 2, 'T': 1, 'à': 1, 'é': 1, ';': 1, 'J': 1})

Como eu faria para imprimir também as letras que não possuem constam no resultado do Counter?
Por exemplo:
Y:0

Outra questão, como eu poderia fazer para imprimir o número de espaços e a letra com maior incidência?
Que seria o ' ':138 e 'e': 97
Answer: Segundo a documentação, um Counter é uma subclasse de dict, e portanto também é um dicionário. Por isso é possível verificar se um elemento existe e obtê-lo, da mesma forma que fazemos com dicionários.

Para obter as letras que não estão no Counter, basta verificar se elas são chaves do dicionário. Uma opção é usar in:
from collections import Counter

counter = Counter()
with open('hino.txt', 'r', encoding='utf8') as f:
    for linha in f:
        counter.update(linha)

from string import ascii_letters

acentos = 'áéíóúãõâêîôûç'
todas_letras = ascii_letters + acentos + acentos.upper()

for letra in todas_letras:
    if letra not in counter:
        print(f'{letra}: 0')

Mudei um pouco a forma de ler o arquivo. Claro que usar read() também funciona, mas este método carrega todo o conteúdo do arquivo para a memória. Se o arquivo for pequeno não faz diferença, mas para arquivos maiores, pode ser interessante lê-lo linha a linha para não gastar memória à toa (e o for linha in f faz isso, lê o arquivo uma linha por vez e logo em seguida a descarta, em vez de carregar o arquivo inteiro de uma vez).
Depois eu criei uma string contendo todas as letras. Como o seu Counter está diferenciando letras maiúsculas, minúsculas e acentuadas, estou assumindo que A, a, á, Á, ã, Ã, etc, são letras diferentes. Se quer uma definição diferente, basta mudar a string todas_letras para ter apenas o que você precisar.
Depois eu faço um loop pelas letras e só imprimo as que não estão no Counter.
Outra opção é usar set:
counter = ... # cria o Counter

from string import ascii_letters

acentos = 'áéíóúãõâêîôûç'
todas_letras = set(ascii_letters + acentos + acentos.upper())

for letra in sorted(todas_letras - set(counter.keys())):
    print(f'{letra}: 0')

Primeiro eu crio um set com todas as letras, e subtraio de outro set contendo apenas as chaves do Counter. O resultado é outro set, contendo as letras que não estão no Counter. Eu uso sorted para retornar as letras em ordem alfabética, já que um set não garante a ordem dos elementos (lembrando que as letras acentuadas ficarão no final, mas uma vez tendo as letras, você pode mostrar da forma que quiser).

Se quer mostrar quantas vezes um determinado caractere ocorre, basta usá-lo como chave. Por exemplo, para o espaço:
# imprime quantas vezes o espaço ocorreu
print(counter[' '])

Já para a letra mais frequente, você tem que obter os elementos mais frequentes com most_common, e percorrê-los até encontrar uma letra:
# busca a letra mais frequente
for c, qtd in counter.most_common():
    if c.isalpha(): # encontrei uma letra
        print(f'Letra {c} ocorre {qtd} vezes')
        break # se já encontrei, interrompo o loop

Fiz assim porque não sei como está o seu texto, e vai que os caracteres mais frequentes não são letras (podem ser espaço, sinais de pontuação, números, etc). Então eu prefiro percorrer os caracteres mais comuns até encontrar uma letra. E quando encontro, interrompo o loop com break.
Mas isso só mostra uma letra. E se tiver empate? Nesse caso, você pode pegar a letra mais frequente, e imprimir todas que têm a mesma quantidade:
letras = list(filter(lambda c: c[0].isalpha(), counter.most_common()))
maior_qtd = letras[0][1]
print(f'Letras mais comuns, ocorrem {maior_qtd} vezes')
for c, qtd in letras:
    if qtd != maior_qtd:
        break # não é a mais frequente, interrompe o loop
    print(c)

Primeiro eu uso filter para gerar uma lista contendo somente as letras do Counter (e suas respectivas quantidades). Depois pego a quantidade do primeiro elemento (ou seja, da letra mais frequente).
Em seguida, eu percorro a lista e vejo se as letras ocorrem na mesma quantidade de vezes da mais frequente. Quando tiver um valor diferente, eu interrompo o loop.
Assim, se duas ou mais letras forem a mais frequente, todas elas serão mostradas.
Answer: import string
from collections import Counter

Pegando os caracteres ascii
asciiLetters = string.ascii_letters

Criando um dicionário com chave(letra) e com o valor(0)
dicionario = {key:0 for (key) in asciiLetters}

Abrindo o arquivo e contando as ocorrências das letras
with open('hino.txt', 'r', encoding='utf8') as f:
    counter = Counter(f.read())

Atualizando o dicionário com os valores que Counter contou
dicionario.update(dict(counter))
dicionario

Aqui mostra os caracteres com maior ocorrência
counter.most_common()[:3]

Código
import string
from collections import Counter

asciiLetters = string.ascii_letters
dicionario = {key:0 for (key) in asciiLetters}

with open('hino.txt', 'r', encoding='utf8') as f:
    counter = Counter(f.read())

dicionario.update(dict(counter))
dicionario

counter.most_common()[:3]


"Can't perform a React state update on an unmounted component" quando tento alterar o state no useEffect

Question: Possuo um component drawer do Material React UI e preciso que quando o componente seja montado, cheque no localStorage e pegue o valor do usuário logado para mostrar no template.
Esse é meu componente:
const PersistentDrawer = () => {

  const [userLogged, setUserLogged] = useState({});
  useEffect(() => {
    setUserLogged(JSON.parse(localStorage.getItem('currentUser')))
        // eslint-disable-next-line react-hooks/exhaustive-deps
    },[])
  const classes = drawerStyles();
  const theme = useTheme();
  const [open, setOpen] = useState(false);

  const handleDrawerOpen = () => {
    setOpen(true);
  };

  const handleDrawerClose = () => {
    setOpen(false);
  };

  return (

        <CssBaseline />
        <AppBar
            position="fixed"
            className={clsx(classes.appBar, {
            [classes.appBarShift]: open,
            })}
        >
            <Toolbar>
            <IconButton
                color="inherit"
                aria-label="open drawer"
                onClick={handleDrawerOpen}
                edge="start"
                className={clsx(classes.menuButton, open && classes.hide)}
            >
                <MenuIcon />
            </IconButton>
            <Typography variant="h6" noWrap>
                Persistent drawer
            </Typography>
            </Toolbar>
        </AppBar>
        <Drawer
            className={classes.drawer}
            variant="persistent"
            anchor="left"
            open={open}
            classes={{
            paper: classes.drawerPaper,
            }}
        >

        <Typography component="h6">{userLogged.login}</Typography>
            <IconButton onClick={handleDrawerClose}>
                {theme.direction === 'ltr' ? <ChevronLeftIcon /> : <ChevronRightIcon />}
            </IconButton>

            <Divider />
            <List>
            {['Inbox', 'Starred', 'Send email', 'Drafts'].map((text, index) => (
                <ListItem button key={text}>
                <ListItemIcon>{index % 2 === 0 ? <InboxIcon /> : <MailIcon />}</ListItemIcon>
                <ListItemText primary={text} />
                </ListItem>
            ))}
            </List>
            <Divider />
        </Drawer>

  );
}

export default PersistentDrawer

Quando eu abro/fecho meu drawer eu recebo:

Can't perform a React state update on an unmounted component. This is
  a no-op, but it indicates a memory leak in your application. To fix,
  cancel all subscriptions and asynchronous tasks in a useEffect cleanup
  function.

Porque isso ocorre?
Answer: Uma das formas de evitar este problema é criar uma variável para controlar se o componente já foi carregado antes de tentar retornar o dado do seu localStorage, tente fazer o seguinte:
const PersistentDrawer = () => {

  const [userLogged, setUserLogged] = useState({});
  useEffect(() => {
    let isCancelled = false;

    if (!isCancelled) {
        setUserLogged(JSON.parse(localStorage.getItem('currentUser')))
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }

    return () => {
      isCancelled = true;
    };

  },[])
  const classes = drawerStyles();
  const theme = useTheme();
  const [open, setOpen] = useState(false);

  const handleDrawerOpen = () => {
    setOpen(true);
  };

  const handleDrawerClose = () => {
    setOpen(false);
  };

  return (
    //Resto do código
  )
}

Aqui tem um exemplo:
https://codesandbox.io/s/use-local-variable-to-avoid-setstate-on-unmouted-component-6cmie
Aqui tem outra forma de resolver:
https://codesandbox.io/s/useref-to-avoid-setstate-on-unmouted-component-p5gmb

“Can't perform a React state update on an unmounted component” quando tento alterar o state no useEffect


Why X=x is impossible for continuous random variables?

Question: Background:
When we consider a continuous random variable $X$ and consider some independent realisations of $X$, I am told that the realisations must be unique since $\text{Pr}(X=x)=0$. When we consider the long run frequency interpretation of probability, where $\text{Pr}(A)=\frac{\text{ Number of times you get event A}}{\text{Number of trials}}$, and we observe $x$ three times we have that $3/\text{Number of independent runs of the experiment}$ still will approach 0 as number of trials approaches infinity.
Question:
Why is it then impossible that I observere a finite amount of observations that are the same when I make a very large number of independent realisations of a RV? When we divide this number by the number of trials, the fraction will approach 0 as the number of trials approaches infinity, so that $\text{Pr}(X=x)=0$ still holds.
Comment: For "must be unique" it is better to say "will be unique with probability $1$" and for "impossible" better to say "zero probability".  If you  observe a value of a continuous random variable, the prior probability that you would observe that particular value was $0$ even though you did in fact observe it, so it was not "impossible" to observe
Comment: Thanks for your comment and answer, @Tim. I will change the title.
Comment: But you won't observe X=3. You'll never observe X=3. You might observe X=3.00001229384873492064897456978136578913657891648975623894761298374612897346189775625....... and so on.
Answer: Actually nobody says that such event is impossible. Probability equal to zero is not the same as impossibility (check here, here and here). Probability that $X=x$ is equal to zero for continuous variables because chance of such event happening is infinitely small since there is an infinite number of real numbers.
Also from purely mathematical point of view informally $\tfrac{1}{\infty} = 0$ and more formally, since infinity is not a number, $\lim_{n\to\infty} \tfrac{1}{n}=0$, so saying that probability of something happening is infinitely small is literally the same as saying that it is equal to zero.
Comment: From a "purely mathematical point of view" $1/\infty$ is either *undefined* (when working with a standard model of the reals) or else it is *not* zero when you are working with the nonstandard reals: it is a nonzero infinitesimal whose standard part is zero.
Comment: Could you please explain the difference between impossible, implausible and improbable (the terms appear in your second link)? I am not that familiar with sigma-algebras and measure-theory. Should not every possible subset of the sample space be part of the sigma-algebra, so that if the event $A$ is part of the sample space then $A$ is in the sigma-algebra?
Comment: If I understand things correctly, the sample space consists of very possible outcome in the experiment. All outcomes that are not possible in the experiment are in the emptyset? Is this what we mean by saying $\text{Pr}(\emptyset)$=0 (since the emptyset does not contain any elements from $S$?). And $\text{Pr}(A)=0$ does not mean $A$ is impossible, since $A$ is a subset of the sample space? Is this correct, @Tim?
Comment: @FredrikAa Yes, you are correct. I do not think that the distinction between impossible and implausible makes much sense in practice, but as for impossible and improbable: throwing seven in six-sided die is impossible (set of all possible outcomes are numbers from 1 to 6). Throwing infinite number of heads in infinite number of throws while using fair coin is improbable, but if you consider all the combinations of all the possible chains of outcomes, then such is a member of such set.
Comment: As $x$ is already used, I'd use another variable name in the limit $\lim_{t\to\infty} 1/t = 0$ to avoid confusion


Typescript - How do I remove a value from a hashmap?

Question: I found this post about implementing a hashmap in typescript, and I've got that working, except for removing something from the hashmap.
TypeScript hashmap/dictionary interface
I add something by doing Input.keys[event.key] = event.keyCode; to add a key to my abstract Input class's keys field that is a hashmap. How can I remove something from it?
Answer: If your not doing this as just an exercise it might be useful to look into Map() I think it should provide the needed functionality


How to interpret negative quantiles on a qqplot?

Question: I am having troubles interpreting the qq plot below. The histogram is residuals from linear regression. How to interpret negative theoretical and sample quantiles? Shouldn't it be [0,1]?
Answer: The actual data values (in your case, the residuals) are plotted along the y-axis. The meaning of the x-axis is probably best illustrated through a simple example. There are five data values in the first column of the table below and they are sorted in increasing order. The remaining columns are rank order of the data values, percentile values (as proportions) associated with the ranks (see the NOTE below), and Z-values associated with those percentile values for a standard normal distribution.
NOTE: For n<=10, the percentile value (as a proportion) is computed as (rank-0.375)/(n+0.25). For n>10, we use (rank-0.5)/n. See http://en.wikipedia.org/wiki/Normal_probability_plot.
<code>   Sorted
    Data    Rank     Percentile        Z
      8       1        0.119        -1.180
     10       2        0.310        -0.497
     15       3        0.500         0.000
     20       4        0.690         0.497
     22       5        0.881         1.180
</code>
The normal Q-Q plot for this data set is shown below and you'll see that it plots the Sorted Data values on the y-axis and the Z-values on the x-axis.
Comment: "For n<=10, the percentile value (as a proportion) is computed as (rank-0.375)/(n+0.25). For n>10, we use (rank-0.5)/n" This isn't true of all software implementations. The OP is using R, but many other languages and packages implement these plots. On CV there is no default software, even though some software is more popular than others.
Comment: So "Theoretica quantiles" axis is just a z-score?
Comment: @YKY Yes, see the wiki here https://en.wikipedia.org/wiki/Normal_probability_plot
Answer: Recall what a q-q-plot is: it plots theoretical against observed quantiles.
When you ask whether it shouldn't be values in [0,1], you are thinking of the corresponding confidence levels. These are not plotted. (You could think of the confidence levels as parameterizing the sequence of dots in your q-q-plot: the dots in the lower left correspond to low confidence levels, the ones in the upper right to high ones.)
When you create a q-q-plot for a linear regression model, you assume normally distributed errors, so the theoretical quantiles on the horizontal axis will be distributed around zero, and since a linear regression always forces the average residual to be zero, the observed residual quantiles on the vertical axis will also be distributed around zero. The vertical axis will be scaled proportionally to your estimated residual standard deviation $\hat{\sigma}$, and if your dots lie on a straight diagonal line (again, with slope equal to $\hat{\sigma}$), you are good. In particular, neither the theoretical nor the observed quantiles will necessarily lie in some specific interval, since the normal distribution takes values on the entire real axis.
Comment: Expecting [0,1] I suggest means rather that the OP is expecting a (cumulative) probability scale. After all, Q-Q plots are often still called probability plots, along with P-P plots. I don't see that confidence levels are expected.
Comment: @NickCox: you are probably right. I honestly don't know what you call the-thing-in-[0,1]-that-you-plug-into-a-quantile-function, and I have seen this referred to as "confidence levels", although it doesn't feel right. Is this called the "probability scale"?
Comment: Cumulative probability is the name I used. It is true that the more you use it, the less you feel the need to name it. Being obliged to teach it helps there!


Using attachment_fu, how do you edit an existing photo, update only thumbnails, and leave original unedited?

Question: After a photo is uploaded and created using attachment_fu, is there a way to edit just the thumbnails and leave the original as it is?  I understand how to do the resizing or cropping, but it's applying the edits to all of the thumbnails and the originals, which is how I'm sure attachment_fu was intended to work.
For example, say in a photo gallery app the user uploads an image and needs to crop the image, but may need to crop it several times.  This would require going back to the original image to crop again.
This thread addresses the core issue of just updating thumbnails when cropping (using Kropper):
http://groups.google.com/group/attachme … c4d14be02d
Is there a simpler way to to bypass updating the original by hacking or patching attachment_fu?
Answer: I'd think your best bet would be to have the initial image upload be a separate file attachment to your model. You might have something like original_image and cropped_image.
Then when you need to make your edits, just reload from the original image:
<code># From attachment_fu docs, code to "upload" from local path
@attachable = AttachmentMetadataModel.new(:uploaded_data => ActionController::TestUploadedFile.new(path, mimetype))
@attachable.save
</code>


Hyper-V 2012 R2 windows backup lingering checkpoints

Question: I have a Windows 2012 R2 Hyper-V server that has two virtual machines running.
I have Windows backup configured to do a full bare metal backup of the Hyper-V server to USB disk.
Every few weeks the virtual machines become paused overnight.  On investigation this is due to lack of disk space.  On the GUI the checkpoints panel for both VMs is empty.  However the Virtual Disks folder contains many .avhdx files with the exact time stamp of the backup start time.
It seems that Windows Backup is not cleaning up the checkpoint files after its backup.  These files are not available in the GUI or by running the powershell command Get-VMSnapshot -ComputerName "vm01" -VMName "server"
The only way to clear these checkpoints is to shut down the virtual machine and wait for the merge to complete.
Have I missed something or is this a limitation of Hyper-V?
Comment: 1) what are the guest machines OSs? 2) have you tried a full Windows Update on hosts and guests? most of the backup stuff will be solved by updating 3) any errors in the event log that you can share?
Comment: The guest OSs are SBS 2011 and Windows Server 2008 R2. Both VMs are fully up to date with Windows updates and so is the host.
Answer: Take note of this note from MSDN:

Backing Up the Virtual Machines
  Hyper-V uses one of two mechanisms to back up each VM. The default backup mechanism is called the "Saved State" method, where the VM is put into a saved state during the processing of the PrepareForSnapshot event, snapshots are taken of the appropriate volumes, and the VM is returned to the previous state during the processing of the PostSnapshot event.
  The other backup mechanism is called the "Child VM Snapshot" method, which uses VSS inside the child VM to participate in the backup.).

Assuming that you are trying to use the "child VM mechanism", have you made sure you meet the critera outlined?

Backup (volume snapshot) Integration Service is installed and running in the child VM. The service name is "Hyper-V Volume Shadow Copy Requestor".
Windows 2000:  Backup Integration Service is not supported.
The child VM must be in the running state.
The Snapshot File Location for the VM is set to be the same volume in the host operating system as the VHD files for the VM.
All volumes in the child VM are basic disks and there are no dynamic disks.
All disks in the child VM must use a file system that supports snapshots (for example, NTFS).

If all of those critera are met, I would review the the following:
1) Are the VSS providers / writers in a healthy state on both the host and the guest VMs? This article from Veritas will show you how to check. It's essentially these two commands.
<code>vssadmin list writers
vssadmin list providers
</code>
2) Are the integration services up to date on the guest VMs? Try to install the integration services, if it is out of date you will be prompted to upgrade.
3) Have you reviewed the Windows backup logs to determine why this is occuring? The default log location is %windir%\logs\windowsserverbackup - additonal logs are outlined in this Technet post.


Hibernate mapping with multiple child classes and getting the super parent data from least child

Question: I have a requirement like: I have 3 classes A, B, and C. From A to B OnetoMany Mapping and B to C ManytoMany  Mapping. I need a BC join table with a date column and I want the list of A based on BC created Date.
Can Anyone Help Me On this?
Comment: Can you provide us with some code? What have you tried so far?
Answer: I'm not sure what you're asking.  Are you asking how to make a custom query for a particular method in your repository class?  Look here: https://www.petrikainulainen.net/programming/spring-framework/spring-data-jpa-tutorial-creating-database-queries-with-the-query-annotation/


Problem 4 of Section G of Chapter 13 of Pinter's Book of Abstract Algebra

Question: First, some background info/context:
Let $G$ be any group of order $10$. Then, by Cauchy's Theorem, there are elements $a, b \in G$ such that $\text{ord}(a)=2$ and $\text{ord}(b)=5$. Since $\text{ord}(a)$ and $\text{ord}(b)$ are coprime, no power of $a$ is equal to any power of $b$, except for the identity. Thus
$G = \{e, a, b, b^2, b^3, b^4, ab, ab^2, ab^3, ab^4 \}$.
The problem in the book:
"If $ba=ab^2$, prove that $ba^2=a^2b^4$ and conclude that $\textbf{b}=\textbf{b}^{\textbf{4}}$. This is impossible because $b$ has order $5$; hence $ba \ne ab^2$."
I don't understand:
I'm not sure how to prove the bold part, "conclude that $b=b^4$". How does one get this from the previous two equations? Wouldn't you have to assume commutativity somewhere?
Answer: $\mathrm{ord}(a)=2$ implies that $a^2=1$, and so $ba^2 = b\cdot 1 = b$, and $a^2b^4 = 1\cdot b^4 = b^4$.
Comment: Oh, wow- I can't believe I missed that! haha... I will accept your answer in 6 minutes, after the minimum waiting time expires.