What does "independent observations" mean?

Question: I'm trying to understand what the assumption of independent observations means.  Some definitions are:

"Two events are independent if and only if $P(a \cap b) = P(a) * P(b)$." (Statistical Terms Dictionary)
"the occurrence of one event doesn't change the probability for another" (Wikipedia).
"sampling of one observation does not affect the choice of the second observation" (David M. Lane).

An example of dependent observations that's often given is students nested within teachers as below. Let's assume that teachers influence students but students don't influence one another.
So how are these definitions violated for these data? Sampling [grade  = 7] for [student = 1] does not affect the probability distribution for the grade that will be sampled next. (Or does it? And if so, then what does observation 1 predict regarding the next observation?)
Why would the observations be independent if I had measured gender instead of teacher_id? Don't they affect the observations in the same way?
teacher_id   student_id   grade
         1            1       7
         1            2       7
         1            3       6
         2            4       8
         2            5       8
         2            6       9

Comment: One might suggest that the distribution of grades for teacher 1 had a lower "mean" value than for teacher 2 and hence the students of teacher 1 would all tend to have lower grades, on average, than the students of teacher 2. In other words, the distribution of students/grades for the two teachers could well be different distributions. That would be sufficient to render the observations dependent.
Comment: You cannot take either (1) or (2) as *definitions* of (statistical) independence, because independence can be defined without reference to causality.  All three quotations are only efforts to provide *informal, intuitive examples*. ((3) possibly could be taken as a definition provided you had access to a quantitative, rigorous definition of amount of information.) It would therefore be a good idea to refer to an actual definition such as those appearing under the heading "Definition" in the Wikipedia article you reference.
Comment: @GavinSimpson: I've been thinking about this exact line of reasoning. However, what if I replace `teacher` by `gender`? Gender is present in most social science data and correlates with almost anything to some extent.
Comment: It must surely depend on the response. If we were looking at grades of students in the sciences in the UK, perhaps there would be an effect with different attainment distributions for the two genders, *on average* over the populations you are studying. Anyway, all of this only matters (in a statistical model) for the residuals, or put differently for the responses conditional upon the fitted model. In other words, if observations aren't independent, that's OK as long as the model accounts for this such that the residuals are independent.
Comment: No, you can render the *residuals* independent (or at least reduce dependency to such an extent that the residuals appear independent). This comes say from the assumptions of the linear model; $\varepsilon \sim N(0, \sigma^2 \Lambda)$ where $\Lambda$ is a correlation matrix. The usual assumption is that $\Lambda$ is an identity matrix, hence off-diagonals are zero and hence the assumption of independence is on the residuals. Put another way though, this is a statement about $y$ *conditional upon* the fitted model.
Comment: Are you sampling with or without replacement in your student example?
Comment: I don't understand the example. Could you give a full presentation of it or a link where the example is fully explained?
Comment: I would also add that choosing appropriate covariates is important here. If `gender` is a catch-all but not a useful covariate for an effect, collect a better covariate.
Comment: @GavinSimpson: "all of this only matters (in a statistical model) for the residuals". -> **where did you read that?** It sounds odd to me because it suggests that you can 'render' any set of observations independent by tweaking the model you're fitting.
Comment: @RubenGeert the terminology _"(assumption of) independent observations"_ is dubious/ambiguous -- to say the least. Off the cuff, I would guess that it refers to drawing a [**random sample**](https://en.wikipedia.org/wiki/Simple_random_sample). However, the example you provide implicitly implies $ P(grade | teacher) \neq P(grade) $ to which you then add something about sampling?? Please consider rephrasing for clarity.
Comment: Gender may have the same kind of effect as a teacher in certain contexts. For instance, if you're looking at gender separated schools or societies where women are discriminated. In the latter case you can have a situation where women are not allowed to study past elementary school, then the grade will depend on the gender
Answer: In probability theory, statistical independence (which is not the same as causal independence) is defined as your property (3), but (1) follows as a consequence$\dagger$.  The events $\mathcal{A}$ and $\mathcal{B}$ are said to be statistically independent if and only if:
$$\mathbb{P}(\mathcal{A} \cap \mathcal{B}) = \mathbb{P}(\mathcal{A}) \cdot \mathbb{P}(\mathcal{B}) .$$
If $\mathbb{P}(\mathcal{B}) > 0$ then if follows that:
$$\mathbb{P}(\mathcal{A} |\mathcal{B}) = \frac{\mathbb{P}(\mathcal{A} \cap \mathcal{B})}{\mathbb{P}(\mathcal{B})} = \frac{\mathbb{P}(\mathcal{A})  \cdot \mathbb{P}(\mathcal{B})}{\mathbb{P}(\mathcal{B})} = \mathbb{P}(\mathcal{A}) .$$
This means that statistical independence implies that the occurrence of one event does not affect the probability of the other.  Another way of saying this is that the occurrence of one event should not change your beliefs about the other.  The concept of statistical independence is generally extended from events to random variables in a way that allows analogous statements to be made for random variables, including continuous random variables (which have zero probability of any particular outcome).  Treatment of independence for random variables basically involves the same definitions applied to distribution functions.

It is crucial to understand that independence is a very strong property - if events are statistically independent then (by definition) we cannot learn about one from observing the other.  For this reason, statistical models generally involve assumptions of conditional independence, given some underlying distribution or parameters.  The exact conceptual framework depends on whether one is using Bayesian methods or classical methods.  The former involves explicit dependence between observable values, while the latter involves a (complicated and subtle) implicit form of dependence.  Understanding this issue properly requires a bit of understanding of classical versus Bayesian statistics.
Statistical models will often say they use an assumption that sequences of random variables are "independent and identically distributed (IID)".  For example, you might have an observable sequence $X_1, X_2, X_3, ... \sim \text{IID N} (\mu, \sigma^2)$, which means that each observable random variable $X_i$ is normally distributed with mean $\mu$ and standard deviation $\sigma$.  Each of the random variables in the sequence is "independent" of the others in the sense that its outcome does not change the stated distribution of the other values.  In this kind of model we use the observed values of the sequence to estimate the parameters in the model, and we can then in turn predict unobserved values of the sequence.  This necessarily involves using some observed values to learn about others.
Bayesian statistics: Everything is conceptually simple.  Assume that $X_1, X_2, X_3, ... $ are conditionally IID given the parameters $\mu$ and $\sigma$, and treat those unknown parameters as random variables.  Given any non-degenerate prior distribution for these parameters, the values in the observable sequence are (unconditionally) dependent, generally with positive correlation.  Hence, it makes perfect sense that we use observed outcomes to predict later unobserved outcomes - they are conditionally independent, but unconditionally dependent.
Classical statistics: This is quite complicated and subtle.  Assume that $X_1, X_2, X_3, ... $ are IID given the parameters $\mu$ and $\sigma$, but treat those parameters as "unknown constants".  Since the parameters are treated as constants, there is no clear difference between conditional and unconditional independence in this case.  Nevertheless, we still use the observed values to estimate the parameters and make predictions of the unobserved values.  Hence, we use the observed outcomes to predict later unobserved outcomes even though they are notionally "independent" of each other.  This apparent incongruity is discussed in detail in O'Neill, B. (2009) Exchangeability, Correlation and Bayes' Effect.  International Statistical Review 77(2), pp. 241 - 250.

Applying this to your student grades data, you would probably model something like this by assuming that grade is conditionally independent given teacher_id.  You would use the data to make inferences about the grading distribution for each teacher (which would not be assumed to be the same) and this would allow you to make predictions about the unknown grade of another student.  Because the grade variable is used in the inference, it will affect your predictions of any unknown grade variable for another student.  Replacing teacher_id with gender does not change this; in either case you have a variable that you might use as a predictor of grade.
If you use Bayesian method you will have an explicit assumption of conditional independence and a prior distribution for the teachers' grade distributions, and this leads to unconditional (predictive) dependence of grades, allowing you to rationally use one grade in your prediction of another.  If you are using classical statistics you will have an assumption of independence (based on parameters that are "unknown constants") and you will use classical statistical prediction methods that allow you to use one grade to predict another.

$\dagger$ There are some foundational presentations of probability theory that define independence via the conditional probability statement and then give the joint probability statement as a consequence.  This is less common.
Comment: Statistical independence is very much what you describe in the first part of your answer. But your sentence "... if events are statistically independent then (by definition) we cannot learn about one from observing the other." is _blatantly_ wrong. The world is full of statistically independent but _similar_ events and random variables.
Comment: I was going to make a similar comment to that of @Alecos. The overall impression one gets is that you are asserting that observing one realization of a random variable tells us nothing about its distribution $F$, so that you cannot predict anything about a second independent realization. If this were the case, most of the theory of sampling and estimation would be impossible to develop. But you're correct in the sense that if we do know $F$ and observe one realization, that gives us no additional information about any other *independent* realization.
Comment: I think the issue here is that the standard IID model with distribution $F$ is implicitly using an assumption of *conditional* independence *given knowledge of $F$*.  Conditional on knowledge of $F$, the observations are independent, but unconditionally you have a situation where each observation gives information about $F$, which then affects your beliefs about the other observations.
Comment: The difficulty in this issue is that classical statistics treats the underlying distribution and parameters as "unknown constants" and therefore does not make any explicit distinction between conditional or unconditional independence, in this case.  In Bayesian statistics, it is all very simple.
Comment: Wouldn't "learning" mean changing our beliefs about a thing based on observation of another?  If so, doesn't independence (definitionally) preclude this?
Comment: Sorry, but I don't understand what that means.  Independence entails that we don't change what we know about one event based on observing the other.  What is "structural similarity" in this context?
Comment: Sorry, I am no longer sure what I meant. You do not discuss beliefs when presenting the frequentist perspective. Forget it.
Comment: The second definition does not follow from the first: simply for the fact that $ A | B $ is not a stand-alone set-theoretic expression. In fact, $ P(A | B) $ needs to be defined, then $ P(A | B) = P(A) $ can serve as a definition of independence and clearly $ P( A \cap B ) = P(A) P(B) $ follows. (treat $ P(B) = 0 $ separately). See also: [Axioms of Probability](https://en.wikipedia.org/wiki/Probability_axioms).
Comment: When I use a conditional probability expression, obviously I'm assuming that conditional probability has already been defined.  It's true that there are competing foundational presentations, some of which define independence by the joint probability equation, and some of which define it by conditional probability equations (though the first is the common treatment).  For questions like this, I prefer to give basic explanations that are helpful for someone with little understanding of the basics.
Comment: I have added a technical footnote to draw attention to the case you're talking about.
Comment: This is indeed one way to describe the word "learning". And who said that by observing two statistically independent events, we don't change what we know for the one due to observing the other? Again, statistical independence is unrelated to structural similarity.
Comment: It would help if this could be made more concrete & applied for a non-technical audience. Can you extend these points to clarify the OP's questions about how independence is violated in their example, & how teacher_id differs from sex.
Comment: I have added an additional section applying this reasoning to the student grades data raised by the questioner.  The implications of independence in classical statistics is inherently complicated and highly technical (like virtually all interpretation issues in classical statistics).
Comment: Does it make sense to talk about beliefs in frequentist statistics? I am not opposing any claims in particular, just questioning the wording.
Comment: @RichardHardy: Can you point out the particular sentence/assertion that concerns you?
Answer: The definitions of statistical independence that you give in your post are all essentially correct, but they don't get to the heart of the independence assumption in a statistical model.  To understand what we mean by the assumption of independent observations in a statistical model, it will be helpful to revisit what a statistical model is on a conceptual level.
Statistical models as approximations to "nature's dice"
Let's use a familiar example: we collect a random sample of adult humans (from a well-defined population--say, all adult humans on earth) and we measure their heights. We wish to estimate the population mean height of adult humans. To do this, we construct a simple statistical model by assuming that people's heights arise from a normal distribution.
Our model will be a good one if a normal distribution provides a good approximation to how nature "picks" heights for people. That is, if we simulate data under our normal model, does the resulting dataset closely resemble (in a statistical sense) what we observe in nature? In the context of our model, does our random-number generator provide a good simulation of the complicated stochastic process that nature uses to determine the heights of randomly selected human adults ("nature's dice")?
The independence assumption in a simple modeling context
When we assumed that we could approximate "nature's dice" by drawing random numbers from a normal distribution, we didn't mean that we would draw a single number from the normal distribution, and then assign that height to everybody. We meant that we would independently draw numbers for everybody from the same normal distribution. This is our independence assumption.
Imagine now that our sample of adults wasn't a random sample, but instead came from a handful of families. Tallness runs in some families, and shortness runs in others. We've already said that we're willing to assume that the heights of all adults come from one normal distribution. But sampling from the normal distribution wouldn't provide a dataset that looks much like our sample (our sample would show "clumps" of points, some short, others tall--each clump is a family). The heights of people in our sample are not independent draws from the overall normal distribution.
The independence assumption in a more complicated modeling context
But not all is lost! We might be able to write down a better model for our sample--one that preserves the independence of the heights. For example, we could write down a linear model where heights arise from a normal distribution with a mean that depends on what family the subject belongs to. In this context, the normal distribution describes the residual variation, AFTER we account for the influence of family. And independent samples from a normal distribution might be a good model for this residual variation.
Overall here, what we have done is to write down a more sophisticated model of how we expect nature's dice to behave in the context of our study. By writing down a good model, we might still be justified in assuming that that the random part of the model (i.e. the random variation around the family means) is independently sampled for each member of the population.
The (conditional) independence assumption in a general modeling context
In general, statistical models work by assuming that data arises from some probability distribution. The parameters of that distribution (like the mean of the normal distribution in the example above) might depend on covariates (like family in the example above). But of course endless variations are possible. The distribution might not be normal, the parameter that depends on covariates might not be the mean, the form of the dependence might not be linear, etc. ALL of these models rely on the assumption that they provide a reasonably good approximation to how nature's dice behave (again, that data simulated under the model will look statistically similar to actual data obtained by nature).
When we simulate data under the model, the final step will always be to draw a random number according to some modeled probability distribution. These are the draws that we assume to be independent of one another. The actual data that we get out might not look independent, because covariates or other features of the model might tell us to use different probability distributions for different draws (or sets of draws). But all of this information must be built into the model itself.  We are not allowed to let the random final number draw depend on what values we drew for other data points. Thus, the events that need to be independent are the rolls of "nature's dice" in the context of our model.
It is useful to refer to this situation as conditional independence, which means that the data points are independent of one another given (i.e. conditioned on) the covariates. In our height example, we assume my height and my brother's height conditioned on my family are independent of one another, and are also independent of your height and your sister's height conditioned on your family. Once we know somebody's family, we know what normal distribution to draw from to simulate their height, and the draws for different individuals are independent regardless of their family (even though our choice of what normal distribution to draw from depends on family).  It's also possible that even after dealing with the family structure of our data, we still don't achieve good conditional independence (maybe it's also important to model gender, for example).
Ultimately, whether it makes sense to assume conditional independence of observations is a decision that must be undertaken in the context of a particular model. This is why, for example, in linear regression, we don't check that the data come from a normal distribution, but we do check that the RESIDUALS come from a normal distribution (and from the SAME normal distribution across the full range of the data).  The linear regression assumes that, after accounting for the influence of covariates (the regression line), the data are independently sampled from a normal distribution, according to the strict definition of independence in the original post.
In the context of your example
"Teacher" in your data might be like "family" in the height example.
A final spin on it
Lots of familiar models assume that the residuals arise from a normal distribution.  Imagine I gave you some data that very clearly were NOT normal.  Maybe the're strongly skewed, or maybe they're bimodal.  And I told you "these data come from a normal distribution."
"No way," you say, "It's obvious that those aren' normal!"
"Who said anything about the data being normal?" I say. "I only said that they come from a normal distribution."
"One in the same!" you say. "We know that a histogram of reasonably large sample from a normal distribution will tend to look approximately normal!"
"But," I say, "I never said the data were independently sampled from the normal distribution.  The DO come from a normal distribution, but they aren't independent draws."
The assumption of (conditional) independence in statistical modeling is there to prevent smart-alecks like me from ignoring the distribution of the residuals and mis-applying the model.
Two final notes
1) The term "nature's dice" is not mine originally, but despite consulting a couple of references I can't figure out where I got it in this context.
2) Some statistical models (e.g. autoregressive models) do not require independence of observations in quite this way.  In particular, they allow the sampling distribution for a given observation to depend not only fixed covariates, but also on the data that came before it.
Comment: Thanks for this. I like that it is put in a very accessible way. You address the issue of how this plays out for the teacher, can you extend the discussion to also address the idea of sex as a covariate?
Answer: Let $\mathbb x=(X_1,...,X_j,...,X_k)$ by a $k-$dimensional random vector, i.e. a fixed-position collection of random variables (measurable real functions).
Consider many such vectors, say $n$, and index these vectors by $i=1,...,n$, so, say
$$\mathbb x_i=(X_{1i},...,X_{ji},...,X_{ki})$$ and regard them as a collection called "the sample", $S=(\mathbb x_1,...,\mathbb x_i,...,\mathbb x_n)$.  Then we call each $k-$ dimensional vector an "observation" (although it really becomes one only once we measure and record the realizations of the random variables involved ).
Let's first treat the case where either a probability mass function (PMF) or a probability density function (PDF) exists, and also, joint such functions. Denote by $f_i(\mathbb x_i),\;i=1,...,n$ the joint PMF or joint PDF  of each random vector, and $f(\mathbb x_1,...,\mathbb x_i,...,\mathbb x_n)$ the joint PMF or joint PDF of all these vectors together.
Then, the sample $S$ is called an "independent sample", if the following mathematical equality holds:
$$f(\mathbb x_1,...,\mathbb x_i,...,\mathbb x_n) = \prod_{i=1}^{n}f_i(\mathbb x_i),\;\;\; \forall (\mathbb x_1,...,\mathbb x_i,...,\mathbb x_n) \in D_S$$
where  $D_S$ is the joint domain created by the $n$ random vectors/observations.
This means that the "observations" are "jointly independent", (in the statistical sense, or "independent in probability" as was the old saying that is still seen today sometimes). The habit is to simply call them "independent observations".
Note that the statistical independence property here is over the index $i$, i.e. between observations. It is unrelated to what are the probabilistic/statistical relations between the random variables in each observation (in the general case we treat here where each observation is multidimensional).
Note also that in cases where we have continuous random variables with no densities, the above can be expressed in terms of the distribution functions.
This is what "independent observations" means. It is a precisely defined property expressed in mathematical terms. Let's see some of what it implies.
SOME CONSEQUENCES OF HAVING INDEPENDENT OBSERVATIONS
A. If two observations are part of a group of jointly independent observations, then they are also "pair-wise independent" (statistically),
$$f(\mathbb x_i,\mathbb x_m) = f_i(\mathbb x_i)f_m(\mathbb x_m)\;\;\; \forall i\neq m, \;\;\; i,m =1,...,n$$
This in turn implies that conditional PMF's/PDFs equal the "marginal" ones
$$f(\mathbb x_i \mid \mathbb x_m) = f_i(\mathbb x_i)\;\;\; \forall i\neq m, \;\;\; i,m =1,...,n$$
This generalizes to many arguments, conditioned or conditioning, say
$$f(\mathbb x_i , \mathbb x_{\ell}\mid \mathbb x_m) = f(\mathbb x_i , \mathbb x_{\ell}),\;\;\;\; f(\mathbb x_i \mid \mathbb x_m, \mathbb x_{\ell}) = f_i(\mathbb x_i)$$
etc, as long as the indexes to the left are different to the indexes on the right of the vertical line.
This implies that if we actually observe one observation, the probabilities characterizing any other observation of the sample do not change. So as regards prediction, an independent sample is not our best friend. We would prefer to have dependence so that each observation could help us say something more about any other observation.
B. On the other hand, an independent sample has maximum informational content. Every observation, being independent, carries information that cannot be inferred, wholly or partly, by any other observation in the sample. So the sum total is maximum, compared to any comparable sample where there exists some statistical dependence between some of the observations. But of what use is this information, if it cannot help us improve our predictions?
Well, this is indirect information about the probabilities that characterize the random variables in the sample. The more these observations have common characteristics (common probability distribution in our case), the more we are in a better position to uncover them, if our sample is independent.
In other words if the sample is independent and "identically distributed", meaning
$$f_i(\mathbb x_i) = f_m(\mathbb x_m) = f(\mathbb x),\;\;\; i\neq m$$
it is the best possible sample in order to obtain information about not only the common joint probability distribution $f(\mathbb x)$, but also for the marginal distributions of the random variables that comprise each observation, say $f_j(x_{ji})$.
So even though $f(\mathbb x_i \mid \mathbb x_m) = f_i(\mathbb x_i)$, so zero additional predictive power as regards the actual realization of $\mathbb x_i$, with an independent and identically distributed sample, we are in the best position to uncover the functions $f_i$ (or some of its properties), i.e. the marginal distributions.
Therefore, as regards estimation (which is sometimes used as a catch-all term, but here it should be kept distinct from the concept of prediction), an independent sample is our "best friend", if it is combined with the "identically distributed" property.
C. It also follows that an independent sample of observations where each is characterized by a totally different probability distribution, with no common characteristics whatsoever, is as worthless a collection of information as one can get (of course every piece of information on its own is worthy, the issue here is that taken together these cannot be combined to offer anything useful). Imagine a sample containing three  observations: one containing (quantitative characteristics of) fruits from South America, another containing mountains of Europe, and a third containing clothes from Asia. Pretty interesting information pieces all three of them -but together as a sample cannot do anything statistically useful for us.
Put in another way, a necessary and sufficient condition for an independent sample to be useful, is that the observations have some statistical characteristics in common. This is why, in Statistics, the word "sample" is not synonymous to "collection of information" in general, but to "collection of information on entities that have some common characteristics".
APPLICATION TO THE OP'S DATA EXAMPLE
Responding to a request from user @gung, let's examine the OP's example in light of the above.
We reasonably assume that we are in  a school with more than two teachers and more than six pupils. So
a) we are sampling both pupilss and teachers, and
b) we include in our data set the grade that corresponds to each teacher-pupil combination.
Namely, the grades are not "sampled", they are a consequence of the sampling we did on teachers and pupils. Therefore it is reasonable to treat the random variable $G$ (=grade) as the "dependent variable", while pupils ($P$) and teachers $T$ are "explanatory variables" (not all possible explanatory variables, just some).  Our sample consists of six observations which we write explicitly, $S = (\mathbb s_1, ..., \mathbb s_6)$ as
\begin{align}
\mathbb s_1 =(T_1, P_1, G_1) \\
\mathbb s_2 =(T_1, P_2, G_2) \\
\mathbb s_3 =(T_1, P_3, G_3) \\
\mathbb s_3 =(T_2, P_4, G_4) \\
\mathbb s_4 =(T_2, P_5, G_5) \\
\mathbb s_5 =(T_2, P_6, G_6) \\
\end{align}
Under the stated assumption "pupils do not influence each other", we can consider the $P_i$ variables as independently distributed.
Under a non-stated assumption that "all other factors" that may influence the Grade are independent of each other, we can also consider the $G_i$ variables to be independent of each other.
Finally under a non-stated assumption that teachers do not influence each other, we can consider the variables $T_1, T_2$ as statistically independent between them.
But irrespective of what causal/structural assumption we will make regarding the relation between teachers and pupils, the fact remains that observations $\mathbb s_1, \mathbb s_2, \mathbb s_3$ contain the same random variable ($T_1$), while observations $\mathbb s_4, \mathbb s_5, \mathbb s_6$ also contains the same random variable ($T_2$).
Note carefully the distinction between "the same random variable" and "two distinct random variables that have identical distributions".
So even if we assume that "teachers do NOT influence pupils", then still, our sample as defined above is not an independent sample, because $\mathbb s_1, \mathbb s_2, \mathbb s_3$ are statistically dependent through $T_1$, while $\mathbb s_4, \mathbb s_5, \mathbb s_6$ are statistically dependent through $T_2$.
Assume now that we exclude the random variable "teacher" from our sample. Is the (Pupil, Grade) sample of six observations, an independent sample?
Here, the assumptions we will make regarding what is the structural relationship between teachers, pupils, and grades does matter.
First, do teachers directly affect the random variable "Grade", through perhaps, different "grading attitudes/styles"? For example $T_1$ may be a "tough grader" while $T_2$ may be not.  In such a case "not seeing" the variable "Teacher" does not make the sample independent, because it is now the $G_1, G_2, G_3$ that are dependent, due to a common source of influence, $T_1$ (and analogously for the other three).
But say that teachers are identical in that respect. Then under the stated assumption "teachers influence students" we have again that the first three observations are dependent with each other, because teachers influence pupils who influence grades, and we arrive at the same result, albeit indirectly in this case (and likewise for the other three). So again, the sample is not independent.
THE CASE OF GENDER
Now, let's make the (Pupil, Grade) six-observation sample "conditionally independent with respect to teacher" (see other answers) by assuming that all six pupils have in reality the same teacher. But in addition let's include in the sample the random variable "$Ge$=Gender" that traditionally takes two values ($M,F$), while recently has started to take more. Our once again three-dimensional six-observation sample is now
\begin{align}
\mathbb s_1 =(Ge_1, P_1, G_1) \\
\mathbb s_2 =(Ge_2, P_2, G_2) \\
\mathbb s_3 =(Ge_3, P_3, G_3) \\
\mathbb s_3 =(Ge_4, P_4, G_4) \\
\mathbb s_4 =(Ge_5, P_5, G_5) \\
\mathbb s_5 =(Ge_6, P_6, G_6) \\
\end{align}
Note carefully that what we included in the description of the sample as regards Gender, is not the actual value that it takes for each pupil, but the random variable "Gender". Look back at the beginning of this very long answer: the Sample is not defined as a collection of numbers (or fixed numerical or not values in general), but as a collection of random variables (i.e. of functions).
Now, does the gender of one pupil influences (structurally or statistically) the gender of the another pupil? We could reasonably argue that it doesn't. So from that respect, the $Ge_i$ variables are independent. Does the gender of pupil $1$, $Ge_1$, affects in some other way directly some other pupil ($P_2, P_3,...$)? Hmm, there are battling educational theories if I recall on the matter. So if we assume that it does not, then off it goes another possible source of dependence between observations. Finally, does the gender of a pupil influence directly the grades of another pupil? if we argue  that it doesn't, we obtain an independent sample (conditional on all pupils having the same teacher).
Comment: @user106860 Yes that would make it. The difference in the two formulations is that in my answer I treated each actual human teacher as a different random variable, while in your formulation you treat each actual human teacher _as a realization_ of the random variable "teacher".
Comment: I do not agree in your point B. For some purposes, like estimating a mean, negative correlation is better than independence.
Comment: Better in the sense of reducing the variance
Comment: @kjetil Better in what sense?
Comment: It would help if you could connect this concretely to the OP's questions in the text. Given this, how do we understand that the listed observations are not independent? & how does leaving out teacher differ from leaving out sex?
Comment: @gung I included some elaboration along the lines you suggested.
Comment: You have repeated $G_2$s in place of $G_3, G_4, \dots$ in your sample lists.
Comment: Any thought's on @kjetilbhalvorsen's comment?
Comment: @AlecosPapadopoulos Could you elaborate further -- either mathematically or verbally --  on how dependence is violated by having multiple observations with the same teacher? My understanding is that it relies on where you say "Note carefully the distinction between "the same random variable" and "two distinct random variables that have identical distributions". **However, why is the same teacher appearing in multiple observations necessarily the same random variable as opposed to $T_1$ being the same realization of different (identically distributed) random variables??**
Comment: (continued) For example, what if the "Teacher" random variable can take on 3 values with equal probability. Then even if in all 6 observations the "teacher" random variable is a different random variable but identically distributed (with 3 possibilities), we will have multiple observations with the same teacher.
Comment: @user106860 When we map a real-world situation to abstract concepts, we must maintain some congruence between the two. Your example implies that we have an actual person, a teacher, that takes on three different "teaching personalities" or three different "teaching performances", and when paired with a specific student, the teacher takes on the same teaching personality for this specific student (but possibly different when paired to another student). This does not seem like a plausible real-world situation, if the students interact with the teacher in the same class. (CONTD)
Comment: @user106860 CONTD  But even if we consider one-to-one tutoring, I would find it hard to believe that across time, the teacher takes on the same "teaching personality" every time she tutors the same student.
Comment: @AlecosPapadopoulos I was not clear, sorry. Let me try again. Suppose we have a pool of 3 teachers (so 3 different people), 6 students, and students after some time get a grade. Suppose that each student is randomly assigned a teacher. Lets say this is done according to independent realizations of independent identically distributed random variables, $T_i$ (where say $T_i=k$ means assign teacher $k$. This could give us a data set similar to the one in the original question, in that at least one teacher will be observed multiple times
Comment: @AlecosPapadopoulos CONTD: I don't see how independence would be violated in this case. One teacher will appear multiple times, but one observation doesn't affect the probability of another observation. In math, denote observation$i$ -- corresponding to student $i$-- as $(T_i, G_i)$, $T_i$ is a random variable equally likely to be $1,2$ or $3$ , and $G_i$ is random variable for grade. Denote observation $j$ similarly. $T_i$ and $T_j$ may both $=1$, indicating the same teacher, but one observation doesn't affect the distribution of the other.
Comment: @AlecosPapadopoulos CONTD2: (As a side note: I elected not to represent pupil as a random variable in observation $i$, because I fail to see how that would work. If we have a random variable for pupil, and we don't allow a pupil to appear twice (i.e. a pupil can't have multiple grades/teachers), then i believe observations would have to be dependent, because if the first observation pertained to pupil $1$, then the distributions for the other observations could not put any mass on having pupil $=1$)
Comment: @AlecosPapadopoulos you mention that, even if we remove the teacher variable from our sample, and if we assume teachers directly affect grades, then $G_1,G_2,G_3$ are still dependent. How is the situation different when we make the observations conditionally independent? My guess is that with conditional independence we account for how the teacher variables affects grades, but if so does this require a parametric approach to analyzing the data?


