How can increasing the dimension increase the variance without increasing the bias in kNN?

Question: My question is about understanding Figure 2.8 in The Elements of Statistical Learning (2nd edition).  The topic of the section is how increasing dimension influence the bias/variance.
I can roughly understand Figure 2.7 in ESL, but have no idea about 2.8. Any explanation on the roughly unchanged bias, or the dominating variance? I cannot imagine how they change when the dimension is increasing.
Following is the detail:
Suppose we have 1000 training examples $x_i$ generated uniformly on $[-1,1]^p$. Assume that the true relationship between $X$ and $Y$ (capital letters for variables) is
$$
Y=F(X)=\frac12(X_1 + 1)^3
$$
where $X_1$ denotes the first component of $X$ ($X$ has totally $p$ components, in other words, features). We use the 1-nearest-neighbor rule to predict $y_0$ at the test-point $x_0 = 0$. Denote the training set by $\mathcal{T}$. We can compute the expected prediction error at $x_0$ for our procedure, averaging over all such samples of size 1000. This is the mean squared error (MSE) for estimating $f(0)$:
\begin{align}
\operatorname{MSE}(x_0) &=E_{\mathcal{T}}[f(x_0)-\hat{y}_0]^2 \\
                        &= E_{\mathcal{T}}[\hat{y}_0-E_{\mathcal{T}}(\hat{y}_0)]^2 +
                            [E_{\mathcal{T}}(\hat{y}_0)-f(x_0)]^2 \\
                        &= \operatorname{Var}_{\mathcal{T}}(\hat{y}_0) + \operatorname{Bias}^2(\hat{y}_0)
\end{align}
The figure is below.  The right plot is the case with increasing $p$ (dimension).

Comment: Not everybody has the book. Can you show the picture (or a similar one) so others can understand the question? It would be helpful in answering it as well.
Comment: @Bor the question was put on hold because on this site we try to maintain questions and answers that are self-contained and so useful for more people then the original poster. Describing your question in detail (like it is now) makes it more readable for other users and also helps you to get an high-quality answer. Btw, welcome to our site!
Comment: @Andy I'm really sorry for the unclear statement. Now I updated the question.
Comment: I changed the title & added the `[knn]` tag to make it more specific to the figure you are trying to understand. I'm not sure that the phenomenon discussed will always work out the same under other circumstances.
Comment: @gung Thank you. I asked this question just because I got confused when reading the book, and I think **understanding** is the most important thing. I think the relationship among bias, variance and dimension is the core issue behind this question.
Comment: Yeah, you can re-edit & change the title, if you'd like. The body of the Q is fairly specific to that figure / exact case. You could say 'I want to know about the relationship b/t bias & variance in general, here's a specific case to motivate the discussion', if you wanted to.
Answer: First of all, the bias of a classifier is the discrepancy between its averaged
estimated and true function, wheras the variance of a classifier is the expected divergence of the estimated prediction function from its average value (i.e. how dependent the classifier is on the random sampling made in the training set).
Hence, the presence of bias indicates something basically wrong with the model, whereas variance is also bad, but a model with high variance could at
least predict well on average.
The key to understand examples generating Figures 2.7 and 2.8 is:

The variance is due to the sampling variance of the 1-nearest
  neighbor. In low dimensions and with $N = 1000$, the nearest neighbor
  is very close to $0$, and so both the bias and variance are small. As
  the dimension $p$ increases, the nearest neighbor tends to stray
  further from the target point, and both bias and variance are
  incurred. By $p = 10$, for more than $99\%$ of the samples the nearest
  neighbor is a distance greater than $0.5$ from the origin.

Recall the the target function of the example generating Figure 2.7 depends on $p$ variables, and hence the MSE error is largely due to the bias.
Conversely, in Figure 2.8 the target function of the example depends only on $1$ variable, and thus the variance dominates. More generally, this happens when you are dealing with low dimensions.
I hope this could help.
Comment: the problem is that the k-nn doesn't know that only one variable is important. so in finding the nearest neighbour it is using the distance with all the other dimensions too. - so the chances of getting a point close on x1 dimension just because the overall distance is small gets smaller and smaller as dimension increases
Comment: Thanks a lot. I've also read that segment, but I still cannot understand why variance dominates when the target function depends on only 1 variable, as well as the increasing trend of variable.
Comment: @seanv507 great comment. I just posted an answer where the core idea is the same as yours. It took me so long that I couldn't see your comment. Thank you!
Answer: Well, I don't know whether it's appropriate to answer a question asked by myself... But I think I have a relatively intuitive answer and I just wanna share it.
First let me add the true function in Figure 2.7 for comparison:
$$Y=f_1(X)=e^{-8||X||^2}$$
and the one in Figure 2.8 is
$$Y=f_2(X)=\frac12(X_1+1)^3$$
As @stochazesthai said, the true function of 2.7 depends on all $p$ components and 2.8 only $1$ component. On the other hand, the 1-NN algorithm involves the ordinary norm (by default), so the distance is measured by all components. Another thing to mention is that the expectation is taken to the estimated target $\hat{y}$ over the sample distribution.
Now consider the input $X$. Given any distance $d$ to the origin, when $p=1$, there're only $2$ choices of the value of $X$, which are $d$ and $-d$. When $p$ is increasing, with any fixed distance, the choices of $X$ will be dramatically increased, where the value of the first component $X_1$ can be oscillating more and more freely.
Then consider the 1-NN. When $p$ is increasing, as @stochazesthai quoted, the nearest neighbor of origin will be far away with high probability, which means that the smallest $||X||$ will be large.
Hence for $f_1$ (where $||X||$ involved), $E(\hat{y}_0)$ will increase a lot when $p$ is increasing, so the bias will increase significantly; but at the same time $\hat{y}_0$ will also be large with high probability, so the variance will not increase too much.
On the other hand, for $f_2$ (where only $X_1$ involved), when $p$ is increasing, as I mentioned above, $X_1$ can oscillate more and more dramatically with the same distance $E_{\mathcal{T}}(\hat{y}_0)$. So the increasing of variance will dominate, but $E_{\mathcal{T}}(\hat{y}_0)$ itself will not change a lot, so the bias will roughly unchanged in comparing with variance.
Hopefully it's kind of helpful.


Does significant correlation imply at least some common underlying cause?