Let $f$ be entire . Evaluate $\int ^{2\pi}_0 f(z_0+re^{i\theta)}e^{i\theta} d\theta$

Question: Let $f$ be entire . Evaluate $\int ^{2\pi}_0 f(z_0+re^{i\theta)}e^{i\theta} d\theta$
my attempt :  $z=z_0+re^{i\theta}$
$dz=rie^{i\theta }d\theta$  then
$\int ^{2\pi}_0 f(z_0+re^{i\theta)}e^{i\theta} d\theta=\int^{2\pi}_0 \frac{f(z)}{ir}dz$
how to processed for further
Answer: By the residue theorem or the Cauchy integral formula the answer is clearly zero, but you don't even need such results to be able to state it. Since $f$ is entire,
$$ f(z_0+z) = f(z_0) + f'(z_0)(z+z_0)+ f''(z_0)\frac{(z+z_0)^2}{2!}+\ldots $$
holds uniformly over any compact subset of the complex plane. It follows that we are allowed to replace $z$ with $r e^{i\theta}$, multiply both sides by $e^{i\theta}$ and perform a termwise integration over $(0,2\pi)$ with respect to $d\theta$. Since for any $n\in\mathbb{N}^+$ we have
$$\int_{0}^{2\pi} e^{ni\theta}\,d\theta = 0, $$
the conclusion is straightforward.
Answer: Hint: You made a mistake in your last integral. Letting $\gamma (t) = z_0 + re^{it}, t\in [0,2\pi],$ it should be
$$\frac{1}{ir}\int_\gamma f(z)\,dz.$$
Comment: @zhw...thanks what is answer
Comment: @zhw..is that answer 0
Comment: @rajendra  Why do you think $0$ might be the answer?
Comment: @Maths_Is_Fun.. i am figure out the answer
Comment: @Maths_Is_Fun.... can ou tell me wht is the answer
Comment: @rajendra;Since $f$ is entire so $\int _\gamma f=0$ by Cauchy-Goursat Theorem
Comment: Hence the answer is $0$
Comment: @Maths_Is_Fun..thank you for your help