Question: If the correlation was significant enough (however you define it), does it necessarily show that there is some underlying cause even if it's not direct causation?
Comment: Also: See [my answer](https://stats.stackexchange.com/a/551872/44269) to Who first coined the phrase "correlation does not imply causation"?
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Comment: [Lack of correlation does not mean lack of causation](https://stats.stackexchange.com/questions/559085/correlation-without-causation/559101#559101).
Comment: I think David Hume would say that you can't have certain knowledge of causal relationships based on empirical observation (we can't observe causation - only correlation/sequence) but Kant would say that our knowledge is based on observation and theory (Adrian's "mechanism" - +1), so we can't say "necessarily" because it is contingent on agreement about theory and it's assumptions.  Caveat lector: I'm (evidently) not a philosopher, just interested where it impinges on statistics and science.
Comment: I'd suggest that many processes tend to change (e.g. increase) over time. To see correlation, there may be no connection whatever other than two processes each existing in time. To attribute time as the cause of each  rather stretches the notion of *cause*.
Answer: It is not "necessarily". The usual "post hoc ergo propter hoc" fallacy is the fallacy that says correlation always implies causation, or even that you can infer causality. This is still a fallacy. However, if you add another condition to the correlation - namely, that of mechanism - then you get Reichenbach's common cause principle: "No correlation without causation."
As an example, the rooster crowing causing the sunrise is a "post hoc" because there's no plausible mechanism for a lone rooster crowing to cause the sunrise - although, interestingly enough, there could be causation the other way: does the sunrise cause the rooster to crow? Perhaps.
We've been conditioned to avoid post hoc so strongly that I think the Reichenbach common cause principle needs trumpeting. The Reichenbach common cause principle says that if there's a mechanism, you should look for causality somewhere: the principle doesn't say which direction the causality is, and it also doesn't rule out a third common cause (confounding variable).
Another way of saying it is

Correlation doesn't imply causation, but it does waggle its eyebrows suggestively and gesture furtively while mouthing 'look over there'. - Randall Munroe.
Comment: Essentially, yes: if there is a suspected mechanism, then correlation usually (not always) implies causation.
Comment: Thanks, but isn't that saying there necessarily is a causation, directly, indirectly or in the other direction somehow?
Comment: Got it. And when you say "NOT implies causation," you mean in cases where it's either indirect or the opposite, right?
Comment: No, I mean that when correlation does not imply causation, there is no causal path to or from one variable to the other. The Reichenbach principle says there is either a direct arrow one way, a direct arrow the other, or a third variable (or set of variables) with arrows to or from the two starting variables: there is causation somewhere. It says that pure serendipity (coincidence) is unlikely.
Comment: Right. I meant 3rd variable when I said indrect.  I suppose the existence of pure serendipities is unknowable, unless you mean they are just rare when you said unlikely.
Comment: " It says that pure serendipity (coincidence) is unlikely. " it may be risky to make such a statement based on a frequentist hypothesis test (as it is a statement about the truth of a particular hypothesis).


A trigonometric function question for calculus

Question:
Compute the definite integral $$\int_0^1 \left(2-x^2\right)^{3/2}dx$$

Please help me, i suppose $x=\sqrt{2} \sin \theta$ but I just couldn't get the answer.
Thank you
Comment: What happened when using your substitution?
Comment: Using that substitution, what does $dx$ need to be?  $dx =  \sqrt 2 \cos \theta$
Comment: If you don't tell us where you get stuck, you won't get the most helpful of answers.
Comment: https://imgur.com/a/wZSjmZS this is my first try and couldn't figure out where going  wrong .i used another way and got the answer. I wanted to know why this is wrong
Comment: Note: I used Wallis in the process
Comment: @Kizaru: In the second line, you correctly have the upper bound $\pi/4$. In the subsequent integrals, you've changed the upper bound to $\pi/2$.
Comment: Actually, that is exactly why you're process fails, Kizaru. You can't apply the Wallis formula because of the bounds.
Answer: So if $x = \sqrt{2} \sin t$ then $2-x^2 = 2 \cos^2 t$, and also $dx = \sqrt{2} \cos t dt$ and you get
$$
\int_0^1 \left(2-x^2\right)^{3/2}dx
 = 2^{3/2} \sqrt{2} \int_0^{\pi/4} \cos^4 t dt
 = 4\int_0^{\pi/4} \cos^4 t dt
$$
Can you complete this? (Hint: use the relation between $\cos 2x$ and $\cos^2 x$ twice)
(You can see here for how to do it if in doubt)
Comment: @amWhy interesting, will update -- thought he made a mistake in substituting -- but it's a standard technique from here and on, tabulated integral really
Comment: That all falls out from the mere substitution, and if the asker was stuck on the dx conversion, that was covered.  Chances are you stopped where it gets difficult.
Comment: https://imgur.com/a/wZSjmZS.    This is my original try
Comment: @amWhy updated with the link to stackexchange post how to solve the trig integral
Comment: I used Wallis in the process


does intel Xeon e5620 have EPT support?

Question: looking for CPU with good Virtualization support. could not find Intel EPT (extended page table) technology with E series. Is it only with higher X series?
but AMD Magny cour 6134 does have the RVI support (Rapid Virt Indexing)
Answer: Yep, all Nehalem/Westmere chips support EPT, so that's the 55xx/56xx/75xx ones plus I'm sure the 35xx/36xx series too (sorry but I'm no expert at workstation chips).

does intel Xeon e5620 have EPT support?


Covariance matrix decomposition and coregionalization

Question: The original question (that can be seen at the bottom of this post) was replaced by this first edit (below)
EDIT I
I give more details about my problem.
First of all let suppose to have K vectors $\boldsymbol{\omega}_k = \{\omega_{i,k}\}_{i=1}^n$, $k=1,\dots ,K$ of length $n$, distributed as multivariate normals:
$$
\boldsymbol{\omega}_k \sim N_n(\mathbf{0}_n, \mathbf{C}_k), k=1,\dots ,K.
$$
Now let suppose that i want to introduce dependence between the $\boldsymbol{\omega}_k$'s assuming that
$$
\boldsymbol{\omega}_{i,\cdot}=(\omega_{i,1},\omega_{i,2},\dots , \omega_{i,K})' \sim N_K(\mathbf{0}_k, \boldsymbol{\Sigma}), i=1,\dots , n
$$
notice that the $\omega$'s have all the same index $i$.
Now we can ask what is the covariance between $\boldsymbol{\omega}_{i,\cdot}$ and $\boldsymbol{\omega}_{j,\cdot}$, with $i\neq j$.
There is not a unique answer. We have to define a matrix $\mathbf{A}$ such that $\boldsymbol{\Sigma}=\mathbf{A}\mathbf{A}'$, and to find the matrices
$$
\mathbf{T}_k = [\mathbf{A}]_{\cdot,k} [\mathbf{A}]_{\cdot,k}', k=1,\dots ,K
$$
where $[\mathbf{A}]_{\cdot,k}$ is the $k^{th}$ column of $\mathbf{A}$.
Then the covariance between $\boldsymbol{\omega}_{i,\cdot}$ and $\boldsymbol{\omega}_{j,\cdot}$ is given by
$$
\sum_{k=1}^K \mathbf{T}_k [\mathbf{C}_k]_{ij}
$$
As you can see, the choice of $\mathbf{A}$ influences the covariance structure of my problem, and different $\mathbf{A}$'s give different models.
For example we can define $\mathbf{A}$ to be the Cholesky factorization, but then it is easy to see that we are saying that, marginally, the covariance matrix of $\boldsymbol{\omega}_1$ depends only on $\mathbf{C}_1$, the one of $\boldsymbol{\omega}_2$ depends on $\mathbf{C}_1$ and $\mathbf{C}_2$ and so on.
What I'm looking for is a $\mathbf{A}$ that let me able to have marginal distributions that do not depend on the ordering of the $\boldsymbol{\omega}$'s, i.e. that potentially the marginal density of $\boldsymbol{\omega}_1$ can be equal to the one of $\boldsymbol{\omega}_K$, that is not true for the Cholesky factorization and the spectral decomposition.
Old Question
Let suppose to have a covariance matrix $\boldsymbol{\Sigma}$. The spectral decomposition of a positive definite matrix tells us that we can write
$$
\boldsymbol{\Sigma} = \boldsymbol{\Psi}\boldsymbol{\Lambda}\boldsymbol{\Lambda}\boldsymbol{\Psi}'
$$
where the column vectors of $\boldsymbol{\Psi}$ are the normalized eigenvectors and $\boldsymbol{\Lambda}$ is a diagonal matrix where the $i^{th}$ element is the square root of the eigenvalue associated to the $i^{th}$ normalized eigenvector.
What I am interested in is the matrix
$$
\mathbf{A} = \boldsymbol{\Psi}\boldsymbol{\Lambda}
$$
where of course $\boldsymbol{\Sigma} =\mathbf{A}\mathbf{A}'$, assuming that the diagonal elements of $\boldsymbol{\Lambda}$ are placed in ascending order. It seems to me obvious that the space of $\mathbf{A}$ is constrained by the fact that I am imposing  an ascending order of the eigenvalues, but what are precisely the constraints?
Comment: I think you are based on the misconception that the eigenvalues are ordered. This actually is guaranteed only with some particular eigen-decomposition algorithms (eg. Lanczos-based algorithms). Any permutation of the columns of $\Lambda$ alongside the corresponding permutation of $\Psi$ would be a perfectly valid eigen-decomposition. Moreover, notice that usually eigen-decompositions entail a balancing pre-processing step; it improves the conditioning of $\Sigma$ to produce more accurate results but it can affect your final results too (among others: their ordering!). (Nice question! +1)
Comment: I am revising my upvote to a downvote because the new question is a completely new and different question which should be given it's own thread. Your adding it in diminishes the utility of my answer.
Comment: There can be no solution is some cases, which is intuitively
clear. Assume that $K=2$ and that (0) all $\omega_{i,k}$ have unit
variance (1) $\omega_{i,1}$ and $\omega_{i+1,1}$ have a strong
correlation say $\rho_1 \approx 1$, while (2) $\omega_{i,2}$ and
$\omega_{i+1,2}$ have a weak correlation say $\rho_2 \approx 0$. Then
no value of $\Sigma_{1,2}$ can be exist because both $\omega_{i,2}$
and $\omega_{i+1,2}$ should then be close to $\Sigma_{1,2}
\omega_{i,1}$, which conflicts with a small value for $\rho_2$.
Answer: A covariance matrix has ${n \choose 2} + n = \frac{n(n+1)}{2}$ free elements. The constraints for the spectral decomposition are:

The eigenvalues are positive
The eigenvectors are orthogonal
The eigenvectors are unit length.

I recently asked a question that had to do with this. @amoeba had a good comment that helped visualize these constraints and proved why the number of free elements in $\Psi$ was ${n \choose 2}$, and the number of free elements in $\Lambda^2$ was $n$.
Regarding the ordering of the eigenvalues, that may or may not be important to you. The spectral decomposition is only unique up to re-orderings of your $\Lambda^2$ diagonal matrix. If your task is to estimate the parameters of this matrix, each of these re-orderings will have corresponding estimates. In this case the model will not be identifiable.
However, if you are just theorizing about the covariance matrix, people sometimes just restrict their attention to one ordering of the eigenvalues, without losing any generality. Proving something is true for one ordering will usually guarantee truth for the other orderings.
Edit to address comment:
1,2 and 3 are constraints that every covariance matrix has, so it is as "free" as possible. Sampling from some distribution of $\Sigma$ is possible as long as long as the distribution exists, but it is also common to restrict the columns of $\Psi$ further, which is the same as fixing the ordering of your eigenvalues. What I mean is that sometimes they will restrict it to have $\psi_{i,j} = 0$ when $j > i$ and $\psi_{j,j} = 1$. In other words, it will be lower-diagonal with $1$s on the diagonal. The are other ways to restrict this space, but it would look something like this:
$$
\Psi =
\left[\begin{array}{cccc}
1 & 0 & 0 & 0 \\
\psi_{2,1} & 1 & 0 & 0 \\
\vdots & \vdots & \ddots & \vdots \\
\psi_{p,1} & \psi_{p,2} & \cdots & 1 \\
\vdots & \vdots & \ddots  & \vdots \\
\psi_{n,1} & \cdots & \psi_{n,p-1} & \psi_{n,p}
\end{array} \right].
$$
Why is this representation unique? If you re-order the diagonal matrix $\Lambda^2$, then you have to re-order the columns of $\Psi$, but then the columns of $\Psi$ won't follow this pattern. Why do this? Well now your posterior is not multi-modal.
Comment: Among other things, I'm trying to estimate the elements of $\boldsymbol{\Sigma}$, but in my application, to model the coregionalization, I need a matrix $\mathbf{A}$  such that $\boldsymbol{\Sigma}=\mathbf{A}\mathbf{A}'$. And I also need $\mathbf{A}$ to be as free as possible, also overparametrized, since, at the end, I'm just looking to the posterior samples of $\boldsymbol{\Sigma}$ (it's a Bayesian model). Maybe I can just introduce a variable that decides the ordering of the eigenvalues/eigenvectors
Comment: @niandra82 see edit
Comment: I edited my question, adding more details on my problem. Thank you
Comment: Minor: Covariance matrix has to be positive semi-definite, so its eigen values are non-negative. Not necessarily all positive.
Comment: @Berkmeister positive definite usually. Unless you're looking at singular random vectors


Mixed model (Multilevel) with two INDEPENDENT Random Effects [lmer]

Question: I like to estimate a mixed model with two Random Effects, that are independent of each other and among themselves.
I use Panel data with a nested structure (counties $j$ nested within regions $i$). The error component should decompose in the following way:
$$E_{ijt} = \alpha_i + \mu_{ij} + e_{ijt}$$
$\alpha_i$ is an unobservable region specific time-invariant effect (normal distributed)
$\mu_{ij}$ is a nested effect of  county $j$ within region $i$ (normal distributed)
$e_{ijt}$ is a remainder disturbance (normal distributed)
I read somewhere that "lmer" is capable to fit such specifications with idenpendent Random Effects.
lmer(y~.... + (1|region) + (1|county)
Is the lmer-model adequate for my task?
Answer: Yes, lme4 should be fine in here. The formula you are asking is:
y ~ 1 + (1|region) + (1|region:county)
because in model you described country is nested in region.
For an extended description and examples see here, here or here.


Minimize the variance of a three-security portfolio

Question: I have three securities whose variance covariance matrix looks like this:
<code>        DE5   FR10   IT15
DE5  0.0376 0.0350 0.0243
FR10 0.0350 0.0658 0.0658
IT15 0.0243 0.0658 0.1335
</code>
How do I weight each of the three to minimize variance of the package, excluding the (0, 0, 0) solution. I don't mind "going short" IE, a mixture of positive and negative coefficients.
Can this be done with regression? I suspect not as weights will depend on which variable is chosen as dependent.
Is there a straightforward linear-algebra way of doing this without bringing in heavyweight quadratic programming package? I have many of these to do.
Ideally I'd like some code in R.
Comment: Traditionally, one would use quadratic programming rather than regression.
Comment: @John but will regression work? I have over 500k of these to do and I know the regression routines in R are highly optimized. The thing is if I use regression, which variable do I choose as the dependent variable? Does it matter? See I think I get a problem because depending on which variable I use as dependent, I'll get different solutions even after scaling.
Comment: First, you need to clearly determine/state all the constraints on the weights. Do they need to sum to 1 (not just that at least one is non-zero)? You "don't mind" shorting, but is there a constraint on magnitude of shorting. e.g.,  is weight < -1 allowed? Etc. Then you can worry about solution methods.  Do actual problems to be solved only involve 3 securities, or are they larger?
Comment: @ThomasBrowne Under some conditions, a quadratic optimization is equivalent to a regression, but as Mark L. Stone notes the types of constraints are important. I would refer you to "The Sampling Error in Estimates of Mean-Variance Efficient Portfolio Weights" by Mark Britten-Jones as a classic source. I'm sure there are others. Also, a good quadratic optimization library, even in R, should be calling C/Fortran code for the best performance. You can do them in parallel to increase speed.
Comment: @MarkL.Stone There is only one single constraint: at least one of the series must have a non-zero weight, given upfront. Because otherwise the optimizer will just give me three zeros. There is no constraint on the sum of the coefficients. And yes, I may generalize to larger problems.
Comment: @John I'll take a look at that source, many thanks. Also your (and Mark L. Stone)s' opinion on the answer below would be useful.
Comment: Why not just buy one cent worth 9or whatever the minimum quantity) of the lowest variance security? It is very unusual to not require a normalized (to 1) sum of weights.
Comment: @ThomasBrowne The constraint "at least one of the series must have a non-zero weight", by itself, would actually be hard to implement. It would require mixed integer quadratic programming because it would need a binary variable in there to handle the "at least one" part. Mark L. Stone's point is also valid that you could just have the bare minimum of the lowest variance security. You need something else going on beyond just that constraint. If the weights sum to 1, then at least one security is guaranteed to have a positive weight, that may be bigger than 100%.
Comment: @John - okay what I meant was that I wanted the minimum variance portfolio of all three securities, while excluding the (0, 0, 0) solution. So either you specify one _specific_ security to have non-zero (any arbitrary number), which will necessarily bound the other two since otherwise we we are not minimizing. It is basically equivalent to saying "sum of weights = 1" for example. My working was inaccurate. I have changed the question.
Comment: @ThomasBrowne I'm not sure we are getting through...maybe instead of thinking about it in weights, think about in terms of shares purchased. The lowest volatility portfolio is buying one share in the stock with the lowest expected volatility. You can instead think about the portfolio investing a certain dollar amount (the total of price times quantity of shares). This is equivalent to the constraint that the weights sum to 1. Moreover, if you add the constraint that the weights sum to 1, then even if you allow shorting at least one variable has a non-zero weight. Something has to be positive.
Comment: @John, actually what I am trying to do is, given three securities, which two securities are the best hedge for the third, _without knowing in advance_ which is the "body" (~"belly")" security in the butterfly and which are the wings.
Comment: @ThomasBrowne With three securities it's relatively easy...just do the optimization three times, constraining one security's weight to be 1 in each of the optimizations. This would not be a good solution with a larger portfolio, but I think would work here.
Answer: This is a well-known finance problem. If the constraints are in the form
$
w_i \geq Const\ \ \ \rm{or}\ \ \ w_i \leq Const
$
the closed-form solution (formula) does not exist. You have to use iterative optimization methods. However, your constraint
$
w_i \neq Const
$
has measure 0 and is likely to be nonbinding. You can solve the unconstrained problem using formula
$
w = \frac{\Omega^{-1}\rm{1}}{\rm{1^{T}}\Omega^{-1}\rm{1}}
$
where $\Omega$ is the covariance matrix and $\rm{1}$ is the vectors of 1's... Then you can see that all the weights are non-zero and happily conclude that the constrained solution is the same as the unconstrained one.
Please note: the formula above gives the absolutely minimum-variance portfolio assuming
$\ \ \ $1) there is not riskless asset (cash account or treasury bond),
$\ \ \ $2) you are fine with any expected return.
The formula for the minimum-variance portfolio assuming a specific expected return is somewhat different.