SVM and kernels

Question: Suppose you are given a binary classification problem. How do you know that you have to map the problem into a higher dimensional space? In other words, how would you know that a linear SVM is not suitable for a problem? Would you look at the accuracy?
Answer: Mapping to higher dimensions is typically only helpful when working in relatively low-dimensional input spaces. In text mining, for instance, it doesn't help much since the input spaces are typically high dimensional ($\gt 100,000$ dimensions).
Basically, always try the linear kernel first and move on to more complex feature spaces if and only if you get insatisfactory results. Be aware that more complex kernels are no guarantee to a better model.
Answer: Based on my own experience with SVM, which in fact is limited mainly to financial market applications, I don't generally know what in advance what will be the best SVM kernel to use. Therefore I make a comparison test between linear, polynomial of varying degree, and RBF. For the work that I am doing, I find that linear, polynomial of low & odd degree, and RBF give good results, with 3rd order polynomial and RBF usually being the best, slightly ahead of linear.
There are a number of different possible metrics for ML quality that you can use based on the confusion matrix. Which metrics are preferred depends to some extent on the specific technical domain in which you are applying your SVM. Accuracy =  (TP+TN)/total is generally NOT the best metric to use. The combination of Sensitivity (Recall) = TPR = TP/(TP+FN) and  FPR = FP/(FP+TN) is what is conventionally plotted on the ROC chart. The combination of these is Informedness = TPR - FPR = distance from random, which you generally seek to maximize. The other unbiased metric is Markedness = Precision + FN/(TN+FN), which is essentially Precision corrected for bias associated with any imbalance between P & N in your input data. The geometric mean of Informedness and markedness is the Matthews correlation coefficient, defined as MCC = (TP*TN-FP*FN)/SQRT[(TP+FP)(TP+FN)(TN+FP)*(TN+FN)]. Other measures such as F1 score = 2*TP/(2*TP+FP+FN) which is commonly used in some applications, suffers from bias associated with input data. The Matthews CC avoids this problem.