Shell do Python e Django

Question: Sei que para abrir o shell interativo do Python, simplesmente executamos no terminal do sistema operacional:
python

Mas com o Django instalado, também é possível abrir o shell usando o comando:
python manage.py shell

Existe alguma diferença entre as duas maneiras de invocar o interpretador Python?
Comment: Pelo que eu saiba, o shell do Django é só uma shell Python pronta para interagir com seu ambiente Django. Creio que essa documentação possa ajudar: https://docs.djangoproject.com/en/1.11/ref/django-admin/#shell
Answer: Ao abrir o shell usando python manage.py shell, dentro do diretório do seu projeto Django, será configurado o ambiente para que seja possível a interação com os objetos do seu código-fonte a partir do shell do Python.
É possível fazer esta configuração de ambiente manualmente abrindo o shell com python, importar o pacote do Django e em seguida configurar a variável de ambiente DJANGO_SETTINGS_MODULE para o settings.py do seu projeto.
Usar python manage.py shell é apenas uma maneira que o Django oferece para  facilitar esta configuração do ambiente do seu projeto no shell do Python.
Answer: Quando voce abre o python shell "puro" voce tem disponível apenas os pacotes disponíveis na sua env. Ao abrir via manage.py, voce tem disponível, no shell, toda a configuração e objetos do seu projeto, podendo, por exemplo, importar uma classe de qualquer model de qualquer app definida no projeto, fazer CRUD (através dessas classes/models), executar comandos do manager, executar rotinas de testes, e por ai vai.... :-)

Shell do Python e Django


How can i align the tooltip above the sorter icon? I am using antd

Question: I am using antd framework for making a table with sorter column. How can I make the tooltip aligned above the sorter icon? Here's the snippet of my UI.

I added this prop inside the column, date.
<code>showSorterTooltip={{title: 'Click to sort', placement: 'topRight', arrowPointAtCenter: false, autoAdjustOverflow: true}}
</code>
Answer: showSorterTooltip accepts Tooltip props.
Try adding 'align:{ offset: [x, y] }' in showSorterTooltip. You can adjust x and y: https://github.com/ant-design/ant-design/issues/21337
This does not work after antd 5.3.0: https://ant.design/docs/blog/tooltip-align
Comment: Your method requires calculating the position of the up and down arrows for each column in the table. The positional parameters are variable, and you should provide code to calculate the position of the up and down arrows.
Answer: ShowSorterTooltip accept Tooltip tips,
align: {offset: [x, y]  }} />
Calculate the position of the arrow on the table column, and then use it to offset the x and y
Comment: it is working though, i think it is not advisable for doing responsive ui
Comment: antd Table does not have better API, so I think that my answer is a relatively good idea at present.


swift - How to delay method call until variables value is stored regarding updating current location

Question: I would like to call a method but it requires coordinates that have not been stored in variables yet.
So far I have:
1) acquired current location
2) Think I store them?
What I want to do:
1) Call method After these variables are stored so the program can run
class ViewController: UIViewController, CLLocationManagerDelegate  {

let locationManager = CLLocationManager()
var clLatitude : CLLocationDegrees!
var clLongitude: CLLocationDegrees!

override func viewDidLoad() {
    super.viewDidLoad()

    self.locationManager.requestAlwaysAuthorization()
    self.locationManager.requestWhenInUseAuthorization()

    if CLLocationManager.locationServicesEnabled() {
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.startUpdatingLocation()

    }

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    let location:CLLocationCoordinate2D = manager.location!.coordinate

    //Test printing coordinates to screen
    print("locations = \(location.self.clLatitude) \(location.self.clLongitude)")

    //place where I think I store the variables?
    self.clLatitude  = location.latitude
    self.clLongitude = location.longitude

}

func methodToBeCalled(){
     //to be called after variables are stored.
}

I believe I have covered everything regarding my problem
Answer: i think you just need to call the method at the end of locationManager(manager: didUpdateLocations:)
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    let location:CLLocationCoordinate2D = manager.location!.coordinate

    //Test printing coordinates to screen
    print("locations = \(location.self.clLatitude) \(location.self.clLongitude)")

    //place where I think I store the variables?
    self.clLatitude  = location.latitude
    self.clLongitude = location.longitude

    // call method
    methodToBeCalled()
}

func methodToBeCalled(){
     //to be called after variables are stored.
}

Comment: Im attempting this at the moment, my apologies for the late response, but trying to print to the screen to test and nothing within the "methodToBeCalled()" is printing to the screen. A silent fail? Grrrr
Comment: what I think this actually did do the trick, just that I had to go back and change the location under the debug dropdown to get it going! thank you!


Have any professional sporting tiebreaks been decided by a coin toss (or equivalent)?

Question: In most professional sporting events that involve some form of ranking system to determine an overall winner, or progression into later stages, there are a series of tie-breaker rules to determine a winner / loser when the primary ranking metric is tied across two or more competitors.
For example, for the 2018 FIFA World Cup, the tie-breakers for the group stage were as follows:

greatest number of points obtained in all group matches;
goal difference in all group matches;
greatest number of goals scored in all group matches.

[...]

greatest number of points obtained in the group matches between the teams concerned;
goal difference resulting from the group matches between the teams concerned;
greater number of goals scored in all group matches between the teams concerned;
greater number of points obtained in the fair play conduct of the teams based on yellow and red cards received in all group matches;
drawing of lots by the FIFA.

https://www.fifa.com/worldcup/news/tie-breakers-for-russia-2018-groups

Quite a lot of these tie-breakers end a coin toss, or another "luck of the draw" type scenario, to determine the "winner".
My question is: has any professional sporting event ever had to use its final "it's down to luck" tie-breaker?
Answer: There are a number of examples of this, but mostly from the days when they didn't have nearly as many tiebreakers before the "coin toss". Some football examples:

In Group F of the 1990 World Cup, a drawing of lots was used to decide the positions of the Republic of Ireland and the Netherlands in the group.
The 1968 European Championship semi-final between Italy and the Soviet Union.
The 1964-5 European Cup quarter-final between Liverpool and Köln

The latter two would these days have been settled by a penalty shootout; the former would probably have used one of the "disciplinary record" tie-breakers but I haven't looked into the details.


The radical presheaf is not a sheaf

Question: $\def\sO{\mathcal{O}}
\def\sI{\mathcal{I}}
$Let $(X,\sO_X)$ be a ringed space. Let $\sI\subset\sO_X$ be an ideal sheaf. We define the radical presheaf of $\sI$, denoted $\sqrt[p]{\sI}$, as the presheaf whose sections over $U\subset X$ are $\sqrt[p]{\sI}(U)=\sqrt{\sI(U)}$. I am trying to show that this presheaf is in general not a sheaf. How one would find a counterexample?
Answer: $\def\sO{\mathcal{O}}
\def\sI{\mathcal{I}}
\def\nil{\operatorname{Nil}}
$I think for those topological spaces whose subspaces are all quasi-compact (i.e., Noetherian topological spaces) we can prove that the radical presheaf is a sheaf.
Here's one non Noetherian counterexample: Consider the topological space $X=\mathbb{N}=\{1,2,3,\dots\}$ whose open sets are $\varnothing$ and $U_n=\{1,\dots,n\}$, for $n\in\{1,2,\dots\}\cup\{+\infty\}$. For $n\in\{1,2,\dots\}\cup\{+\infty\}$, define $\sO_X$ to have sections over $U_n$ equal to the polynomials of degree $<n$. That is, we define $\sO_X(\varnothing)=0$, $\sO_X(X)=k[x]$ and $\sO_X(U_n)=k[x]/(x^n)$, for $n<+\infty$. On the other hand, we define the restriction morphism from some open set containing $U_n$ to $U_n$ to kill all monomials of degree $n\geq 0$. Then $\sO_X$ can be verified to be a sheaf (of rings). Denote $\nil_p\sO_X$ to the nilradical presheaf of $\sO_X$, i.e., the radical presheaf of the zero ideal sheaf of $\sO_X$. Then $x\in\Gamma(X,\sO_X)$ is a global section such that $x|_{U_n}\in\nil (k[x]/(x^n))=(\nil_p\sO_X)(U_n)$ but $x\not\in(0)=\nil k[x]=\Gamma(X,\nil_p\sO_X)$.

The radical presheaf is not a sheaf


What's causing so many "httpd: " entries in /var/log/messages?

Question: On a low-powered VPS I maintain, which also functions as a production server, I keep an eye on logs to crisis-manage should a site get an influx of traffic or something goes haywire (tail a bunch of log files, top, iostat etc). This is infrequent, but can happen.
There's half a dozen WordPress installs (all up to date), with a few custom plugins (all up to date) and cached & optimised for quick pageloads.
I've noticed that in /var/log/messages there's dozens, nay, hundreds of entries similar to the following:
httpd:

Feb 25 09:48:19 node1 httpd:

Feb 25 09:51:54 node1 last message repeated 8 times
Feb 25 09:56:23 node1 last message repeated 40 times
Feb 25 10:11:49 node1 last message repeated 40 times

with nothing further provided. This isn't a new problem, but I couldn't pin down when exactly it started happening.
Obviously Apache's generating the error, and it smells to me like a PHP error, but before I go squirreling around turning various high-level logging on and enabling debug modes on this production VM, has anybody else come across this problem and knows the root cause(s)?
Comment: Are you using linux-ha or something?

I only know this log messages in the form of "node1 {servicename}" in /var/log/messages from resource agents in linux-ha.
Comment: To either validate or discard the PHP relation, I would turn php error logging on for a while, and try to associate the timestamps of php errors with /var/log/messages to see if you get matches.
Comment: Sounds like one of your plugins in wordpress (which is known for not having always the best quality plugins) is logging this error. May be some developer tried to debug something (without a real debugger like XDebug) and forgot to remove this "error message" at that point. Could you implement your own php error handler to get a backtrace of this string?
Comment: How is your logging setup in apache - does it actually use syslog or is it supposed to write to a file?
Comment: This box is a virtual machine running CentOS 2.6.18-164.2.1.el5xen. Its regular high-level management is done through DirectAdmin but I'm always SSHed in monitoring things. I'm running Apache with MPM-prefork; the "node1" is a truncation of the VM's primary hostname which only Apache seems to produce in logs.
Answer: Something - probably PHP - is writing to STDERR or STDOUT, most likely to STDOUT.
Search your plugins for anything related to Logging into STD{ERR,OUT} filedescriptors.


How can I handle race conditions in a headless setup?

Question: I am currently trying to build an eCommerce site. The functionalities are quite basic; there are products with limited quantities and customers can purchase those products. I've decided to use Drupal 10 as my backend CMS headless to handle the products and orders. The frontend communicates with Drupal through REST APIs. This includes order creation. When a user checks out, an order gets created in the backend, and the quantity of the item purchased is decreased.
I have a potential issue arising with the above order creation. The order creation can be seen below... The code is a bit simplified but the point is there:
<code>public function post($data) {
  if (!$this->loggedUser->hasPermission('access content')) {
    throw new AccessDeniedHttpException();
  }

  $productVariationStorage = \Drupal::entityTypeManager()->getStorage('commerce_product_variation');
  $productVariation = $productVariationStorage->load($data['id']);

  // potential check to make sure the product variation is available (quantity > 0)
  // Throw error message if not available
  $orderItems = array();
  $orderItem = OrderItem::create([
    'type' => 'example_order_item',
    'purchased_entity' => $data['id'],
    'quantity' => 1,
  ]);

  $orderItem->save();
  array_push($orderItems, $orderItem);

  $order = Order::create([
    'type' => 'example_order',
    'uid' => $this->loggedUser->id(),
    'store_id' => 1,
    'order_items' => $orderItems,
    'placed' => \Drupal::time()->getCurrentTime(),
    'state' => 'draft'
  ]);
  $order->save();

  $productVariation->field_quantity->value -= 1;
  $productVariation->save();

  $resultArray = array();
  $resultArray['order_id'] = $order->uuid();
  return new ResourceResponse($resultArray);
}
</code>
The purchased product ID is sent from the frontend in the request body. Drupal then loads the product variation and checks if the quantity is greater than zero (if it is available, this can only be seen written in comments). If it is available, it proceeds to create an order item type and an order, etc. The quantity is then reduced by one, and the product variation is saved.
Let's say customer one clicks checkout on the frontend and the order creation API is called resulting in the above PHP code running. However, very shortly after customer one clicks checkout, customer two also clicks checkout with the same product (quantity is one for the product). A problem arises if the order of execution is the following for the two requests:

Customer one check if available->it's available, continue
Customer two check if available->it's available, continue
Customer one create order, decrease quantity, save, etc.
Customer two create order, decrease quantity, save, etc.

Both customers are able to purchase a single product, and I need to refund someone. Can this scenario happen? If so, the solution would be to somehow lock the product variation entity until it is up to date. While it is locked nobody can read/write. Can this be done from PHP?
I appreciate the help in advance, and if anything is unclear, let me know, and I'll edit the post!
Comment: Drupal has a lock API. https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Lock%21LockBackendInterface.php/group/lock/10
Comment: Are you using a stock management module like https://www.drupal.org/project/commerce_stock?
Comment: This is common in most commerce systems. You can't sell what you don't have - so you should check before processing a payment if the item is still in-stock. If there is stock, proceed. Otherwise it should throw an error and let the user know that the item is now sold out.
Comment: @cilefen I am not. Can the module help in a headless Drupal setup as well?
Comment: @Kevin Exactly. But my problem is the checking and the updating is not atomic. So really the only solution is to lock the resource I am reading and intending to update. This is what I do not know how to do in Drupal.
Answer: There are many ways to handle stock preventing overselling ... from a pattern standpoint, not necessarily from a contrib standpoint. However, our least favorite version is using a field on the product variation itself, as that results in a product update on every purchase. In a high-volume scenario, that's going to really hurt your database... and as you've seen, it's not great for concurrency issues.
Rather than using a field on the product, we'd typically recommend a custom table tracking the product variation ID and stock level. When a customer starts a purchase, you might use a separate table to place a hold and then only decrement the stock level once that order is placed. Thus, when you want to determine if a product is available for purchase, you're actually looking up how many holds are active against how many remaining stock for a given product.
Then, to solve for concurrency, you'll need an additional check in the checkout flow. Prior to payment, or at least between payment authorization and capture, you need to confirm the stock you thought was there is still there. If it isn't, you need to error out (and void any authorization if you went that route) ... if it is, you capture and carry on. This will almost always entail custom code, as we've yet to encounter the same set of rules twice, to be honest.
Comment: A simple direct query against the field data table wouldn't be too taxing, but typically what happens is a full entity load. The real gains will be updates to the stock level not requiring a full variation entity load and update.
Comment: I see what you're saying here, but I do have a few questions. Firstly, if I have a separate table tracking stock, why is the confirmation of stock before payment less painful for the database than checking the quantity field belonging to the variation (the same goes for updating stock after payment)?  Secondly, in a low-volume scenario, does my solution along with using the lock API work?


IndentityServer3 sample HTTP Error 403.14 - Forbidden when running Host.Web

Question: I am running the IdentityServer3 sample from:
https://github.com/IdentityServer/IdentityServer3
in IISExpress. When I start the Host.Web application,  I get:
<code>HTTP Error 403.14 - Forbidden
The Web server is configured to not list the contents of this directory.
</code>
I simply cloned the sample and clicked run.
My guess is that I am not starting with the correct url. Unfortunately, there is no information or "Getting Started" page.
Answer: You need to know - IdentityServer3 is no longer supported. Is there any specific reason that you are trying to use it? Why don't you head for IdentityServer4 - Official documentation, GitHub (seems that you are just starting).
If you have any concerns that IdentityServer4 is .NET Core based, and you won't be able to use it with some old legacy clients - don't worry about that, it is fully compatible with the old projects.
Besides that - IdentityServer4 has a lot of examples, better documentation and more active community.
EDIT
But if you are so much willing to use IdentityServer3 - here is the documentation for the latest release and here are the samples.
But I stick to my words - if you are just starting, go for IdentityServer4.


How can I work out what network account my TFS 2008 instance is using to access Analysis Services?

Question: I'm building a new TFS 2010 environment and need to find out what network account my TFS 2008 instance is using to access Sql Server Analysis Services.  How do I find out?
Answer: You kilometreage/mileage may vary ...
Two places I checked.

Computer Management
Services (order the LogOn Column)

Picture tells a thousand pew-pews...