SVM and kernels


Organic Groups D7 : How to get custom group list of login user?

Question: How to get logged in user group list in select box.
Need to help Please suggest me any one ?
Answer: You can use og_get_groups_by_user function.
<code>$current_user_groups = og_get_groups_by_user();
</code>


Intersecting a non-principal filter on $\Bbb Z$ with $\mathcal P(\Bbb N)$

Question: Does there exist a non-principal filter $\mathscr F$ on $\Bbb Z$ such that $\mathscr F \cap \mathcal P(\Bbb N)$ is principal?
Answer: I'll get you started.
Suppose that $\mathscr{F}$ is a filter on $\Bbb Z$ such that $\mathscr{F}\cap\wp(\Bbb N)$ is a principal filter on $\Bbb N$. Let $\mathscr{G}=\mathscr{F}\cap\wp(\Bbb N)$; then there is some non-empty $A\subseteq\Bbb N$ such that $\mathscr{G}=\{G\subseteq\Bbb N:A\subseteq F\}$. In particular, $A\in\mathscr{G}\subseteq\mathscr{F}$.
Let $F\in\mathscr{F}$ be arbitrary; then $\varnothing\ne F\cap A\in\mathscr{F}$. But $F\cap A\subseteq\Bbb N$, so $F\cap A\in\mathscr{F}\cap\wp(\Bbb N)=\mathscr{G}$, and therefore $A\subseteq F\cap A$, i.e., $F\cap A=A$. In other words, $F\supseteq A$ for each $F\in\mathscr{F}$. What can you now conclude about $\mathscr{F}$?
Comment: Out of curiosity, what's the rationale behind using the Weierstrass $\wp$ for power set?
Comment: @Lord_Farin: In handwriting I've always distinguished the power set P from all other uses of the letter, and $\wp$ is very close to the form that I do use for power set. $\mathscr{P}$ is a reasonable approximation to my script P, and $\mathcal{P}$ is an abomination. (I'm a little picky about these things: I'm out of practice, but I used to [do a fair bit of calligraphy](http://cleftlands.cwru.edu/archive/picture.asp?id=61).)
Comment: Thanks for your reply; nice calligraphy! I usually keep my letters straightforward since I'm not so gifted with the pencil. It already took some decent effort to have a consistent signature, and it took a few pages to find a nice way of writing an $\aleph$.


Custom module and template.tpl.php files

Question: I am just getting started with custom modules for my test site on my localhost. Is there a simple demonstration online where there is an example of using a mymodule.tpl.php files to render my content?
At the moment I have create a hook_menu() function also a function for the page call, all it does is return some text.
Answer: There are a lot of examples of use of the Drupal API for module developers in the Drupal documentation. In particular, you may find the Examples for Developers module handy, especially the "theming_example" sub-module. This is not an actually functional module, but just a container for a lot of example code that new developers can test, manipulate and learn from.
Answer: I know its too late to answer this now, but still could be helpful to many:
This is the best and exact to the point: http://www.nicklewis.org/drupal-hackers-cookbook/theming/hook_theme-and-template-files
Comment: This link is for Drupal 6


How to get a ComboBox in a DataGridViewCell to drop down after a single click?

Question: I have a DataGridView which has it's first column's style set to a ComboBox rather than the default TextBox. Since the number of rows in the DataGridView is not fixed on startup I cannot load in data to the ComboBoxes for each row when a new row is added. So I tried loading on the event of a user adding a row to the DataGridView:
public void myDataGridView_UserAddedRow(object sender, DataGridViewRowEventArgs e)
{
    // Identifiers used are:
    var myTableAdapter = new databaseTableAdapters.myTableTableAdapter();
    var myDataTable = myTableAdapter.GetData();
    int rowIndex = myDataGridView.CurrentcellAddress.Y;
    var comboBoxCell = (DataGridViewComboBoxCell)myDataGridView.Rows[rowIndex].Cells[0];
    string itemToAdd;

    // Load in the data from the data table
    foreach (System.Data.DataRow row in myDataTable.Rows)
    {
        // Get the current item to be added
        itemToAdd = row[0].ToString();
        // Make sure there are no duplicates
        if (!comboBoxCell.Items.Contains(itemToAdd))
        {
            comboBoxCell.Items.Add(itemToAdd)
        }
    }
}

but this only will allow the user to see the drop down options after a second click. I would like to be able to have the user only click on the combo box once and see the options rather than the less intuitive double click. How can this be done?
Comment: Have you looked at the `DataGridViewComboBoxColumn`? It seems redundant to keep adding the same values to each combo box cell when you can add them to a combo box column in one shot. You could do this before the data is loaded.
Comment: I will check that out, very interesting
Answer: The cell must gain focus for the drop down to occur, so the double click is actually a single click to gain focus on that cell and the second click is what causes the drop down to occur. So to see how to change focus following this link. I was able to modify the code with a single line of code
public void myDataGridView_UserAddedRow(object sender, DataGridViewRowEventArgs e)
{
    // Identifiers used are:
    var myTableAdapter = new databaseTableAdapters.myTableTableAdapter();
    var myDataTable = myTableAdapter.GetData();
    int rowIndex = myDataGridView.CurrentcellAddress.Y;
    var comboBoxCell = (DataGridViewComboBoxCell)myDataGridView.Rows[rowIndex].Cells[0];
    string itemToAdd;

    // Load in the data from the data table
    foreach (System.Data.DataRow row in myDataTable.Rows)
    {
        // Get the current item to be added
        itemToAdd = row[0].ToString();
        // Make sure there are no duplicates
        if (!comboBoxCell.Items.Contains(itemToAdd))
        {
            comboBoxCell.Items.Add(itemToAdd)
        }
    }
    // Send the focus to the next combo box (removes need for a double click)
    myDataGridView.CurrentCell = myDataGridView.Rows[rowIndex + 1].Cells[0]; // <--- HERE
}


inquality question

Question: I was just asked the following question(not on this website but by a friend):

$A = 2015x^2 + 2015y^2 + 6z^2$
$ B = 2(2012xy + 3yz + 3zx)$
Which is correct?

A > B

B > A

A = B

Relationship cannot be determined

I don't understand how you can compare the two unless it was in reference to something measurable like perimeter, area or volume.  So should the answer be relationship cannot be determined?
Comment: I can't see how you could conclude any of the relationships with the given information, so I would say you're right
Comment: Before you can write any of those, you need to tell us what **definition** of "<" you are using here.  There is no standard order on polynomials of several variables.
Answer: Presumably your friend wants you to show that $A\ge B$ for all real values $x,y,z$.  (Note, however, that "$A\ge B$" is not one of the options, just "$A\gt B$."  Also, your friend neglected to mention the "for all" business.) The inequality $A\ge B$ can be demonstrated by noting that
$$\begin{align}
0&\le2012(x-y)^2+3(y-z)^2+3(z-x)^2\\
&=2012(x^2-2xy+y^2)+3(y^2-2yz+z^2)+3(z^2-2zx+x^2)\\
&=(2015x^2+2015y^2+6z^2)-2(2012xy+3yz+3zx)\\
&=A-B
\end{align}$$
Answer: Edit : Method 2
The following expression is positive (sum of squares)
$$\frac{4027}{2}(x-y)^2+\frac{3}{2}(x+y-2z)^2$$
You can expand it and find it is equal to
$$\frac{4027}{2}(x^2+y^2) - 4027xy + \frac{3}{2}(x^2+y^2)+6z^2-6zx-6zy+3xy$$
$$ \frac{4030}{2}(x^2+y^2)-4024xy+6z^2-6zx-6zy$$
This is exactly equal to $A-B$. Hence $A\geq B$
Method 1:
Matrix of quadratic form $A-B$ is
$$\begin{pmatrix} 2015 & -2012 & -3 \\ -2012 & 2015 & -3 \\ -3 & -3 & 6\end{pmatrix}$$
It has eigenvalues $0$, $9$ and $4027$, that is to say positive. Hence $A>B$ (well actually $A\geq B$ because of $0$ eigenvalue) (matrix are symmetric)
Note 1 : writing $A>B$ makes perfect sense if $A$ and $B$ are real polynomials and if the inequality holds for all $x,y,z$. If $A$ and $B$ are symmetric matrixes, $A>B$ means $A-B$ is positive matrix.
Note 2 : if you are not familiar with quadratic forms, you can always write some equation such that $a x^2 + b y^2 + 2 c x y$ using expression $(x \quad y) \begin{pmatrix} a & c \\ c & b\end{pmatrix} (x\quad y)^T$ (same for 3 dimensions with 3x3 matrix). The polynomial is positive if the matrix in the middle is positive. Being positive for a symmetric matrix means all its eigenvalues are positive.

inquality question


add a char to a string in c

Question: I have this function called add_to_string and I call it from my main function to add a char to a string
add_to_string(name[I]);

it seems to me that I cannot append a char into a string. so how would I tackle this problem?
my main intention in this code is simply to print the entered name initials and avoid the user wrong entry (adding two spaces between first name and middle name)
here is my full code
#include<stdio.h>
#include<cs50.h>
#include<string.h>

string add_to_string (char letter);
string result;

int main (void)
{
    printf("pleas enter your full name:  ");
    string name = get_string();
    int len = strlen(name);
    for (int i = 0; i < len; i++)
        {
            if (i == 0)
            {
                add_to_string(name[i]);
            } else if (name[i] == ' ')
            {
                if (name[i + 1] != ' ')
                {
                add_to_string(name[i]);
                }
            }
    }

    printf("%s\n",result);
}

string add_to_string (char letter)
{

    strncat(result, letter, 30);
    return result;
}