HTH ...
Comment: Thanks, found it in the login listed against the TFS services
Comment: what services where those (i tried to look for that but didn't know what to actually find).


Evaluate the following definite integral: $\int_{-3}^3(3x + 5)\,dx$

Question: I'm new to the topic of integration and I'm struggling big time with it.
I am trying to evaluate $\int_{-3}^3(3x + 5)\,dx$.
Any help is greatly appreciated.
Thank you
Comment: Do you know a function that its derivative is $3x$?
Comment: Do you know a function that its derivative is $5$?
Answer: Have you learned the Fundamental Theorem of Calculus yet?
If so, recall that you can evaluate definite integrals of $3x + 5$ using an antiderivative. In particular
$$
\int_{-3}^3 3x + 5 \,dx = \left[\frac{3}{2}x^2 + 5x \right]_{-3}^3
$$
Otherwise, you should draw a graph of this function and use simple geometry to find the integral - recall that the integral is related to the area between the function and the $x$-axis; if the area is above the $x$-axis, you count it positively, and if it is below, you count it negatively.
Further, because this function is so basic, you'll be able to calculate the areas involved using simple geometric formulae for triangles.
Comment: great answer +1
Answer: If you've learned the power rule for integration, then this will serve to refresh that learning. If you haven't learned the power rule, then you'll find this very helpful.
In general, if we need to integrate a polynomial, we use the rule:
$$\int_a^b {cx^n} \,dx = c\cdot\dfrac{x^{n+1}}{n+1}\Big|_a^b, \quad \forall n\in \mathbb Z, n\neq -1$$
In your case, we have the definite integral $$\int_{-3}^3 3x + 5 \,dx = \int_{-3}^3 3x^1 + 5x^0 \,dx = \int_{-3}^3 3x^1 \,dx + \int_{-3}^3 5x^0\,dx$$
Using the power rule on the right-hand side, and then evaluating the result at (upper-bound $-$ lower-bound) gives us $$\begin{align} \int_{-3}^3 3x^1 \,dx + \int_{-3}^3 5x^0\,dx & = 3\dfrac{x^{1+1}}{(1+1)}\Big|_{-3}^3 + 5\cdot \dfrac{x^{(0+1)}}{(0+1)}\Big|_{-3}^3 \\ \\ &= 3\cdot\dfrac{x^2}{2}\Big|_{-3}^3 + 5x\Big|_{-3}^3 \\ \\ & = \dfrac 32 ((3)^2 - (-3)^2) + 5(3 - (-3)) \\ \\ & = 0 + 5\cdot 6 \\ \\ &= 30\end{align}$$
Comment: Thank you. That was extremely helpful. We have been using the power rule. I am able to begin the questions but as I approach the last 2 lines I am unable to go any further. Your explanation was very clear. Think you
Comment: @amWhy: Nice feedback + 1
Answer: so we have
$\int{(3 \cdot x+5)}dx=3 \cdot x^2/2+5 \cdot x$
now  we insert bounds  $3$ and $-3$, we will do separately  when we insert bound values  and denote them by $A_1$ and $A_2$
$A_1=3 \cdot (3^2)/2+5 \cdot 3=3\cdot9/2+15$
$A_2=3 \cdot (-3)^2/2-15$
now total result is $A_1-A_2$
Answer: Integration of a Variable
Integration requires you to add $1$ to the power (exponent value) of the variable and then divide by that sum. (LHS) Below the power of the variable, $x$, is $1$, so you would add $1+1=2$ to get $x$ raised to the power of $2$ and then divide the entire term by $2$. (RHS)
$$ \int n^x = \frac{n^{x+1}}{x+1} \implies \int x \space dx= \frac{x^2}{2} + c$$
Integration of a Constant
With constants what you really have is $ax^0$ which is simply the constant itself, $a$, (anything raised to the power of $0$ is $1$). So following from above, when you add $1$, you get $1+0=1$ to get $x$ raised to the power of $1$ which is just $x$. So therefore the integral of any constant is the constant itself times $x$. See below.
$$\int a \space dx= ax + c$$
Applying those rules to the question:
$$\int_{-3}^3 3x + 5 \space dx = \left[\frac{3}{2} x^2 + 5x \right]_{-3}^3 = \left(\frac{3}{2} (3)^2 + 5(3) \right) - \left(\frac{3}{2} (-3)^2 + 5(-3)  \right) = \cdots$$
With definite integrals once you've calculated the integral, you substitute the lower and upper limit into the integral and calculate (subtracting the lower limit from the upper limit). From then on its just simple arithmetic.


Error accessing database after migration

Question: We've an old application made on Classic asp and we're migrating this to a new server.
until here everything works fine, our problem is when the application needs to access the database, we get the following error:
"An error occurred on the server when processing the URL. Please contact the system administrator.
If you are the system administrator please click here to find out more about this error."
The DSN connection is set up and tested.
Any idea why i'm getting this error?
UPDATE
LOG

2017-11-09 11:22:12 192.168.16.172 GET /testing/
  |55|80040e4d|[Microsoft][ODBC_SQL_Server_Driver][SQL_Server]Login_failed_for_user_'domain\machine-TEMP$'.
  80 - 192.168.1.122
  Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/61.0.3163.100+Safari/537.36
  - 500 0 0 109
Comment: Enable extended logging in your web.config and post the full error you see. Do this by setting `customErrors`to `off`.
Comment: I've posted the log which i have
Answer: You are using the computer account to connect to SQL Server. It currently has no rights to connect.
<code>[SQL_Server]Login_failed_for_user_'domain\machine-TEMP$'
</code>
So, open up SQL Server Management Studio and give it the needed rights.
<code>USE [master]
GO
CREATE LOGIN [domain\machine-TEMP$] FROM WINDOWS WITH DEFAULT_DATABASE=[master], DEFAULT_LANGUAGE=[us_english]
GO
</code>
After you've done that, open up the properties for the newly created account and give it the needed rights on the database used.
Even better would be altering the App Pool in IIS to use a service account and add that account to your SQL Server.


jQuery UI not working on FireFox

Question: jQuery Ui is working in Safari & Chrome but doesn't work at all in FireFox.
The code is too large to paste here so I have it located at the following URL...
http://opencalendars.com/alpha/v0.9/index.php (link has become broken over time & is no longer how it would have appeared when this question was asked.)
Comment: In what way is it not working?
Comment: In my FF browser it acts as if no CSS or Javascript is being used. As well as a friends browser.
Comment: what is this ocde supposed to do $(function() {
$('.').animate({ backgroundColor: "#89b7da" }, "slow");
});
Comment: On my local server there is content within the jQuery UI Tabs. It just animates something on load. Removing it doesn't effect the no CSS or JS problem.
Comment: @PhilipK - Please see my answers edit, I was able to duplicate and have it work locally.
Answer: This is working here
http://jsfiddle.net/BsG6q/4/
Comment: is it work without php inserts ? what kind of insert these are ? and where it is added...bottom line is your code is working just relax and first remove the php code and see is it working as standalone ( script and html ) than add php inserts...
Comment: What is this? A version you have edited? Not familiar with that site.
Comment: ah first you should be familiar with this site http://jsfiddle.net/ ;) nop i did't edited anything just copy the source from firefox and pasted there and it start working.... just try adding files 1 by one and you will catch the issue..otherwise its working with the files i added including style and ui styles with your js..
Comment: It is I've been trying to update it based on the jsfiddle.net/BsG6q/4 code, but I havn't had any lucky yet. It's getting kind of messy because there quire a few php inserts.
Comment: I copied the JS, CSS, and HTMl exactly and not working. It must have something to do with how the framework is set up on JSfiddle vs. http://code.jquery.com/ versions.

So current version on my local server is no PHP and still not working so must be framework.
Answer: the issue is with http://code.jquery.com/jquery-latest.min.js see http://jsfiddle.net/BsG6q/7/ for error in FFX.. change it to 1.6.2 and see.
the source of the problem looks like this line of code:
$( "#tabs" ).tabs({ selected: $.getUrlVar('p'), cache: true, spinner: 'Retrieving data...',fx: { opacity: 'toggle' } }
).find( ".ui-tabs-nav" ).sortable({ axis: "x" });;

$.getUrlVar('p') is undefined!!

saw a bunch of js errors on your  site in chrome
Uncaught TypeError: Object [object Object] has no method 'datetimepicker'
(anonymous function)scripts.js:27
f.extend._Deferred.e.resolveWithjquery-latest.min.js:16
f.e.extend.readyjquery-latest.min.js:16
f.c.addEventListener.B

and also this
GET http://opencalendars.com/alpha/v0.9/ajax/cal.php 500 (Internal Server Error)

Comment: Have updated the live version with version 1.6.2 and removed the 'selected: $.getUrlVar('p'),' code.
Didn't seem to help. The GET error occurs live but not on local server.
Comment: the js error doesnt occur on your local m/c and it doesnt load on ffx?  can u remve the datepicker just in case
Comment: Got it I updated version 1.6.2 and linked to the same UI that JSfiddle linked to.
Answer: I was able to reproduce the problem using Fire Fox and the URL.
I saved the file locally in Chrome and looked at it in Fire Fox and it was fine.
I edit the local file to point to your web server and it broke.
Clearly the problem is how your server is serving the css files.  Maybe they are not using UTF-8 -- maybe they are compressing and don't have the right headers?  Something is wrong with how they server the files that Fire Fox can't handle.
Best bet to debug -- fiddler 2.  Look at the content and the headers and see if it looks different form CSS files that work.
Sadly I don't have time to do that myself right now.

Original Ideas:
Try adding type="text/css" to the link statement and using a fully qualified path.
Also add a DOCTYPE element.
Comment: Added type & DOCTYPE. no luck.
Answer: Have you looked at you HTML? The DOCTYPE should be at the top...

Email firstname.lastname@example.com for details

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

That's not valid HTML...
Remove the div before the DOCTYPE, and Firefox should display it properly too, I'd guess...
:)
Comment: I have seen that but only happens when you click on the link labeled 'Advertise'.
When your on the page http://opencalendars.com/alpha/v0.9/index.php
It doesn't appear appove the DOCTYPE. And still doesn't work in FireFox.
Comment: I have removed the Message div and it doesn't solve the problem.
Comment: Try fixing these errors. If it STILL doesn't work, don't hesitate to call back... :) http://validator.w3.org/check?uri=http%3A%2F%2Fopencalendars.com%2Falpha%2Fv0.9%2Findex.php&charset=%28detect+automatically%29&doctype=Inline&group=0
Comment: I dnt think any of those errors should cos the probs that you are seeing
Comment: Maybe not. However, try firing up the error console in Firefox. It doesn't like your CSS at all. And the CSS it not valid, so why should it? http://jigsaw.w3.org/css-validator/validator?uri=http%3A%2F%2Fopencalendars.com%2Falpha%2Fv0.9%2Fcss%2Fstyle.css
Comment: shouldn't email address be obfuscated?

jQuery UI not working on FireFox


JSON.parse issue with single quotation

Question: I have below JSON string
var value = "{'type':'youtube','id':'https://www.youtube.com/embed/JlLGdc71LUc','title':'mental health & it's benifits for testqaabhi','playerId':'','playerKey':''}";