Comment: Compile with all warnings enabled... You have several misuses and type errors that any decent compiler will highlight right away.
Comment: e.g. [man strncat](https://linux.die.net/man/3/strncat): `char *strncat(char *dest, const char *src, size_t n);`. What is the type of the second param and what is the type you gave it?
Comment: If you need to add a single character, cheat. Plase it in an array of length 2, the character itself being at index 0, and the `'\0'` being at index 1, and pass that to the function.
Comment: I don't really get what you meant, but I suppose you mean the string and get_string() ,, this is a class am taking and they provide us with this cs50 header that include these types and functions
Comment: this is my entire question haha , I know it expect a string, but what if I have to add char? what would I do?
Comment: What kaylum said for one. My problem with cs50 is that they foster this approach of typdefing for no real useful abstraction. You would have learned far more by simply knowing you are working with `char*` than `string`.
Comment: You can't give single character like that, really. C lets you pass `char`, it does a not very useful conversion, and your program has a hidden error that you now languish over.
Comment: Another big problem is that `string result;` declares a `NULL` pointer. You can't access that pointer. You need to allocate memory for it first.
Comment: `typedef char * string;`. Everyone can do that. This `string` type is really misleading.
Comment: To expand on @Jean-FrançoisFabre's comment, a "string" is by definition "a contiguous sequence of characters terminated by and including the first null character". A pointer of type `char*` may or may not *point* to a string (i.e., point to its initial character), but it cannot *be* a string. I understand that you're stuck with this typedef, because it's provided by ``, but be aware that it's misleading.
Comment: thank you guys,, after a little of research I found out what you mean, cuz at first I didn't study what a pointer is, so I got so confused with of what you were saying
Answer: i am not sure what string is here but I assume it is a typedef for char*
Your function
string add_to_string (char letter)
{
  strncat(result, letter, 30);
  return result;
}

is wrong in several ways,
first result is a global variable so initially it is pointing to NULL.
you need to allocate storage for your string and let result point to that storage or declare result as an array
char result[128]; // assuming here it is still global otherwise initialize

The function add_to_string adds a character to the string but you call strncat which expects two strings as arguments plus a size.
Instead append the character like this
size_t len = strlen(result)
result[ len++ ] = letter;
result[ len ] = '\0';

This keeps result a string

add a char to a string in c


connectivitymanager.getActiveNetworkInfo() returning true when Internet is off (Android)?

Question: This is the code I am using to determine if the phone is connected to the Internet:
public boolean isOnline() {
    ConnectivityManager cm =
        (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    }
    return false;
}

On an emulator, this is returning true even when I turn my computer's Wi-Fi off. I see a 3G sign on the topmost bar of the emulator, even when the computer is off the Internet. Is there something wrong with my code, or is this an emulator problem?
Comment: There's an airplane mode in emulator (I guess). Turn it off and the method should return `false`
Answer: You should call isConnected instead of isConnectedOrConnecting if you want to determine whether the device is connected at the time of call to isOnline.
Generally, there are many problems/bugs with hardware-features APIs on the emulator, this might be one of them. Your code is fine.
Comment: It works on my Galaxy S2 as expected: `isOnline` returns true when the device is either on WiFi or the cellular network, and `false` when none of them.
Comment: Can you confirm this code will work on a real device? Thanks.
Comment: Yes, I'll try to run it on my device.


Does this function execute : jQuery(".class").function(); if the class is not found on this page?

Question: Just a quick question.
I'm wondering if in the following code if unslider() will run if there is no .banner class on the page?

jQuery(".banner").unslider();

I do not want it to run on pages where there is no .banner class.
Do I need to do something like

if (jQuery(".banner") > 0){
   jQuery(".banner").unslider();
  }
Answer: Yes, it runs and executes the following (source):
$.fn.unslider = function(o) {
    var len = this.length;

    //  Enable multiple-slider support
    return this.each(function(index) {
        //  Cache a copy of $(this), so it
        var me = $(this);
        var instance = (new Unslider).init(me, o);

        //  Invoke an Unslider instance
        me.data('unslider' + (len > 1 ? '-' + (index + 1) : ''), instance);
    });
};

So it does a .each() on your collection.
However, if that collection is empty, the function passed to .each() will not run and therefore "not much" would describe best what would happen if you run $('.banner').unslider();
Btw, it wouldn't make sense to try and "optimize" this by doing a .length check unless you're certain that the call will be heavy.
Answer: No, it will not get executed if the element is not found.
The plugin method will get called, but since there are no element matching the selector it should not be doing anyting - but it again depends on how the plugin is implemented
Answer: Normally the follow up actions wont get executed if the class is not available, but doing a preliminary check will be safer one.
You have to like this,
if(jQuery(".banner").length > 0){ jQuery(".banner").unslider(); }

Or
if(jQuery(".banner").length){ jQuery(".banner").unslider(); }

Comment: The last condition makes no sense, because all objects are considered truthy in an expression.
Comment: @Jack I thought it would return undefined. Thanks for a new info. But i just want to return what it will return in that context.? Thanks.!
Comment: It returns an empty set, or empty array if you will; but even an empty array is still considered truthy.
Answer: You need to use the length property to check if element exists.
if (jQuery(".banner").length > 0)
{
   jQuery(".banner").unslider();
}

You even do not need to check if it is greater then zero.
if (jQuery(".banner").length)
{
   jQuery(".banner").unslider();
}


Is SNA DLC traffic compatible?

Question: My question involves the compatibility the with SNA DLC traffic. In the pass with ESX 3.5 an incident had been logged with this protocol.
Here are the links of this problem:
http://communities.vmware.com/message/823536#823536
http://communities.vmware.com/message/953976#953976
Is this incident resoled with ESX4 and VSphere 4 , will I have any problems if I migration my VMware 3.5 to 4?
Thank you
Comment: Good question (for old timers like me anyway :) ) but I don't know the answer sorry.
Answer: According to the community post, it may be fixed as of 3.5u1:
http://kb.vmware.com/kb/1003696
"7. Fixes a network connectivity issue where packets with an 802.2LLC header (without SubNetwork Access Protocol (SNAP)) are dropped by the vmxnet driver in ESX Server 3.5. This issue has been observed with NetBEUI and SNA/DLC protocols."
I would imagine the fix carries on through all version after 3.5u1.

Is SNA DLC traffic compatible?


Erro na instalação do Visual Studio 2015

Question: Sempre que estou tentando instalar o visual studio 2015 no meu notebook, aparece o seguinte erro :

alguem saberia como resolver ??
Comment: Você precisa realmente utilizar o VS2015? Se não sugiro começar com o mais atualizado que é o VS2017 Community: https://www.visualstudio.com/downloads/?rr=https%3A%2F%2Fwww.google.com.br%2F
Comment: sim, precisa ser a 2015 ... preciso resolver esse erro, mudar a versao da ide não ta em cogitação
Comment: Teria como entrar no log que ele sugere e colocar aqui o conteúdo?
Answer: Após pesquisar um pouco verifiquei que o instalador pode ter feito confusão na hora de instalar bibliotecas x86 e x64. Há algumas formas de se resolver o problema, vou citar duas:
1ª opção
1. Após o erro na instalação, feche o instalador.
2. Entre no painel de controle e depois nos programas instalados.
3. Repare todos os Microsoft Visual Redistributable, tanto a versão x86 quanto a x64.

A imagem acima representa os que eu tenho instalado. Pode ser que você não tenha a mesma quantidade ou tenha outros nomes. Repare todos que tenham Microsoft Visual Redistributable no nome. Sim, isso pode levar um tempo para ser concluído.
4. Execute o instalador do Visual Studio.
2ª opção
1. Desinstale completamente o Visual Studio 2015 do seu computador.
2. Desinstale todos os Microsoft Visual Redistributable, tanto a versão x86 quanto a x64.
3. Reinicie o computador.
4. Manualmente delete as dlls que possam ter ficado no computador de ambas as pastas system32 e SysWOW64 (os nomes das dlls acabam com *140.dll - tenha cuidado e faça um backup antes!)
5. Faça o download do "Microsoft Visual C++ 2015 Redistributable Update 3" desse link - https://www.microsoft.com/en-us/download/confirmation.aspx?id=53840 - ambas as versões x86 e x64.
6. Instale o "Microsoft Visual C++ 2015 Redistributable Update 3" - ambas as versões x64 and x86.
7. Reinicie o computador.
8. Execute o instalador do Visual Studio 2015.


d3 with Vue - this.ownerDocument is undefined

Question: I am trying to integrate d3 charts with Vue.  Using a ref seems to give an error, but that's the way to do it right?
<template>

</template>

const chart = ref(null);

onMounted(() => {

  const chartContainer = d3.select(chart);

  const margin = { top: 20, right: 20, bottom: 30, left: 50 };
  const width = chartContainer.offsetWidth - margin.left - margin.right;
  const height = chartContainer.offsetHeight - margin.top - margin.bottom;

  const svg = chartContainer
    .append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform",`translate(${margin.left},${margin.top})`);
});

I am getting this error:
Uncaught (in promise) TypeError: this.ownerDocument is undefined

Answer: Try d3.selectAll instead of d3.select
If that doesn't work, more tips here:
https://stackoverflow.com/a/49696538/7549483


Find vectors whose components do not change signs under a linear transformation

Question: I have a vector space with vectors whose components can take only integer values. I also have a symmetric square binary matrix A that can act on these vectors. I am interested in finding all vectors ${\bf x}$ whose components lie in the set $\{-1, 0, 1\}$ and such that the signs of all the components of the vector ${\bf y=Ax}$ are same as the signs of the corresponding components of the vector ${\bf x}$. I initially thought that these vectors would like in the subspace spanned by the eigenvectors of ${\bf A}$ with positive eigenvalues. But that doesn't seem to be correct to me now. Is there any way to find out these vectors?
Edit: After thinking over the comments, I think I did not ask the question correctly. So here it goes. I am working in a special basis with the basis vectors given as $(1, 0, 0,\cdots, 0), (0, 1, 0, \cdots, 0), \cdots, (0, 0, \cdots, 0, 1)$. In this basis, I am demanding that the components of my vectors must be integers and they, in general, won't be so in a different basis. Now, I want those vectors for which the components don't change signs in this basis.
Comment: A detail: if the component can only be integer than your vector space is not a vector space, but a [$\mathbb Z$-module](https://en.wikipedia.org/wiki/Module_(mathematics)). I don't think that this can substantially help you, though.
Comment: The eigenvectors and values are independent of the basis but the sign changes induced by the transformation depend on which basis you've chosen. Any method used to find such values should be done relative to the basis given to account for this.
Comment: Are you looking for a fast algorithm to compute these vectors or some theoretical insight?
Comment: What are the scalars? Where does $A$ live? The problem is a little underspecified as is.
Comment: I have added some corrections now. Thanks for pointing those out.
Answer: Maybe this answer is tautological or I did not understand the question correctly but here it goes:
So $A \in \{0,1\}^{n\times n}$ and $x \in \{ -1,0,1\}^n$ and it should hold for all $i \in \{1,\dots,n\}$ that
$$
\text{sgn}((Ax)_i) = x_i.
$$
This is the case if for all $i$ where $x_i \neq 0$ if
$$
\lvert \{j: a_{ij} = 1 \land x_j = x_i \} \rvert > \lvert \{j: a_{ij} = 1 \land x_j = - x_i \} \rvert
$$
and for all $i$ where $x_i = 0$ if
$$
\lvert \{j: a_{ij} = 1 \land x_j = -1 \} \rvert = \lvert \{j: a_{ij} = 1 \land x_j = +1 \} \rvert.
$$
This is easy to see. Consider the the case $x_i \neq 0$, then
$$
(Ax)_i = \sum_j a_{ij}x_j = \sum_{\{j:a_{ij} = 1 \land x_j = x_i\} } a_{ij}x_j + \sum_{\{j:a_{ij} = 1 \land x_j = - x_i\} } a_{ij}x_j \\ = \sum_{\{j:a_{ij} = 1 \land x_j = x_i\} } x_i + \sum_{\{j:a_{ij} = 1 \land x_j = - x_i\} } -x_i.
$$
The case $x_i = 0$ can be checked in the same way.
Answer: I can provide you just a starting hint.
Consider the 2D case.
All the possible vectors $\bf x$ will thus lay on the axes ($(1,0)$, etc.) and on the diagonals ($(1,1)$, etc.)
of a square of side $2$ centered at the origin.
For our purpose, we can also consider the corresponding points, obtained by moving the original ones
along the ray from the origin, until bringing them on the unit circle ($(0,1),\, (\sqrt{2}/2,\sqrt{2}/2),\cdots$),
i.e placed at multiples of $\pi /4$.
Now the action of any matrix on the set of points on the circle will consist, by the SVD decomposition, into
a rotation, a stretch and a further rotation, with the final result that they will lay on an ellipse.
If the matrix is diagonal, its action will be a stretch, and all the points will preserve the sign
of each of their coordinates.
If the matrix is just a rotation, the coordinates with a null value will loose their sign, while the others
will preserve it if the angle of rotation is less than $\pi/4$ in absolute value.
So we can pass from SVD to the Polar decomposition
and consider only the rotation given by the unitary component.
The fact that the matrices you are considering be binary seems to me not to simplify the process.
And passing to higher dimensions, to discern which components will preserve their sign under a rotation does look
to be a complicated process in general.


@(at) syntax can't render in controller to view yajra datatables

Question: i write @ syntax in addcolumn on return datatables, but @ syntax can't render in blade template, @ syntax only plaintext. how i can render @ syntax?

this my code:
http://pastebin.com/Sc2eG6us
can any help me? thank you before
Answer: Do it the other way around, add the columns only if they have the permissions.
$postsDataTable = Datatables::of($posts);

$actionButton = '';
if(\Entrust::can('pengguna-view')){
   $actionButton = '<button name="button-drop" class="lihat-data btn-sm btn btn-default "
       data-id="'.$datas->id.'"
       data-username="'.$datas->username.'"
       data-attribute="'.$datas->attribute.'"
       data-op="'.$datas->op.'"
       data-value="'.$datas->value.'"
       data-barcode="'.$datas->barcode.'"
       data-flag="'.$datas->flag.'"
       data-dismiss="modal">
        Lihat
     </button>';
}

   $postsDataTable = $postsDataTable->addColumn('action',function($datas) use ($actionButton) {
      return $actionButton;
  });
}

return $postsDataTable->make(true);

Comment: Try change `if($user->can(''))` to `if(\Entrust::can('pengguna-view'))`
Comment: @muzamilindra code updated, datatable is complaning about displaying content for the column 'action' but we didn't pass anything to it, so I'm passing an empty string to it if the user doesn't have permission for 'pengguna-view' and add the button if user has permission.
Comment: i ask variable $user from where?
my entrust before editing from table user to table radcheck
Comment: i got notice error if no any data in action coloumn...
"DataTables warning: table id=tabelrad - Requested unknown parameter 'action' for row 0, column 4. For more information about this error, please see http://datatables.net/tn/4"

but accordance with the previlleges
Comment: SOLVED Thank you very much


Series expansion of incomplete gamma function ratio

Question: I am interested in the series expansion of:
$$S(k)=\frac{\Gamma(k+1,a)}{k!},$$
around $k=\infty$ where $\Gamma(x,z)$ is the incomplete gamma function and $a$ is some positive constant.  In particular, I would like to know how quickly this ratio converges to 1.
How to prove asymptotic limit of an incomplete Gamma function shows that:
$$1-S(k)\leq \left(\frac{e^a-1}{e^a}\right)^{k+1},$$
but is it possible to make this any tighter?
Answer: If we start with a little rearranging,
$$
\begin{align}
\frac{\Gamma(k+1,a)}{k!} &= \frac{1}{k!} \int_a^\infty t^k e^{-t}\,dt \\
&= \frac{1}{k!} \left( \int_0^\infty t^k e^{-t}\,dt - \int_0^a t^k e^{-t}\,dt \right) \\
&= 1 - \frac{1}{k}\int_0^a t^k e^{-t}\,dt,
\end{align}
$$
then make the change of variables $t = ae^{-s}$, we end up with
$$
1 - \frac{\Gamma(k+1,a)}{k!} = \frac{a^{k+1}}{k!} \int_0^\infty e^{-ks} \exp\{-s-ae^{-s}\}\,ds.
$$
If we expand
$$
\begin{align}
\exp\{-s-ae^{-s}\} &= \sum_{n=0}^{\infty} c_n s^n \\
&= e^{-a} + e^{-a}(a-1) s + \tfrac{1}{2} e^{-a} (a^2-3a+1) s^2 + \cdots
\end{align}
$$
then by Watson's lemma we can exchange the order of integration and summation to obtain an asymptotic series for the integral;
$$
\begin{align}
1 - \frac{\Gamma(k+1,a)}{k!} &\approx \frac{a^{k+1}}{k!} \sum_{n=0}^{\infty} c_n \int_0^\infty e^{-ks} s^n \,ds \\
&= \frac{a^{k+1}}{k!} \sum_{n=0}^{\infty} \frac{n! c_n}{k^{n+1}} \\
&= \frac{a^{k+1} e^{-a}}{k \cdot k!} \left(1 + \frac{a-1}{k} + \frac{a^2 - 3a + 1}{k^2} + \cdots \right).
\end{align}
$$
In particular, to first order we have
$$
1 - \frac{\Gamma(k+1,a)}{k!} \sim \frac{a^{k+1} e^{-a}}{k \cdot k!}.
$$
Answer: Using a CAS, what it found as expansion for large values of $k$ is $$S(k)=\frac{\Gamma(k+1,a)}{k!}\simeq 1-\frac{ a^{k+1} e^{k \left(\log
   \left(\frac{1}{k}\right)+1\right)-a}}{\sqrt{2 \pi }k^{3/2}}$$ I hope this could be of some help.
Comment: Can you show how you did this with CAS?


Nginx location blocks don't apply to .php files inside them?

Question: So to help prevent brute force attacks against my phpmyadmin install I've configured nginx to require HTTP Basic Auth (extra username and password) and then the requests need to come from a whitelisted IP Address. However the IP Address whitelist works fine if I run https://example.com/phpmyadmin/ however without adding the extra .php block I could load https://example.com/phpmyadmin/index.php without my IP being whitelisted. This issue doesn't affect the HTTP Basic Auth. Is there a reason this happens? Anyway to get around having to add extra .php blocks? A copy of the config area for phpmyadmin is below.
# Setup and secure phpMyAdmin
location /phpmyadmin/ {
  allow 188.8.131.52;
  deny all;
  auth_basic "phpMyAdmin - HTTP Basic Login";
      auth_basic_user_file /etc/nginx/pma_pass;
    location ~ \.php$ {
    include snippets/fastcgi-php.conf;
            fastcgi_pass unix:/run/php/php7.0-fpm.sock;
    allow 184.108.40.206;
    deny all;
    }
}

Answer: In most PHP configurations, there is one location ~ \.php$ block that processes any URI that ends with .php, so adding restrictions to other location blocks will only affect the static files involved. See this document for more.
The cleanest solution is to use a prefix location with the ^~ modifier, which ensures that all URIs that begin with /phpmyadmin/ are processed by that block, and other locations at the top level do not bypass your security. See this document for more.
As you have discovered, you will need to add a nested location to handle PHP within that block, but the authentication statements should all be inherited and do not need to be repeated within the inner block.
For example:
location ^~ /phpmyadmin/ {
    allow 188.8.131.52;
    deny all;
    auth_basic "phpMyAdmin - HTTP Basic Login";
    auth_basic_user_file /etc/nginx/pma_pass;

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php7.0-fpm.sock;
    }
}


db_update add value to field

Question: I want use db_update to update a field,instead of update a field with new value (replace) , I want add a value to last value,
I know I can do it with mysql command
UPDATE `databasename`.`tablename` SET fieldB = fieldB + 1 WHERE fieldA='2';

but I use below code, It is not add to credit field, only replace it with $credit value,
anybody know where is my problem and how can I achieve this job?
$cr_update_no = db_update('rah_cc_credit') // Table name no longer needs {}
                ->fields(array('uid' => $user->uid,'update_date'=>REQUEST_TIME,'last_code'=>$code ,'credit' => 'credit'+ $credit))
                ->condition('uid', $user->uid, '=')
                ->execute();

Comment: @Jimajamma no , It +1 to pervious value, how can I add $credit to it??  'credit+ $credit' will not work
Comment: you can put anything in there instead of 1, see http://drupal.stackexchange.com/questions/4764/update-query-with-a-dynamic-expression-in-drupal-7, I only linked the first q&a in because your static query used 1.
Comment: @Jimajamma you say my answer is  ` db_update('rah_cc_credit') // Table name no longer needs {}
                ->fields(array('uid' => $user->uid,'update_date'=>REQUEST_TIME,'last_code'=>$code )
    ->expression('credit', 'credit + :amount', array(':amount' => $credit))
                ->condition('uid', $user->uid, '=')
                ->execute();` ?
Comment: that's what the various docs say should do it, yes; I haven't a testbed to debug it exactly here
Answer: The problem is way I used to update,
for this job drupal has syntax, according to  Update query with a dynamic expression in Drupal 7?
I found my solution
$cr_update_no= db_update('rah_cc_credit') // Table name no longer needs {}
                ->fields(array('uid' => $user->uid,'update_date'=>REQUEST_TIME,'last_code'=>$code ))
                ->expression('credit', 'credit + :amount', array(':amount' => $credit))
                ->condition('uid', $user->uid, '=')
                ->execute();

I submit this answer maybe helpful for another in future.

db_update add value to field


I need help correcting a misunderstanding about confidence intervals.

Question: My professor was trying to explain something to me about confidence interval and I haven't been able to understand it.
There is a statement I think is true that she says is false. I can't understand why it is false.
The situation is that the (107.8, 116.2) is a 95% confidence interval for a mean statistic.
The statement is:

There is a 95% probability that the interval from 107.8 to 116.2 contains μ

My statistics professor says that the statement is false because the probability is either 0 or 1.
However, I am fairly sure that the statement is true considering that the definition of probability is:

the extent to which an event is likely to occur, measured by the ratio
  of the favorable cases to the whole number of cases possible.

My statistics professor has tried to explain to me her point but I have not understood it yet.
We did both agree that the following statement is true

This interval was constructed using a method that produces intervals
  that capture the true mean in 95% of all possible samples