If I use JSON.parse(value); than it give me error. I just wanted to replace  single quote with double quote except that in it's string . Can anybody suggest any method. I had another solution using regular expression to replace it. But I'm calling replace method again and again. So If anybody can minimize it.
value.replace(/^{'/,'{"').replace(/'}$/,'"}').replace(/':'/g,'":"').replace(/','/g,'","')

JSON string is incorrect and coming from other source on which I don't have control. So can't update JSON string.
Comment: This is not a valid JSON string. All the field names need to have double quotes in a valid JSON
Comment: Can't you fix the string generator? Why do you have such string?
Comment: first do one thing, validate your JSON in jsonlint.com. Once its a valid JSON, then you can move ahead, otherwise try to work on JSON string to get with correct format
Comment: Unless this is coming to you from an external source, I would first fix the JSON as @AnandharamanBuvaneswaran suggested above. Everything should work out of the box afterwards.
Comment: It's not a valid  JSON and  title  should  be escaped  before  creating  JSON object.
Comment: JSON string is coming from other sources on which I don't have control. So can't update JSON string.
Answer: JSON.parse(value.replace(/'/g,"\"").replace(/"s/g,"'"))

Answer: {
"type": "youtube",
"id": "https://www.youtube.com/embed/JlLGdc71LUc",
"title": "mental health & its benifits for testqaabhi",
"playerId": "",
"playerKey": ""
}

I would be a valid JSON. Your JSON failed because you have used quote(') on the title.
use this
its benifits for testqaabhi
instead of
it's benifits for testqaabhi
Comment: I know that but JSON data is coming from other source on which I don't have control. So can't update JSON string.
Answer: value is an object. (creating from an object literal)
JSON.parse() is used to convert a string containing JSON notation into a Javascript object.
Your code turns the object into a string (by calling .toString()) in order to try to parse it as JSON text.
The default .toString() returns "[object Object]", which is not valid JSON; hence the error.
use JSON.stringify() function for convert your JS object to JSON object... after that you can call JSON.parse() for your JSON object
Answer: You can use this.
var xx="{'type':'youtube','id':'https://www.youtube.com/embed/JlLGdc71LUc','title':'mental health & it's benifits for testqaabhi','playerId':'','playerKey':''}";

JSON.parse(JSON.stringify(xx));

JSON.parse issue with single quotation


A Faster / More Scalable Approach to Twitter OAuth Dance in Rails?

Question: I'm running a Rails app on the Heroku Stack (complete with Memcached, DJ Asynchronous workers, MongoDB persistent storage).
Right now we use Twitter Oauth as the only authentication option on our site. (We plan to branch out to FB connect, OpenID, and/or Email/password eventually).
Ruby/Rails apps, as you probably know, don't support concurrency out of the box. On Heroku, you can spin up additional app instances (dynos), which increase your concurrency (concurrency capability = number of dynos), but each one costs $36/month.
In general, this hasn't been a problem, because the average request on the site takes <100 ms.
EXCEPT for Twitter OAuth. The OAuth-related requests to Twitter take, on average, around 3,500 ms.
So basically, when anyone logs in an entire app instance gets held up for 3-4 seconds.
Is there any decent way to mitigate this? Would it be weird to put these actions in asynchronous DJ workers? It could make logging in a little slower, but at least if a bunch of people are logging in at once and/or Twitter is being really slow, these processes do not affect the rest of the app / other web requests?
Any other ideas?
Answer: I would say that this advice is now superseded. I'd suggest you use OmniAuth instead, possibly with Devise if you need normal auth as well.
OmniAuth is a Rack app as suggested and you basically get all the "big" OAuth providers working in fell swoop.
There are 2 OmniAuth specific RailsCasts that walk you through exactly what's needed: OmniAuth Part 1 and OmniAuth Part 2
Answer: You could push the oAuth into a rack middleware app - then at least only a rack app gets spooled up instead of the whole rails stack. That should make it a little quicker (though it will still take up an instance).
That being said, there is no reason why you can't put authentication into it's own app, especially if it's all in the same domain (so any authentication cookies are still local to the domain). Though you'll have to be really careful of security issues - eg man-in-the-middle attacks etc. Better if somebody's already done the work/bugfixing for you :)
You can even have an authentication app on an independent app domain if you use rubyCAS: http://rubyglasses.blogspot.com/2009/12/rails-single-sign-on-with-rubycas.html


Why is my phpMyAdmin page not interpreted from raw PHP code?

Question: I am quite new to website construction. I have been practicing with MySQL and phpMyAdmin before, but only on localhost. It went well. But when I actually bought myself a domain name and changed the document root of my Apache to some other directory (other than public_html and such), I found it's not working as I expected it to.
It happened when I was trying to manage my database from a remote client. I typed in the URL of mywebsite/phpmyadmin, it gave me a 404 error. I ran a little research and found this page and followed the instructions, added Include /etc/phpmyadmin/apache.conf to /etc/apache2/apache2.conf. It worked to an extent that I don't get the 404 error any more. But it went more peculiar in that my website started downloading the raw php code file that looks will be rendered as my phpMyAdmin page, but the page is not showing.
Anyone help?
Comment: Oh I'm so sorry folks I forgot to provide my system info... Indeed I am running Ubuntu, 12.10. I can't try out the solutions right now, but I will as soon as I get back to my computers. Thanks guys! You are awesome! ^_^
Comment: Your apache server does not how to execute php code: http://stackoverflow.com/a/20740045/1566267
http://stackoverflow.com/a/18061391/1566267
Answer: /etc/apache2/apache2.conf indicates a debian-ish distribution. Did you install the libapache2-mod-php5 and php5-mysql packages? And did you run a2enmod php5?
Comment: Yes I am running Ubuntu. It appears that I have indeed installed all the packages you mentioned, and all my other php files are functioning just fine. I don't think the php interpreter is the problem. :\
Comment: Same issue here


Missing some Firebase methods in previous versions

Question: I'm trying to verify user's number with Firebase on iOS using a phone number using this tutorial. But I am use Firebase 3.7.1 so, this: Auth.auth().setAPNSToken(deviceToken, type: AuthAPNSTokenTypeProd) and many another code samples not work for me: I couldn't even find Auth class, but when I found FIRAuth.auth() method I couldn't find setAPNSToken method, after this I found FIRInstanceID.setAPNSToken() but even now I have a problem, this code:
FIRInstanceID.setAPNSToken(deviceToken, type: .Prod)

Causes an error:

Extra argument 'type' in call

But this:
FIRInstanceID.setAPNSToken(deviceToken)

Causes this error:

Cannot convert value of type 'NSData' to expected argument type
  'FIRInstanceID'

So, how can use this method in Firebase 3.7.1?
P.S. I really can't find Firebase 3.7.1 documentation, I can find docs only for the last version of Firebase. So, if someone can share a link with it, this will be the best help.
Answer: Phone number authentication was only introduced in Firebase SDK version 4.x. It is not available on 3.x or earlier.


Recharts render pie chart vertically

Question: I am using recharts library for pie charts.
I want to load pie chart for two values always.The chart is loading horizantally as you can see here starting from angle 0.
But i want it to be starting from angle 90 looking as below.

PS: Tried changing startAngle and endAngle values.
Answer: Well I guess it's still related with props startAngle and endAngle
It starts counting at degree 90. (It may be kind of counterintuitive)
If you try another value as below, it would become a vertical start pie
startAngle={-270}

Notice according to the document, the default value:

startAngle: 0
endAngle: 360

The diff equals 360 would show a full circle pie. You can try out other pairs, like
[-270, 90], [90, -270], [45, 405]

Recharts render pie chart vertically


What is RouteComponentProps?

Question: When I was searching for information about react, I saw RouteComponentProps like
import { RouteComponentProps } from 'react-router-dom';
const ~~~: React.FC<RouteComponentProps>

and
class BookingSiteOverview extends React.Component<RouteComponentProps<{}>

So I searched RouteComponentProps, but given information is too fragmented. RouteComponentProps is mentioned in Q&A only briefly.
I want to know what is this. What is it for and how to use it?
Please give me advice.
Answer: RouteComponentProps looks to be a Typescript interface definition of react-router-dom's route-props.
The RouteComponentProps prop-types definition may've been part of react-router-dom but isn't currently exported. I found the Typescript export in Definitely Typed.
export interface RouteComponentProps<Params extends { [K in keyof Params]?: string }> {
  match: match<Params>;
  location: H.Location;
  history: H.History;
  staticContext?: any;
}

This is just the way to define the react propTypes in Typescript, via interfaces.
Comment: If you need to use the `History` type in TypeScript, it needs to be imported from a library that react-router-dom uses: [history](https://reactrouter.com/web/api/history)

What is RouteComponentProps?


What is a good way of testing for a relationship between two count variables?

Question: I have counts of occurrences of two types of words (A and B) in several texts. What I would like to test is whether the frequencies of occurrence of both types of words across texts is 'correlated'. However, using Pearson's correlation is probably not correct, because my data is not continuous, and in addition the counts are often quite low (sometimes zero).
What is a good way to test my hypothesis?
Comment: @TrynnaDoStat the $\chi^{2}$ would be inappropriate because it ignores the *ordering* of count data, right?
Comment: @TrynnaDoStat ordering is critical in correlation between ordered variables.
Comment: [Spearman's correlation](http://en.wikipedia.org/wiki/Spearman's_rank_correlation_coefficient) seems appropriate?
Comment: @Matthew, I suppose I'd need to analyze proportions then, in order to factor out the text length. (The texts differ in length.) Is Spearman's correlation still a good choice for proportions?
Comment: Consider the chi-square test for independence. http://stattrek.com/chi-square-test/independence.aspx
Comment: @Alexis if I'm reading the question correctly, the order of the data is not of interest here. If ordering is of interest, then you are correct the chi-square test is inappropriate.
Comment: @Ben This thread is from 2014. :)
Answer: @Mattthew has answered your question: Spearman's $\rho$ will give you a measure of monotonic association between your variables. You can also perform inference on whether this correlation is, for example, different than zero using a straightforward t test.
To calculate $\boldsymbol{r}_{\textbf{S}}$ (assuming no ties):

Rank each of your variables independently.
Calculate the difference, $d_{i}$, between ranks for each observation/text (I am assuming from your question, that the measures are paired: so there's a count from text $A$ and a different count from text $B$, across n texts).
$r_{\text{S}} = 1 - \frac{6\sum_{i=1}^{n}{d_{i}^{2}}}{n\left(n^{2}-1\right)}$

The calculation for $\mathbf{r}_{\textbf{S}}$ (regardless of ties):

Rank each of your variables independently.

Calculations proceed as for Pearson's $r$ but using the ranked values ($r_A$ and $r_B$) of the before and after (or matched) observations:
$r_{\text{S}} = \frac{\sum_{i=1}^{n}{\frac{r_{A,i} - \overline{r}_{A}}{s_{r_A}} \times \frac{r_{A,i} - \overline{r}_{A}}{s_{r_B}}}}{n-1}$

To test for evidence $\mathbf{r_{\textbf{S}} \ne 0}$:

$\text{H}_{0}\text{: }r_{\text{S}} = 0$, $\text{H}_{\text{A}}\text{: }r_{\text{S}} \ne 0$

$t = r_{\text{S}}\sqrt{\frac{n-2}{1-r^{2}_{\text{S}}}}$

Base your rejection decision for $\text{H}_{0}$ on the t distribution, with $n-2$ degrees of freedom.

Pagano, M., & Gauvreau, K. (2000). Principles of Biostatistics (2nd ed.). Duxbury Press.
Comment: Can you please add a reference for the calculation of $r_s$?
Comment: Actually, there are two counts from each text. One count for one type of word (type A), and another for another type of word (type B).
Comment: Thanks, @Alexis. I realize that I didn't ask the right question. My hypothesis is not actually about a correlations of counts as such. Because the texts are of different lengths, there will be a correlation of counts even if there is no actual correlation of probabilities of occurrence. So I guess I really need to know whether there is a correlation between two ratios, i.e. (number of times word type A appeared)/(total number of words) and the same kind of ratio for word type B. Is Spearman's rho applicable to ratios?
Comment: In response to your first comment: yes, precisely, you have **paired measurements** on each text.
Comment: In response to your second comment, this is an oxymoron: "there will be a correlation of counts even if there is no actual correlation of probabilities of occurrence." However, I *think* you might mean that you are interested in correlations between counts inflated zero counts?
Comment: I'm not quite sure why it is an oxymoron. What I mean is this: let's assume that I have three texts and that the probabilities of occurrence of word A in these texts are 0.3,0.1,0.3 and those for word B are 0.1,0.2, and 0.3. The probabilities are not correlated. Let's assume that the number of words is 100 for the first text, 200 for the second text, and 300 for the third text. Thus the actual counts will be 30, 20, 90 and 10, 40, 90 respectively. These counts have a spearman correlation of 0.5. Am I missing something?
Comment: What does it mean for "a probability to be correlated?"
Comment: What I mean by that is that if the probability of occurrence of event A is high, so is the probability of event B, and vice versa. (For positive correlations.)
Comment: @usεr11852 Sure. Amplified a little for ties and no ties.
Comment: Cool, thanks (+1).


Why is my audio so high pitched on garageband?

Question: I recorded some music and downloaded it as a mp4. When I imported it into GarageBand the voices sounded like chipmunks. I checked to see the sample rate and it is at 32 khz. Apparently, that might be the issue. How do I check the track info and change it to 32 khz so the voices sound normal?
Comment: I don't use garageband, so I can't answer your question, but you want the imported audio upsampled to project sample rate, not project sample rate lowered to 32kHz.  Lowering your project sample rate will have a detrimental effect on the quality of every sound in the project.
Comment: @Edward That sounds like an answer.
Comment: I didn't post as an answer because I don't know how to do that in garageband, as I don't use it.  Anyone who does is welcome to post an answer.
Answer: My guess would be that the sample rate was misgauged during conversion. How did you originally record it? What's the original file format, and how did you convert it to mp4?
If you can, go back to your original recording, download it in the most lossless format possible (e.g. wav file). If it's originally a video file, then convert it to an audio file on your computer using a respected audio editor like Audacity (open source) or Goldwave (no affiliation). Then import the audio file into GarageBand.
In future, record audio using a dedicated audio recorder app with flexible export options. The one I use on Android lets me choose various filters, e.g. recording dialogue or music; various quality levels; and various export formats. But there are many good ones. Recording using your phone camera or a notes app or similar stand-ins for the real thing will lead to janky results.
Comment: @Tetsujin Certainly could have been, but my hypothesis here is that the encoding is borked (rather than that GB just can't read 32khz rates, though that is also a possibility worth investigating).
Comment: Might have been some kind of voice recorder/notes/memos app, at 32k.
Comment: (Another way to extract audio from a video file is with the open-source command-line program `ffmpeg` — the Swiss Army knife of media file conversion — as that can do so losslessly, and understands a huge range of formats.)
Comment: "I recorded some music"... great, now where is the wav file? +1


What is $x + O(x^2)$?

Question: Let $x \to 0$.
I wonder what is $x + O(x^2)$. I think it is $O(x)$, but I don't understand why is it true.
Is it also $\Theta(x)$?
And if it is $\Theta$ can I estimate it as $c \cdot x$?
Comment: See [here](https://en.wikipedia.org/wiki/Big_O_notation#Family_of_Bachmann.E2.80.93Landau_notations) and [here](https://www.khanacademy.org/computing/computer-science/algorithms/asymptotic-notation/a/big-o-notation).
Comment: @SimplyBeautifulArt I know about it, but the case when $x \to 0$ really confuses me.
Comment: @Eff My mistake, i was thinking about $o(x)$
Answer: Say that $f(x)$ is in $\mathcal O(x^2)$, this means that
$$|f(x)| \leq c|x^2|$$
for $|x|<\varepsilon$ for some $\varepsilon>0.$
Hence, for $|x|<\varepsilon$, we have that
$$|x+f(x)| \leq |x|+|f(x)| \leq |x|+c|x^2|.$$
It is true that $|x^2|<|x|$ for $|x|<1$, so if $\varepsilon<1$, then
$$|x|+c|x^2| \leq |x|+c|x|=(1+c)|x|.$$
In conclusion, $x+\mathcal O(x^2)$ is in $\mathcal O(x).$
Comment: Just one question is $O(x^2) = o(x)$ as $x \to 0$?I think it is...
Comment: If $f(x)$ is in $\mathcal O (x^2)$, then
$$\lim\limits_{x\to 0}\frac{f(x)}{x} = 0$$
so: yes.

What is $x + O(x^2)$?


Windows update looks completely different on two servers both running Windows Server 2012?

Question: I have a clean install of Windows Server 2012, and another server where I upgraded to 2012 from 2008.
I noticed that on the upgraded machine, when I type "Windows Update", an item for it appears in the start menu named "Windows Update", and when clicked a Metro-style full-screen UI appears for windows update.
Meanwhile, on the clean install of Windows Server 2012, there is no match for "Windows Update", although I can reach it indirectly by clicking the "View Update History", then clicking the breadcrumb in the address bar for Windows Update, all of which is a standard window that looks like it did in Windows 7.
So why are there two completely different looks for Windows Update on what is basically the same operating system?  Could it have something to do with the fact that on the upgraded machine I had "Windows Desktop Experience" installed?
Answer: Yes, the Windows Desktop Experience feature converts your Windows Server 2012 into something that looks exactly the same as Windows 8.
Hint: Use control panel (the classic one) and run Windows Update there instead.
Comment: No, if you enable "desktop experience" then the metro start menu is default. It's the same for everyone, feature-by-design according to Microsoft. One of the reasons why using 2012 for terminal services blows. Waiting for 2012 R2...
Comment: @Triynko All these comments are suited better to Microsoft directly (their technet forums). Nobody at Microsoft is going to read this and then fix the stuff you find buggy :)
Comment: I see.  Something else strange I noticed is that when logging in with remote desktop, the start screen is open and stuck.  It's not frozen; I can interact with it, but I can't dismiss it in any of the usual ways.  Pressing escape has no effect and hovering to the corners (difficult b/c it's on a multi-monitor setup where the screens meet) also has no effect.  The only way to escape the start menu is to press the start button to reactivate it or to click the "desktop" panel.  It's very strange behavior, and the start menu shouldn't even be visible by default upon connecting to the session.
Comment: No, in my comment I was talking about a clean install of 2012.  Both machines, with and without desktop experience, use the metro start screen.  The "stuck in start screen" issue is occurring on the machine without the desktop experience installed. In any case, going through control panel completely defeats the purpose of the accelerated start screen, where you can press Windows Key, type a few letters of what you want, then press enter to go there.  The "Windows Update" item should be present in both configurations.
Comment: The advantage of the new start screen isn't it's pretty icon layout, that's  basically useless.  The advantage is being able to press start, start typing something, and seeing a full-screen view of results with descriptions... something that was impossible with the old tiny start menu.  And it's great for terminal services too.  I'm just tripping up on some unexpected inconsistencies, like the missing "Windows Update" result (present in Windows 7 too), and the strange stuck behavior of the start screen.
Comment: There's also what I would call a bug in that the "start typing to search" feature is broken if you click in a blank area of the search results, the search bar goes away, and when you start typing again, nothing happens. The odd thing is it only happens if you have "Settings" results selected on the right. And it's not just that you clicked something, because if you click back to Apps, you can still just type to bring the search bar back. Once in settings, you have to mouse into the lower right corner, bring up the charms bar, and click search to bring it back, or exit out and restart.


How to use Chebyshev Polynomials to approximate $\sin(x)$ and $\cos(x)$ within the interval $[−π,π]$?

Question: I have approximated $\sin(x)$ and $\cos (x)$ using the Taylor Series (Maclaurin Series) with the following results:
$$f(x)=f(0)+\frac{f^{(1)}(0)}{1!}(x-0)+\frac{f^{(2)}(0)}{2!}(x-0)^2+\frac{f^{(3)}(0)}{3!}(x-0)^3+\cdots$$
$$\begin{align}\implies \sin(x)&=x-\frac{x^3}{3!}+\frac{x^5}{5!}-\frac{x^7}{7!}+\frac{x^9}{9!}-\cdots\\&=\sum_{n=0}^{\infty} \frac{(-1)^n}{(2n+1)!}x^{2n+1} \end{align}$$
$$f(x)=f(a)+\frac{f^{(1)}(a)}{1!}(x-a)+\frac{f^{(2)}(a)}{2!}(x-a)^2+\frac{f^{(3)}(a)}{3!}(x-a)^3+\cdots$$
$$\begin{align} \implies \cos(x)&=1-\frac{x^2}{2!}+\frac{x^4}{4!}-\frac{x^6}{6!}+\frac{x^8}{8!}-\frac{x^10}{10!}+\cdots \\&=\sum_{n=0}^{\infty} \frac{(-1)^n}{(2n)!}x^{2n} \end{align}$$
How can I use Chebyshev Polynomials to approximate $\sin(x)$ and $\cos(x)$ within the interval $[−π,π]$?
Thanks in advance!
Comment: It would be better to rephrase the question in more specific terms, like: "How to compute the Fourier-Chebyshev expansion of $\sin(x)$ and $\cos(x)$ over $[-1,1]$?" - and add your attempts. The link is quite irrelevant, you may assume we know how to approximate an exponential through Chebyshev polynomials.
Comment: Thanks! I've modified my question.
Answer: Assume that we want to approximate $\cos(x)$ over $I=[-1,1]$. The Taylor series gives:
$$ \cos(x) = \sum_{n=0}^{+\infty}\frac{(-1)^n}{(2n)!} x^{2n}\tag{1} $$
while the Fourier-Chebyshev series is given by:
$$ \cos(x) = J_0(1) + 2\sum_{n\geq 1}(-1)^n J_{2n}(1) T_{2n}(x)\tag{2}$$
where:
$$ \frac{2}{\pi}\int_{-1}^{1}\frac{\cos(x) T_n(x)}{\sqrt{1-x^2}}\,dx = \frac{2}{\pi}\int_{-\pi/2}^{\pi/2}\cos(\cos x)\cos(nx)\,dx\tag{3}$$
is a Bessel function of the first kind and $T_{n}(x)$ is a Chebyshev polynomial of the first kind. Since both $x^n$ and $T_n(x)$ are bounded by $1$ on $I$, the accuracy of the approximation just depends on how fast $J_{2n}(1)$ decays to zero. Since:
$$ J_{2n}(1) = \sum_{l\geq 0}\frac{(-1)^l}{4^{l+n}(2n+l)!},\qquad \left|J_{2n}(1)\right|\approx\frac{1}{4^n(2n)!}\tag{4}$$
we have that the Taylor approximation pointwise outperforms $(2)$ in the region $|x|\leq\frac{1}{2}$, while the $L^2$-approximation $(2)$ is more accurate than $(1)$ near the endpoints of $I$, and in uniform terms. However, its coefficients are less trivial to compute.
It is also interesting to mention that, by expanding $T_{2n}(x)$ and equating the coefficients of $x^{2m}$ in $(1)$ and $(2)$ we get an interesting identity about the Bessel function of the first kind. The same happens if we integrate the square of both sides of $(2)$, multiplied by $\frac{1}{\sqrt{1-x^2}}$, over $I$.
Here we have a graph of the approximation error for $n=5$. The Taylor series gives the blue graph, the Fourier-Chebyshev series gives the red graph.
$\hspace1in$
This is the same graph over the subinterval $\left[-\frac{2}{3},\frac{2}{3}\right]$:
$\hspace1in$
Comment: Thanks! What is the difference between Chebyshev Polynomials and the Fourier-Chebyshev series?
Comment: Also, is there a way to approximate Sine and Cosine using Chebyshev Polynomials which have results similar to http://caig.cs.nctu.edu.tw/course/NM07S/slides/chap4_1.pdf Page 9?
Comment: @DavidLin: Chebyshev Polynomials : Fourier-Chebyshev series = $\sin(nx)$ : Fourier series. Chebyshev polynomials are a complete base of $L^2(-1,1)$ with respect to the inner product $\int_{-1}^{1} \frac{f\cdot g}{\sqrt{1-x^2}}\,dx$, you should know this. I do not understand your second question: are you asking me to write $x^n$ in terms of Chebyshev polynomials or the opposite?
Comment: Thanks again! My second question is asking if there is a way to express sin(x) and cos(x) each in one simple line of infinite Chebyshev Series. Sorry, I am only a highschool student so I don't really quite understand 70% of the high maths in your answer LOL. Thanks again for answering and helping out!
Comment: @DavidLin: my $(2)$ gives $\cos(x)$ in terms of Chebyshev polynomials. To have a similar expansion for $\sin(x)$, too, just differentiate both sides of $(2)$.
Comment: Oh, thanks!! :)
Comment: There should be $J_{2n}(1)=\sum_{l\ge 0}\frac{(-1)^l}{4^{l+n}l!\, (2n+l)!}$ instead of $J_{2n}(1)=\sum_{l\ge 0}\frac{(-1)^l}{4^{l+n}\, (2n+l)!}$.


Diagonal perturbation of skew-symmetric matrix

Question: A skew-symmetric real matrix $A$ has zeros on the diagonal and eigenvalues that are purely imaginary.
If I perturb any diagonal entry $A_{ii}=0\rightarrow -\epsilon$ where $\epsilon>0,$ simulations suggest that all the eigenvalues of the perturbed $A$ now has eigenvalues that all have negative real part. How can this be shown?
Thank you.
Comment: What size matrix are you doing simulations on?
Comment: @Paul It seems to held for any $n\times n$ real skew-symmetric matrix.
Comment: Do you only perturb a single diagonal entry, leaving all the others at zero?
Comment: @PaulAljabar Yes, but I don't think it makes much of a difference.
Comment: The correct terms are "perturb" and "perturbed", by the way.
Comment: @Omnomnomnom Thanks, I had been wondering about that! :)
Answer: It is well known that if $M + M^T$ is negative semi-definite, then the eigenvalues of $M$ have non-postive real part (see this post, for instance).
In your case, we find that $M = A - \epsilon \,e_ie_i^T$ is such that $M + M^T$ is a diagonal matrix with non-positive real entries on the diagonal.  We conclude that $M + M^T$ is negative semi-definite, from which we deduce that the eigenvalues have non-positive real part, as you suspected.

Notably, there are examples where we still have some imaginary eigenvalues in the resulting matrix.  In particular:
$$
\pmatrix{0&0&0\\0&0&-1\\0&1&0} \to \pmatrix{-\epsilon&0&0\\0&0&-1\\0&1&0}
$$
has eigenvalues $-\epsilon, \pm i$.  I suspect that such an "unlucky" event has probability zero if $A$ is a suitably "random" skew-symmetric matrix.  An obvious perturbation to move the eigenvalues over is to consider $A - \epsilon I$ instead (that is, apply the subtraction to all diagonals).
Comment: Yes, I used the term non-positive to include the zeros on the other diagonal entries.  For any matrix $A$ and eigenvector $x$ of $A$, note that
$$
(A - \epsilon I)x = Ax - \epsilon x = \lambda x - \epsilon x = (\lambda - \epsilon)x
$$
so, we have shifted the entire spectrum over by $\epsilon$.
Comment: In fact, I'm not relying on diagonalizability at all.  $\lambda$ is an eigenvalue if and only if there is an associated eigenvector.  I suppose that what I have technically shown is that for any $\lambda$ in the spectrum of $A$, $\lambda - \epsilon$ is in the spectrum of $A - \epsilon I$.  As it turns out, the converse is just as easy to show.  More generally, we have the "spectral mapping theorem" (surprisingly difficult to google, but you might find it in the index of your textbook).
Comment: Thank you. 1) In line three you write "$M+M^T$  is a diagonal matrix with non-positive real entries on the diagonal", but isn't this matrix the zero matrix with a $-2\epsilon$ added on entry $ii$? Did you use the term "non-positive" to include the zeros on the other diagonal entries?

2) How can one show that $A-\epsilon I$ has eigenvalues with *exclusively* negative real parts? I'm probably missing something obvious.
Comment: I see. $A$ must be diagonizable though, right (but there is a zero probability of hitting a singular matrix when doing simulations over cont. dist.s)?


Modal de Confirmação com codeigniter

Question: Preciso fazer um modal de confirmação de exclusão.
No html
<a class="btn btn-primary" onclick="Confirmar(<?=$dados->id;?>)">Excluir

A funcao

Modal de Confirmação com codeigniter


Clustering coefficient (equation) for a regular ring lattice

Question: Hi, I would like to understand why the clustering coefficient for a regular ring lattice has the following equation: $C(v) = \frac{3(d-2)}{4(d-1)}$.
Do you know how to derive it? Or where I can find a derivation of it?
So far I found just this explanation:
http://www.hcs.harvard.edu/~cs134-spring2017/wp-content/uploads/2017/01/section2.pdf.

However, that is not clear to me and already the first paragraph is not convincing. I can show her below my concerns about the first paragraph:
Answer: I think two notions of neighbors are competing here: neighbors in the graph and neighbors in the ring (they are the same in your first example, but not in the last figure). 'Hops' seem to refer to moves on the ring, not in the graph (again, this makes a difference only on the second example). In addition, when the author mentions "points", I think she refers to elements of $S$ only (and then your objection to (d) falls). Does this work any better?


Server 2012 Cannot find C: Boot to cd

Question: Server 2012 R2
ESXI 6
I am having an issue with resetting the local admin password on a windows server 2012 VM.
I first booted to a windows server 2012 cd, hit the repair option -> toubleshooting -> command prompt
c:

The system cannot find the the drive specified

wmic logicaldisk get name

name

d:

x:

Neither of these are the drive where the OS lives.

So i booted to a windows 8 recovery disk
Couple other option when i select the repair windows option under that recovery console i get an error:
The drive where windows is installed is locked.

I have tried various way to unlock it but cannot get anywhere.
Things I have tried
diskpart

list disk

there are no fixed disks to show.

bootrec /ScanOS

Total identified Windows installations: 0

Why is the local c: not showing up?
If i reboot the vm and not boot to CD the OS will load fine. Just can't log in.
UPDATE:
I just tried to install the OS from the boot media, and could not find the local disk there either, defiantly a driver issue, I will try again tomorrow when i find the right driver and can slipstream it into the ISO
Answer: Your partition/disk got removed (within ESX) as your list disk  within diskpart find nothing.
Check your hardware. A human error that removed the partition, or just unplugged it maybe if lucky. (or a storage array error at your esx level)
Comment: If he can get into the VM, but not the OS, it wouldn't be a storage issue unless the VMX and VMDK are on separate datastores on separate storage systems. It sounds like the VMDK was disconnected from the VM like you said.
Answer: Sorry to the user that attempted to answer they question but unfortunately you are both incorrect.
I was actually able to fix the issue and completely forgot about the question here.
I had to call VMware, turns out we were on a older version of vcenter and had to upgrade, had to pay the licensing cost and get the version that supported vAPPS, go through a very long migration process, get everything over to the new systems and decomm/reuse the clusters one by one to get the all over.
I couple hours of downtime later and not so happy CIO we were able to get everything setup and able to change the admin password through vcenter.
All this because the server owner forgot his password.
The reason we went through all this for one server is to be able to not have to go through this again in the future.
Answer: Click on the VM, click "Edit Settings". There should be a Hard Drive shown. If it's greyed out or there is no Hard Drive there, then that is why it can't be seen. If it's simply missing, you can add it back by selecting Add... and Hard Drive. Select Next and when it asks if this should be new or existing, select Existing. Browse your datastores for the folder your VM is in and attach the VMDK. Should be good to go after that.
If a snapshot was corrupted, this could also cause a problem with accessing the disk. If the HDD is there, but is showing mounted as /vmname-000001.vmdk or something like this, it is a snapshot and if it is missing from your VMX file, this might be the problem as well. If so, you'll likely need to restore from backup or call VMware.

Server 2012 Cannot find C: Boot to cd


Can't Block https://facebook using squid Transparent

Question: I'm using Squid Proxy 3.1 as transparent proxy server, I want to block facebook.com but while listed in blocked list , Some user's accessing facebook using https, how can i block only https for facebook
Comment: You need to block all the IP addresses it maps to. With `https`, you don't get to see the name of the server they're trying to reach, only the IP address.
Comment: Why does it need to be a transparent proxy?  As a configured proxy, you'll be able to actually work with the HTTPS requests sent by clients.
Comment: I Have used every IP's Of facebook too
Here are the list

.facebook.com
126.96.36.199/20
184.108.40.206/21
126.96.36.199/21
126.96.36.199/24
22.214.171.124/20
22.214.171.124/21
126.96.36.199/24
220.127.116.11/21
184.108.40.206/19
184.108.40.206/20
188.8.131.52/24
220.127.116.11/20
220.127.116.11/24
188.8.131.52/22
188.8.131.52/22
184.108.40.206/18
188.8.131.52/19
22.214.171.124/24
188.8.131.52/19
22.214.171.124/22
220.127.116.11/21
188.8.131.52/18
126.96.36.199/19
188.8.131.52/24
22.214.171.124/24
184.108.40.206/24
188.8.131.52/24
18.104.22.168/24
126.96.36.199/24
188.8.131.52/24
220.127.116.11/24
126.96.36.199/24
22.214.171.124/24
Comment: If i mentioned the proxy settings in Browser user's used to change it, so what i need to use it, And my squid Server have 2 Ethernet to route
Comment: `If i mentioned the proxy settings in Browser user's used to change it` - Update your firewall so if they do change it they won't be able to access the Internet.  That means block all outgoing traffic that doesn't pass through the proxy.  You can make exceptions for a few sites you explicitly whitelist.
Comment: ok let me try and ill be back , thanks for spending your precious times
Comment: If you wanna block something on HTTPS protocol you'll need to know what's on the SSL tunnel, so either you have a PaloAlto style appliance / Squid module able to handle SSL Traffic OR ultimatly you could be able to trick your users since if you're on Corporate environnement you're able to control DNS which (at least most of time) are not using SSL.
Answer: I think you can get the most up-to-date list of Facebook IP addresses using the folowing query
<code> whois -h whois.radb.net '!gAS32934'
</code>
The current list is somewhat longer than the one in your comment above. It should be fairly easy to parse the output of that query and load it into your firewall.
Answer: And if you decide to go explicit proxy way, be sure to setup ICAP web filtering with Squid and (possibly) HTTPS/SSL bumping. In this case SquidGuard will be able to filter actual HTTPS urls. If it is not possible to perform HTTPS filtering - use qlproxy to block access to CONNECT:443 request for facebook.com domain name only as you require.
Comment: Can i use it in same squid transparent ? what i'm using now ?
Comment: Probably something like http://6pmsolutions.com/2013/11/18/squid-transparent-ssl-interception/
Comment: ok let me have a look
Answer: Try this in squid.conf:
<code>acl blockfb dstdomain -i ".facebook.com"
http_access deny blockfb
</code>
Since the initial CONNECT request still comes through as HTTP, it should be able to catch it and block it.


In MVC what is difference between partial view and strongly typed view?

Question: Question is the title itself. I am new to MVC and I am now following self learning. Kindly give me answer which is clear for a fresher to MVC. Thanks.
Comment: why negative  I have searched in Google . But I could n't get a clear idea. :(
Answer: A partial view is nothing more than a "piece" of Html that you can keep in a separate file that you can reuse in other views. Sort of like UserControls in ASP.NET WebForms.
A Strongly Typed view means it has a ViewModel associated to it that the controller is passing to it and all the elements in that View can use those ViewModel properties
You can have strongly typed partials as well. Meaning that piece of Html needs specific data so you type it to a certain ViewModel
Here is an example of a Strongly Typed View
@model SomeViewModel

...// all the html comes after

A view that is not strongly typed does not have a @model SomeViewModel line
Here's an example of a controller action that renders a normal view without a ViewModel
public ActionResult Index() {
    return View();
}

Here's one that renders a strongly typed View
public ActionResult Index() {
    var model = new SomeViewModel();
    return View(model);
}

And the view makes use of that ViewModel by having the @model SomeViewModel at the top of the file.
So now that the view has a ViewModel I can display elements that are bound to the ViewModel like
@Html.TextBoxFor(m => m.FirstName)
@Html.CheckBoxFor(m => m.IsAwesome)

So any data entered into those fields are bound to the ViewModel. When the user clicks the submit button, those entered values get sent back to the server.
As I said before, partial view is a reusable piece of Html. So in that same view I can add in my partial. Let's say I have a partial view that contains a standard bit of Html that I want to reuse all over my site, like a Footer
I can create a .cshtml file and put this inside it

 footer text here

And then include it on any View, doesn't matter if it's strongly typed or not, it's just reusable Html
@model SomeViewModel

@Html.TextBoxFor(m => m.FirstName)
@Html.CheckBoxFor(m => m.IsAwesome)

{@Html.RenderPartial("MyFooter")}

Comment: Thanks for answer. So what is the advantage ? Can u explain little bit more ?
Comment: @VeeKeyBee This really is a 'tutorial'-esque question. Have you tried searching google for your issue?
Comment: @VeeKeyBee I just tried to google it, and the first result was the answer: http://www.google.com/#hl=en&output=search&sclient=psy-ab&q=What+is+the+difference+between+a+partial+view+and+a+strongly+typed+partial+view+in+ASP.NET+MVC&oq=What+is+the+difference+between+a+partial+view+and+a+strongly+typed+partial+view+in+ASP.NET+MVC&aq=f&aqi=&aql=&gs_l=hp.3...936.13577.0.138126.96.36.199.126.96.36.199.4782.59j10.69.0...1.0.4ptEDgYwJtg&pbx=1&bav=on.2,or.r_gc.r_pw.r_qf.,cf.osb&fp=3fbf9333af451b8d&biw=1920&bih=979
Comment: @GeorgeStocker Thanks again for explanation and let me search in google. And surely comeback. Hope your help again. :). I saw it bur it hard for me digest the code. Let me read it once again.