I am fairly sure this statement says exactly the same thing as the first statement does. What am I missing?
Comment: That your professor is a frequentist.
Comment: Can you please explain that further?
Answer: The typical interpretation of confidence intervals goes something like this:
Let's say I have a statistic $\xi$ and I have decided upon an experiment to create a confidence interval. A 95% CI means that if I repeated the experiment over and over and over (infinitely many times) 95% of the time the CI I generated would contain $\xi$. Now, $\xi$ is a fixed number. So for any fixed interval, the interval either contains or does not contain $\xi$. This is what your teacher means.
Does this make sense, or should I give it another go?
----EDIT-----
Additionally, if we have a 95% confidence interval, and $\xi$ is outside the interval, we can interpret the sampling event (the collection of data used to make the CI) to have had a probability of 5% (or less). In this sense, it is the sampling event that was "rare."
Comment: Because given the fixed interval there isn't a 95% probability that the value is contained in the interval. Before the sampling (collection of data) has occurred, we know that we will generate an interval that contains the value with a probability of 0.95. The issue is you shouldn't think about the mean as the random variable, but rather the interval is random (or more precisely, probabilistic). Therefore, once we have fixed the interval, we have already realized a value of the random quantity.
Comment: Why does that invalidate saying there is a 95% probability. I agree it either is or isnt but lets say we set out a physical number line on the ground and dropped a penny randomly there would be a non 0 or 1 chance that the penny would land on the line on the ground right?
Comment: Thankyou! That makes sense!


Apparent violation of fundamental theorem of ODEs, how to resolve?

Question: Consider, in the $(x, y)$-plane, the family of curves given by $y = (x - c)^3$, for the various possible values of the number $c$. Denote by $v$ the unit vector field everywhere tangent to this family of curves. Then it would seem that there are two integral curves of this $v$ beginning at the origin, namely, the one that goes along the $x$-axis, and the one that goes along the curve $y = x^4$. Thus, we apparently have a violation of the fundamental theorem of ordinary differential equations. How do we resolve this?
Comment: Field is singular on the x-axis.  Uniqueness assumes nonsingularity.
Answer: The curve through the point $(x_0, y_0)$ has$$c = x_0 - y_0^{1/3}.$$Its tangent vector at this point is$$\left(1, 3(x_0 - c)^2\right) = \left(1, 3y_0^{2/3}\right).$$But the unit vector field given by$$v^x = 1, \quad v^y = 3y^{2/3}$$is not smooth; and unitizing it is not going to make it smooth. Nonuniqueness of integral curves of this nonsmooth vector field does not violate the fundamental theorem of ordinary differential equations.
Remark. This is a trick question I am fond of. The first thing to do is draw these curves in the plane, just to see that there is a real issue here. It all looks so innocent. Everything in sight is smooth, and there is no reason to believe that the final vector field will not be smooth. I think the key to getting this problem is to really believe in your heart that the fundamental theorem of ordinary differential equations is true. Faced with this belief, and your diagram, there should be a real puzzle. Finally, out of pure frustration, you say the following.

OK, I am just going to write out explicitly what this vector field is.

Once you get to that point, you are in good shape. But you must actually write down the vector field, i.e. say exactly what its components are at each point. No $c$'s are allowed here! When you do so you discover, lo and behold, that is not smooth.
And this example illustrates, existence and uniqueness of integral curves fails in general for a vector field that is merely continuous, as this one is. So how nice, you might ask, must a vector field be to guarantee existence and uniqueness of integral curves? It turns out that $C^1$ is plenty good enough. In fact, there is a condition that is weaker than $C^1$ but stronger than $C^0$ that still suffices. It is that, in any local neighborhood, there be a number $a$ such that$$\left|\vec{v}(\vec{x}) - \vec{v}(\vec{x}')\right| \le a\left|\vec{x} - \vec{x}'\right|.$$This is called a local Lipschitz condition.


Why Cassandra doesn't let to query clustering key by IN restriction?

Question: Does anyone know why I cannot use query where I restrict clustering column by IN and I select collection column?
Let me elaborate on that. Let's say I have data model similar to the following:
create table inventory (
                sku text,
                class text,
                unit text,
                node text,
                supply map<text, frozen<delta_and_time>>,
                supply_compacted int,
                primary key ((sku, class, unit), node));

when I try to use following select statement:
select sku, class, unit, node, supply_compacted where sku = '0'
           and class = 'good' and unit = 'each' and node in ('1', '2', '3')

everything is fine. But when I try to select * with the same restrictions I get follow
ing error:
Cannot restrict clustering columns by IN relations when a collection is selected by the query

I tried to find out why there is such restriction in C* but I couldn't find anything. Also I looked into the code but there is no information why such check is performed.
Does anyone know what is the reason of such restriction?
Answer: This is a limitation based on how Collection Data types were "hacked" into the existing storage engine. A Map collection is implemented by storing each key as a unique column name in the same area as the clustering column. Thus making it difficult for Cassandra to efficiently do an "IN" operation especially for large collection sizes for each "row".
However I do feel that you could re-work your data model to get around this limitation and not even use a Collection type (since they have many issues associated with them if your are not careful). It looks like "supply_compacted" could be a roll up of the total inventory within the supply map? If so you could do the following:
create table inventory (
  sku text,
  class text,
  unit text,
  node text,
  supply_compacted int static, -- stored once, total amount of inventory across all nodes
  supply frozen<delta_and_time>,
  primary key ((sku, class, unit), node)
);

Comment: That is the most bizarre limitation I have seen so far in a technology...
Comment: could you elaborate more on the `same area as the clustering column`?
Answer: My original thought is that the constraint is due to the impact on the memory and the network to get collections, since multiple collections can be returned at once with the in restriction. However, I found that the query is working if it's less restricted by only specifying the partition key.
My test data (on Cassandra 3.7):
cqlsh:test> create table mytable(X text, Y text, Z text, mylist list<int>, primary key (X,Y));
cqlsh:test> insert into mytable (X,Y,Z,mylist) values('x','y1','z1',[1,2,3]);
cqlsh:test> insert into mytable (X,Y,Z,mylist) values('x','y2','z2',[4,5,6]);
cqlsh:test> select x,y,z from mytable where x = 'x' and y in ('y1');

 x | y  | z
---+----+----
 x | y1 | z1

(1 rows)
cqlsh:test> select * from mytable where x = 'x' and y in ('y1');
InvalidRequest: Error from server: code=2200 [Invalid query] message="Cannot restrict clustering columns by IN relations when a collection is selected by the query"
cqlsh:test> select * from mytable where x = 'x';

 x | y  | mylist    | z
---+----+-----------+----
 x | y1 | [1, 2, 3] | z1
 x | y2 | [4, 5, 6] | z2

(2 rows)

The underlying sstable dump:
$ sstabledump mb-1-big-Data.db
[
  {
    "partition" : {
      "key" : [ "x" ],
      "position" : 0
    },
    "rows" : [
      {
        "type" : "row",
        "position" : 15,
        "clustering" : [ "y1" ],
        "liveness_info" : { "tstamp" : "2016-09-13T08:14:33.172799Z" },
        "cells" : [
          { "name" : "z", "value" : "z1" },
          { "name" : "mylist", "deletion_info" : { "marked_deleted" : "2016-09-13T08:14:33.172798Z", "local_delete_time" : "2016-09-13T08:14:33Z" } },
          { "name" : "mylist", "path" : [ "1a1a0760-798a-11e6-851a-e3954ecad15b" ], "value" : "1" },
          { "name" : "mylist", "path" : [ "1a1a0761-798a-11e6-851a-e3954ecad15b" ], "value" : "2" },
          { "name" : "mylist", "path" : [ "1a1a0762-798a-11e6-851a-e3954ecad15b" ], "value" : "3" }
        ]
      },
      {
        "type" : "row",
        "position" : 99,
        "clustering" : [ "y2" ],
        "liveness_info" : { "tstamp" : "2016-09-13T08:14:49.772718Z" },
        "cells" : [
          { "name" : "z", "value" : "z2" },
          { "name" : "mylist", "deletion_info" : { "marked_deleted" : "2016-09-13T08:14:49.772717Z", "local_delete_time" : "2016-09-13T08:14:49Z" } },
          { "name" : "mylist", "path" : [ "23fefce0-798a-11e6-851a-e3954ecad15b" ], "value" : "4" },
          { "name" : "mylist", "path" : [ "23fefce1-798a-11e6-851a-e3954ecad15b" ], "value" : "5" },
          { "name" : "mylist", "path" : [ "23fefce2-798a-11e6-851a-e3954ecad15b" ], "value" : "6" }
        ]
      }
    ]
  }
]

As you can see the collection is not really different from the non primary key column, except for the aggregation that's needed before returning it to the client. I wonder if this was a constraint on the old thrift implementation and got carried over even though there is no obvious reason why this can't be done.


Como mostrar/esconder um sidebar baseado no tamanho da tela e aperto de um botão?

Question: Eu construí uma sidebar customizada para o meu painel. Dentro dessa sidebar, eu tenho alguns itens de menu. Quando a minha tela está pequena, eu faço com que todas as opções de menu desapareçam, e que mostre apeas uma opção de menu específica. Essa opção de menu específica é utilizada como um botão que faz com que todos os itens de menu apareçam novamente.
A minha sidebar:

Quando a minha tela está pequena, a sidebar fica dessa maneira:

Para montar a sidebar eu utilizo o código abaixo:

 Open/Close menu

 Home
 Projects
 Jobs
 Logout

Para fazer os itens aparecer/desaparecer eu utilizo essa lógica CSS abaixo:
@media screen and (min-width: 992px) {

#shmenulinks {
display: none;
}
#menulinks {
display: block;
}
}

@media screen and (max-width: 991px) {
#shmenulinks {
display: block;
}
#menulinks {
display: none;
}

}

Meu problema é quando a tela está pequena e o menu colapsado, o botão que eu utilizo para fazer os itens do menu aparecerem novamente não funciona.
O CODEPEN: https://codepen.io/neyelson-alves/pen/ZEGbdJB
O que devo fazer?
Answer: Faltou adicionar a classe .collapse na div do menu:

E não precisa colocar display: none no CSS nessa div, pois o controle disso fica à cargo do próprio Collapse do Bootstrap. Remova o código abaixo do CSS:
#menulinks {
display: none;
}

Teste:

@media screen and (min-width: 992px) {
   #menulinks {
      display: block;
   }

   #shmenulinks {
      display: none;
   }

}

@media screen and (max-width: 991px) {
   #shmenulinks {
      display: block;
   }
}

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

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

    Open/Close menu

       Home
       Projects
       Jobs
       Logout

Referência:

Collapse do Bootstrap 4


I want to add $ sign to TextField in SwiftUI

Question: Hi I want to add $ sign to a TextField when a user is typing.

This is my current code.
ZStack(alignment: .leading) {
  if price.isEmpty {
    Text("Enter total budget")
  }
  HStack {
    TextField("", text: $price)
      .keyboardType(.decimalPad)
  }
}

Comment: it may be reasonable to use the some kinda currency formatter with the `TextField`, it does not do the formatting on the fly during typing but it definitely formats the input value when the edit finishes.
Comment: Use a Formatter https://stackoverflow.com/questions/24960621/formatting-input-for-currency-with-nsnumberformatter-in-swift
Comment: Does your app only support dollars?
Answer: currency formatter is the way to go, but if you just want to show a $ in the TextField as you type, you could use something like this:
(you can of course combine this approach with a Formatter)
struct ContentView: View {
    @State var price = ""

    var body: some View {
        VStack {
            ZStack(alignment: .leading) {
                if price.isEmpty {
                    Text("Enter total budget")
                }
                HStack {
                    TextField("", text: Binding(
                        get: { price },
                        set: { newVal in
                        if price.starts(with: "$") {
                            price = newVal
                        } else {
                            price = "$" + newVal
                        }
                    })).keyboardType(.decimalPad)
                }
            }.padding(20)
            Text("number entered: " + String(price.dropFirst()))
        }
    }
}


Proof that Sargan test statistic is distributed $\chi^2$

Question: Assume that
$$\textbf{y} = X\boldsymbol\beta + \boldsymbol\varepsilon $$
, where $\boldsymbol\varepsilon$ is an $n \times 1$ random vector and that X is an $n \times k$ matrix of regressors; $m$ of these regressors are endogenous. Let $Z$ be an $n \times (k-m+l)$ matrix where the endogenous regressors are replaced by exogenous instruments. If $\boldsymbol\beta$ is estimated by 2SLS
$$ \hat{\boldsymbol\beta}_{2SLS} = \left(X^\prime P_Z X \right)^{-1} X^\prime P_Z \textbf{y}$$
$$ P_Z= Z\left(Z^\prime  Z \right)^{-1} Z^\prime $$
, it is (supposedly) possible to show that if $E[\boldsymbol{z}_i^\prime\varepsilon_i]=\textbf{0} $, then
$$ n\frac{\hat{\boldsymbol\varepsilon}^\prime P_Z \hat{\boldsymbol\varepsilon}}{\hat{\boldsymbol\varepsilon}^\prime \hat{\boldsymbol\varepsilon}} \sim \chi^2 \left(l-m \right)$$
See, e.g., https://en.wikipedia.org/wiki/Sargan%E2%80%93Hansen_test . I have not been able to find an explanation of how it is possible to show this. That is, I have not found one that I am able to understand; see, e.g., http://www.jstor.org/stable/1907619 for the original article. My guess is that we would invoke the Central Limit Theorem
$$ \frac{1}{\sqrt n} Z^\prime  \hat{\boldsymbol\varepsilon} \sim N(0,\Omega) $$
and assume that $\Omega$ is invertible, such that
$$ \frac{1}{\sqrt n} \Omega^{-\frac{1}{2}} Z^\prime  \hat{\boldsymbol\varepsilon} \sim N(0,I) $$
Then
$$ \left(\frac{1}{\sqrt n} \Omega^{-\frac{1}{2}} Z^\prime  \hat{\boldsymbol\varepsilon} \right)^\prime \left(\frac{1}{\sqrt n} \Omega^{-\frac{1}{2}} Z^\prime  \hat{\boldsymbol\varepsilon} \right) \sim \chi^2 (l-m) $$
, since it is a sum of independent squares. Assuming homoskedasticity, we can replace $ \Omega $ by
$$ \hat{\Omega} = \frac{\sigma^2_{\hat{\varepsilon}}}{n} Z^\prime Z$$
, which yields the Sargan test statistic.
My question is if this proof is correct? Also, how can we show that the degrees of freedom are $l-m$? The $l$-part makes sense, since all except $l$ elements of $Z^\prime \hat{\boldsymbol\varepsilon} $ are 0 by construction. Any help would be much appreciated.
Comment: There are $k-m+l$ elements in $Z^\prime \hat{\boldsymbol\varepsilon}$. For the exogenous variables that are not excluded from the second stage, $x_1, ..., x_{k-m}$,  we have $\sum_{i=1}^n x_{ji }\hat{\varepsilon}_i = 0$ by construction.
Comment: OK, I did not read your matrix dimensions right.
Comment: What do you mean by saying "since all except $l$ elements of $Z′\hat{\epsilon}$ are 0 by construction"? There are just $l$ elements in $Z′\hat{\epsilon}$.
Answer: I will give a proof for a general GMM test statistic of overidentifying restrictions, which evaluates the GMM criterion function at the GMM estimate.
The Sargan statistic is a special case of this statistic under conditional homoskedasticity.
The notation and exposition follow Hayashi (2000) Econometrics, so that, unlike in your question, instruments are denoted by $X$ (there are $K$ of them) and regressors by $Z$ (there are $L$ of them). $S_{xz}$ etc. are then corresponding sample moment matrices. $\widehat{\delta}_{GMM}$ is the GMM estimate of the true coefficient $\delta$. $\widehat{S}^{-1}$ is the efficient weighting matrix. $g_i(\tilde{\delta}):=x_{i}(y_i-z_i'\tilde{\delta})$ and $g_n(\tilde{\delta})=\frac{1}{n}\sum_{i=1}^{n}g_{i}(\tilde{\delta})$
\begin{equation*}
J\bigl(\widehat{\delta}_{GMM},\widehat{S}^{-1}\bigr)\to_d\chi^{2}(K-L).
\end{equation*}
Proof:
First, note that
\begin{eqnarray*}
g_n(\widehat{\delta}_{GMM})&=&s_{xy}-S_{xz}\widehat{\delta}_{GMM}\\
&=&s_{xy}-S_{xz}(S_{xz}'\widehat{S}^{-1}S_{xz})^{-1}S_{xz}'\widehat{S}^{-1}s_{xy}\\
&=&\bigl(I-S_{xz}(S_{xz}'\widehat{S}^{-1}S_{xz})^{-1}S_{xz}'\widehat{S}^{-1}\bigr)s_{xy}\\
&=:&\widehat{B}s_{xy}
\end{eqnarray*}
Further,
\begin{eqnarray}
\widehat{B}s_{xy}&=&(I-S_{xz}(S_{xz}'\widehat{S}^{-1}S_{xz})^{-1}S_{xz}'\widehat{S}^{-1})s_{xy}\notag\\
&=&(I-S_{xz}(S_{xz}'\widehat{S}^{-1}S_{xz})^{-1}S_{xz}'\widehat{S}^{-1})(S_{xz}\delta+g_n(\delta))\notag\\
&=&\underbrace{(S_{xz}-S_{xz}\underbrace{(S_{xz}'\widehat{S}^{-1}S_{xz})^{-1}S_{xz}'\widehat{S}^{-1}S_{xz}}_{I})}_{0}\delta+\widehat{B}g_n(\delta)\notag\\
&=&\widehat{B}g_n(\delta)\label{bgndelta}
\end{eqnarray}
Using the decomposition $\widehat{S}^{-1}=C'C$ we obtain $\widehat{B}'\widehat{S}^{-1}\widehat{B}=(C\widehat{B})'(C\widehat{B})$.
Now,
\begin{eqnarray*}
C\widehat{B}&=&C(I-S_{xz}(S_{xz}'\widehat{S}^{-1}S_{xz})^{-1}S_{xz}'\widehat{S}^{-1})\\
&=&C-CS_{xz}(S_{xz}'C'CS_{xz})^{-1}S_{xz}'C'C\\
&=&C-A(A'A)^{-1}A'C\\
&=&(I-A(A'A)^{-1}A')C\\&=:&MC,
\end{eqnarray*}
where $A:=CS_{xz}$ and, as usual, $M$ is symmetric and idempotent, so that
\begin{equation}\label{Jtestproof3}
\widehat{B}'\widehat{S}^{-1}\widehat{B}=C'M'MC=C'MC.
\end{equation}
Then,
\begin{eqnarray*}
tr(M)&=&tr(I-A(A'A)^{-1}A')\\&=&K-tr((A'A)^{-1}A'A)\\
&=&K-tr(I_L)\\&=&K-L.
\end{eqnarray*}
Now, take $D'D=S^{-1}$ so that $C\to_pD$.
With the baseline assumption that, at true value, the sample moment conditions satisfying a CLT, $\sqrt{n}g_n(\delta)\to_dN(0,S)$
it holds that
\begin{eqnarray}
C\sqrt{n}g_n(\delta)&\to_d&N(0,DSD')\notag\\&=&N(0,D(D'D)^{-1}D')\notag
\\&=&N(0,DD^{-1}D'^{-1}D')\notag
\\&=&N(0,I)\label{hansenovern}
\end{eqnarray}
Hence,
\begin{eqnarray}
J\bigl(\widehat{\delta}_{GMM},\widehat{S}^{-1}\bigr)&=&n\cdot g_n(\widehat{\delta}_{GMM})'\widehat{S}^{-1}g_n(\widehat{\delta}_{GMM})\notag\\
&=&n\cdot g_n(\delta)'\widehat{B}'\widehat{S}^{-1}\widehat{B}g_n(\delta)\notag\\
&=&n\cdot g_n(\delta)'C'MCg_n(\delta)\notag\\
&=&\sqrt{n}\cdot(Cg_n(\delta))'M\sqrt{n}Cg_n(\delta)\label{hansenoveridasy}
\end{eqnarray}
Thus, this is asymptotically is a quadratic form in normally distributed vectors and an idempotent matrix $M$ with $tr(M)=rk(M)=K-L$. Thus, (see e.g. Thm. A.87 in Toutenburg and Rao (1999) Linear Models: Least Squares and Alternatives)
$$J\bigl(\widehat{\delta}_{GMM},\widehat{S}^{-1}\bigr)\to_d\chi^{2}(K-L)
$$
Comment: Cheers! I will work through your proof when I get the time. The reference was helpful, found it [here](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.465.2347&rep=rep1&type=pdf). I'm not sure that it answers my question, though. I'm not saying that it doesn't, either. I'm just not sure yet...
Answer: I will use your notation and write $M_A = Id - P_A = Id - A^T (A^T A)^{-1} A$ for the projection onto the orthogonal complement of $A$.
Let's assume all k regressors in $X$ are endogenous, i.e., $k=m$. Otherwise, replace $Z, X, y$ by their projection onto the orthogonal complement of the exogenous regressors. Thus, $\dim(X) = k \leq \dim(Z) = l$.
The J-statistic is
\begin{align*}
J &= \frac{1}{\hat \sigma_\varepsilon^2} (y - X \hat\beta)^T P_Z(y - X\hat\beta).
\end{align*}
Expand
\begin{align*}
P_Z(y - X \hat\beta) &= P_Z\left(X \beta_0 + \varepsilon - X (X^T P_Z X)^{-1} X^T P_Z (X\beta_0 + \varepsilon)\right) \\
&= P_Z \varepsilon - P_Z X (X^T P_Z X)^{-1}X^T P_Z \varepsilon \\
&= P_Z M_{P_Z X} \varepsilon = P_{M_X Z} \varepsilon
\end{align*}
Thus
$$
J = \frac{1}{\hat\sigma_\varepsilon^2} \varepsilon^T P_{M_X Z} \varepsilon.
$$
As $rank(P_{M_X Z}) = l - k$, the result $J \overset{d}{\to} \chi^2(l - k)$ follows from a CLT argument. If the $\varepsilon$ are normal, then $\frac{1}{l - k} J \sim F_{l - k, n - l}$.