Prove that $S(x) = \sum_{n = 0}^{+ \infty} \frac{n!}{1.3....(2n + 1)} x^{2n + 1}$ is solution to $(E): (x^2 - 2)y' + xy + 2 = 0 $

Question:
Prove that the power series defined as:
$$ S(x) = \sum_{n = 0}^{+ \infty} \frac{n!}{1.3....(2n + 1)} x^{2n + 1} $$
is solution to the differential equation:
$$ (E): (x^2 - 2)y' + xy + 2 = 0 $$
and find its expression.

So far I found:
$ S'(x) = \sum_{n = 0}^{+ \infty} \frac{n! (2n + 1)}{1.3....(2n + 1)} x^{2n} $
$$ \implies S'(x) = \sum_{n = 0}^{+ \infty} \frac{n! (2n)}{1.3....(2n + 1)} x^{2n} + \sum_{n = 0}^{+ \infty} \frac{n!}{1.3....(2n + 1)} x^{2n} $$
$$ \implies x^2 S'(x) = x \sum_{n = 0}^{+ \infty} \frac{n! (2n)}{1.3....(2n + 1)} x^{2n + 1} + x\sum_{n = 0}^{+ \infty} \frac{n!}{1.3....(2n + 1)} x^{2n + 1} $$
$$ \implies x^2 S'(x) = x \sum_{n = 0}^{+ \infty} \frac{n! (2n)}{1.3....(2n + 1)} x^{2n + 1} + xS(x) $$
I do not see how to proceed to the other terms.
Answer: $$S(x) = \sum_{n=0}^\infty \frac{n!}{1\cdot3\cdot\cdots\cdot(2n-1)\cdot(2n+1)} x^{2n+1} \\
\implies S'(x) = \sum_{n=0}^\infty \frac{n!}{1\cdot3\cdot\cdots\cdot(2n-1)} x^{2n}$$
The left side of the ODE is then
$$\sum_{n=0}^\infty \frac{n!}{1\cdot3\cdot\cdots\cdot(2n-1)} x^{2n+2} - 2 \sum_{n=0}^\infty \frac{n!}{1\cdot3\cdot\cdots\cdot(2n-1)} x^{2n} + \sum_{n=0}^\infty \frac{n!}{1\cdot3\cdot\cdots\cdot(2n-1)\cdot(2n+1)} x^{2n+2} + 2$$
Combine the series with the same-degree terms.
$$2 \sum_{n=0}^\infty \frac{(n+1)!}{1\cdot3\cdot\cdots\cdot(2n-1)\cdot(2n+1)} x^{2n+2} - 2 \sum_{n=0}^\infty \frac{n!}{1\cdot3\cdot\cdots\cdot(2n-1)} x^{2n} + 2$$
Shift the index on the first sum.
$$2 \sum_{n=1}^\infty \frac{n!}{1\cdot3\cdot\cdots\cdot(2n-3)\cdot(2n-1)} x^{2n} - 2 \sum_{n=0}^\infty \frac{n!}{1\cdot3\cdot\cdots\cdot(2n-1)} x^{2n} + 2$$
Join the constant term to the first sum and we're done.
$$2 \sum_{n=0}^\infty \frac{n!}{1\cdot3\cdot\cdots\cdot(2n-1)} x^{2n} - 2 \sum_{n=0}^\infty \frac{n!}{1\cdot3\cdot\cdots\cdot(2n-1)} x^{2n} = 0$$

To get a closed form for $S$, observe that
$$\frac{n!}{1\cdot3\cdot\cdots\cdot(2n-1)} = \frac{n!\cdot2\cdot4\cdot\cdots\cdot2n}{1\cdot2\cdot3\cdot4\cdot\cdots\cdot(2n-1)\cdot2n} = \frac{2^n\cdot(n!)^2}{(2n)!} = \frac{2^n}{\binom{2n}n}$$
Compare this to the series expansion of the square of $\arcsin$,
$$\arcsin^2(x) = \sum_{n=0}^\infty \frac{2^{2n-1}}{n^2\binom{2n}n} x^{2n}$$
We can then find $S'$ in terms of derivatives of $\arcsin^2(x)$, and recover $S$ by integrating.

 Differentiate $\arcsin^2$ twice and multiply by $2x$ as needed to obtain
 $$\frac{2x\arcsin(x)}{\sqrt{1-x^2}} = \sum_{n=0}^\infty \frac{2^{2n}}{n\binom{2n}n} x^{2n}$$
$$\frac{x^2\sqrt{1-x^2}+x\arcsin(x)}{(1-x^2)^{3/2}} = \sum_{n=0}^\infty \frac{2^{2n}}{\binom{2n}n} x^{2n} = S'\left(\sqrt2\,x\right)$$
 and upon replacing $x\mapsto \frac x{\sqrt2}$,
 $$S'(x) = \frac{x^2\sqrt{2-x^2}+2x\arcsin\left(\frac x{\sqrt2}\right)}{(2-x^2)^{3/2}}$$
 By the fundamental theorem of calculus, noting that $S(0)=0$, we have
 $$S(x) = \int_0^x \frac{y^2\sqrt{2-y^2}+2y\arcsin\left(\frac y{\sqrt2}\right)}{(2-y^2)^{3/2}} \, dy = \frac{2\arcsin\left(\frac x{\sqrt2}\right)}{\sqrt{2-x^2}} - x$$
 as long as $|x|<\sqrt2$.
Comment: In the first sum, rewrite the coefficient as$$\frac{n!}{1\cdot3\cdot\cdots\cdot(2n-1)}=\frac{(2n+1)n!}{1\cdot3\cdot\cdots\cdot(2n-1)\cdot(2n+1)}$$Then adding the two $x^{2n+2}$ sums together, we get a coefficient of$$\frac{(2n+1)n!+n!}{\cdots}=\frac{2(n+1)n!}{\cdots}=\frac{2(n+1)!}{\cdots}$$
Comment: I've added a few more details to my answer
Comment: After combining the series with the same degree terms, I don't see why on the nominator we have $(n + 1)!$. Can you tell me what I am missing? Thank you.
Comment: Ah, I see. How can I get the explicit expression of $S$? I am stuck in that part too, thank you for your help.
Comment: Accepted answer, thank you so much for your help.


Why does this shell script fail if I split it in two lines?

Question: I'm very comfortable using the shell, but I don't know much about shell scripting. Today I cam across a tiny shell script for fixing the node-webkit libudev.so.0 problem: https://github.com/rogerwang/node-webkit/wiki/The-solution-of-lacking-libudev.so.0
As you can see, solution one instructs to create a shell script with the following code in it:
LD_LIBRARY_PATH=/home/omi/nw:$LD_LIBRARY_PATH ./nw $*

My understanding of what is happening is the following:
1) Declare the variable LD_LIBRARY_PATH, and assign a value to it, in this case it is the path to the nw directory where we have previously created a symlink to libudev.so.1. Then, append the previous value of $LD_LIBRARY_PATH to the new value. Then execute the nw binary passing the arguments that were passed to the shell script.
This works well, as expected, but if I split the code in two lines like so:
LD_LIBRARY_PATH=/home/omi/nw:$LD_LIBRARY_PATH
./nw $*

It does not work. The shell script executes without any errors, but the node-webkit application doesn't run. Instead we get the error about libudev.so.0 missing. Why is that?
Also, it seems like the path you add (/home/omi/nw in this case) can be anything. I tried using /home/, /home/akjfd/, and other variations, and the script always worked as expected. Why is that? (I finally left it with the correct path pointing to where I created the symlink)
PS. A bit out of topic, I found out that creating a symlink to libudev.so.1 in the same directory (/lib64/ in Fedora 18 64bit) and calling it libudev.so.0 works as well without having to create the shell script, but I would not recommend it since you would be polluting the /lib64/ directory, and it may cause problems in your system.
Answer: Commands that are prefixed by a variable assignment run in a modified environment.
LD_LIBRARY_PATH=/home/omi/nw:$LD_LIBRARY_PATH ./nw $*

is (roughly) equivalent to
OLD_PATH="$LD_LIBRARY_PATH"
export LD_LIBRARY_PATH=/home/omi/nw:$LD_LIBRARY_PATH
./nw $*
LD_LIBRARY_PATH="$OLD_LIBRARY_PATH"

./nw runs in an environment where LD_LIBRARY_PATH is set to the given value, but nothing in the current environment is changed.
Your two-line command is equivalent to
LD_LIBRARY_PATH=/home/omi/nw:$LD_LIBRARY_PATH; ./nw $*

(note the semicolon). If LD_LIBRARY_PATH wasn't already marked for export to the environment, it is simply a local shell variable, and is not inherited by ./nw when it runs.
Comment: Thanks a lot. This clarifies everything for me :D
Answer: Here's your first script:
LD_LIBRARY_PATH=/home/omi/nw:$LD_LIBRARY_PATH ./nw $*

That command sets LD_LIBRARY_PATH in the environment of the child process (which runs nw).
Here's your second script:
LD_LIBRARY_PATH=/home/omi/nw:$LD_LIBRARY_PATH
./nw $*

That script sets the LD_LIBRARY_PATH shell variable.  It doesn't modify the environment of any process, unless the shell is exporting LD_LIBRARY_PATH, which doesn't happen by default.  You need to ask the shell to export LD_LIBRARY_PATH at least once to make that happen, using the export command.  Example:
export LD_LIBRARY_PATH=/home/omi/nw:$LD_LIBRARY_PATH
./nw $*

You can also export separately from setting the variable, like this:
LD_LIBRARY_PATH=/home/omi/nw:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH
./nw $*

Comment: Thanks a lot for your explanation. I makes everything clear for me :D I'm marking the other answer as my answer just because it shows earlier, but yours is as valid, and as helpful.


Index notation and differentiation

Question: Let $x_i$ such that $i=1,2,\ldots,n$, and $\vec{x}=(x_1,\ldots,x_n)$
Define $$A:= M_{ij}(\vec{x})\dot{x}^i\dot{x}^j$$ where Einstein summation applies.
Also, $M$ is symmetric and invertible -- a metric.
What then is ${\partial \over \partial \vec{x}}A$ and ${\partial \over \partial \dot{\vec{x}}}A$?
I can't remember how this sort of index notation work, could someone please help?
Also, if anyone has any good references on the subject, and would not mind sharing, that would be greatly appreciated.
Answer: Valentin's answer is quite correct, but for a neophyte it can still be daunting. So I would like to remind to you that dummy indices don't matter when we sum over them, so:
$$ A = M_{ij}(x) \dot{x}^{i}\dot{x}^{j} = M_{kl}(x)\dot{x}^{k}\dot{x}^{l}.$$
Remember, Einstein's summation convention says when an index is repeated, and one is "upstairs" while another is "downstairs", then we sum over it...thus its a dummy index.
(Contrast this with what Misner, Thorne, and Wheeler's Gravitation calls the "Euclidean summation convention" where we just sum over any repeated index, regardless whether it's repeated downstairs or upstairs. So Euclidean has $M_{ii}={M^{i}}_{i}=M^{ii}=\sum_{i}M_{ii}$ whereas Einstein says this is just the diagonal entry of $M$)
This is important because when we consider the vector $\vec{v}=\partial A/\partial\dot{\vec{x}}$ it has components
$$\begin{aligned}
 v_{k}&=\frac{\partial A}{\partial \dot{x}^{k}}\\
&=\frac{\partial M_{ij}(x)}{\partial\dot{x}^{k}}\dot{x}^{i}\dot{x}^{j}
+M_{ij}(x)\frac{\partial\dot{x}^{i}}{\partial\dot{x}^{k}}\dot{x}^{j}
+M_{ij}(x)\dot{x}^{i}\frac{\partial\dot{x}^{j}}{\partial\dot{x}^{k}}\end{aligned}$$
(where we use the product rule), and we have
$$\frac{\partial\dot{x}^{j}}{\partial\dot{x}^{k}}={\delta^{j}}_{k}$$
be the Kronecker delta, in abstract index notation. Thus we have our components be
$$\begin{aligned}
 v_{k}&=\frac{\partial M_{ij}(x)}{\partial\dot{x}^{k}}\dot{x}^{i}\dot{x}^{j}
+M_{ij}(x)\frac{\partial\dot{x}^{i}}{\partial\dot{x}^{k}}\dot{x}^{j}
+M_{ij}(x)\dot{x}^{i}\frac{\partial\dot{x}^{j}}{\partial\dot{x}^{k}}\\
&=0+M_{ij}(x){\delta^{i}}_{k}\dot{x}^{j}+M_{ij}(x)\dot{x}^{i}{\delta^{j}}_{k}\\
&=M_{kj}(x)\dot{x}^{j}+M_{ik}(x)\dot{x}^{i}.
\end{aligned}$$
Now we use the fact that $M$ is a symmetric matrix to rewrite this as
$$M_{kj}(x)\dot{x}^{j}+M_{ik}(x)\dot{x}^{i}=M_{jk}(x)\dot{x}^{j}+M_{ik}(x)\dot{x}^{i}.$$
Then we use the fact that we can rewrite dummy indices as we please,
$$M_{jk}(x)\dot{x}^{j}=M_{ik}(x)\dot{x}^{i}.$$
So we get Valentin's result
$$ v_{k} = 2M_{ik}x^{i} $$
where we sum over $i$, using Einstein's convention.
Comment: Thank you very much for the detailed explanation!
Comment: One last warning: mathematicians often use "Einstein's summation convention" sloppily and ambiguously, as strange as it sounds they abuse language and sometimes call "Euclidean summation convention" incorrectly Einstein summation. So be careful! I know representation theory commits this crime a lot. But it's a misdemeanour, not a felony...
Answer: $\displaystyle \frac{\partial}{\partial \vec{v}} F$ is a shorthand notation for a vector whose components are $\displaystyle \frac{\partial}{\partial v^j}F$. It is extensively used in calculus of variations in the multivariable case for writing out Euler-Lagrange equations, or in the proof of Noether's theorem, for example.
In your case, apparently
$$\frac{\partial A}{\partial \vec{x}}=\frac{\partial M_{ij}(\vec{x})}{\partial \vec{x}}\dot{x}^i\dot{x}^j$$
$$\frac{\partial A}{\partial \dot{\vec{x}}}=2M_{ij}\dot{x}^i$$

Index notation and differentiation


Loopback password encryption vis-a-vis rails AES password

Question: We have an existing app which is developed using rails but we are migrating to loopback. One of the issue we are facing is different encryption method for password. We have used AES encryption method whereas loopback uses bcrypt. I have two questions

which encryption (AES or bcrypt way) is better
If we were to implement bcrypt then would it be consistent to login from web as well as from API. I know we have used salt (basic).

Please suggest.
Thanks,
Raj
Answer: AES doesn't make much sense for password storage: it's an encryption algorithm (not a hashing algorithm). For storing passwords, you should always be using bcrypt no matter what.
You also don't want to login to an API using your username/password (eg: bcrypt). You want to generate API keys (random uuids) specifically for an API user to auth with -- this reduces the risk of leaking user credentials (username/password) publicly, which could cause huge breaches.


Missing bundle property on entity of type taxonomy_term

Question: I am using the Feeds Import module as described in Drupal as an interface for users to Add/Edit/Search a database.
When we import, we get the following error:

Missing bundle property on entity of type taxonomy_term

Why does that error message appear?
Answer: This error is caused when there is no Vocabulary selected in the Term reference fields of the content type into which feed import is performed.
Go to the Manage fields of your content type into which you are importing. Check all the Term reference fields and reconfirm that in the Field Settings, correct Vocabulary is selected.
Answer: In my case, my entity (term) did not have the property vocabulary_machine_name.
It was ["vocabulary_machine_name"] => NULL when it should have the right vocabulary_machine_name, in this case 'forum'.
So a made sure the term has it:
                        $term->name = ...;
                        $term->vid = ...;
                        $term->vocabulary_machine_name = 'forum'; //here
                        $term->format = ...;


Linq não retorna dados. Existe dados na tabela e eu retorno pela query

Question: Procurei fazer uma LINQ bem semelhante a minha query. Essa é minha query.
select * from PDV
where tipo_PDV = 'R' and UF = 'DF' and Cidade = 'BRASILIA-DF'

Essa é minha LINQ
var resultado_rede_descricao = (from _pdv in db.PDV
                                            //.Where(r => r.Tipo_PDV == _tipo_rede)
                                            select new { _pdv.Descricao, _pdv.Tipo_PDV, _pdv.UF, _pdv.Cidade }).ToList().DistinctBy(u => u.UF).DistinctBy(c => c.Cidade).Distinct();

            if(_tipo_rede != "E")
            {
                resultado_rede_descricao = resultado_rede_descricao.Where(t => t.Tipo_PDV == _tipo_rede).Distinct().ToList().OrderBy(o => o.Descricao);
            }

            if (_uf != "E")
            {
                resultado_rede_descricao = resultado_rede_descricao.Where(u => u.UF == _uf).Distinct().ToList().OrderBy(o => o.Descricao);
            }

            if (_cidade != "" && _cidade != "Todos")
            {
                resultado_rede_descricao = resultado_rede_descricao.Where(u => u.Cidade == _cidade).Distinct().ToList().OrderBy(o => o.Descricao);
            }

Nesse exemplo: _tipo_rede = "R", _uf = "DF" e _cidade = "BRASILIA-DF"
Answer: Resolvi. Retirei o DistinctBy() do LINQ pricipal. Ainda não entendi a diferença entre o Distinct e o DistinctBy. Tenho procurado livros sobre LINQ e Lambda e não achei nada ainda, aui em Sampa(Nobel, Saraiva, Martins Fontes), nenhuma dessas livrarias eu encontrei algo do gênero.


The Evaluation Map is Bilinear

Question: I was asked to prove the following: The evaluation map $\epsilon : V \times V^* \rightarrow \mathcal{F}$ such that $\epsilon(v, f) = f(v)$ is bilinear. Prove.
However, it seems like it is impossible for this map to be bilinear. If f is fixed to the square root function, it follows that $\epsilon(f, av) = f(av) = \sqrt(av) \neq af(v) = a\sqrt(v)$, if $a \neq 1, 0$. How is this evaluation map a bilinear mapping then?
EDIT
I understand now, I'm not too sure how I made that mistake. Thanks!
Comment: You're assuming that the square root function is in $V^*$ -- however by definition $V^*$ is the space of all _linear_ functions $V\to F$, and $\sqrt{\phantom{a}}$ is not linear.
Comment: The domain of $\epsilon$ is $V\times V^*$.  Why do you believe the square root function belongs to $V$?  Maybe it does, but you haven't told us what you mean when you write $V$.
Comment: You need to show two things:
1. $\epsilon(f,cv+w) = c\epsilon(f,v)+\epsilon(f,w)$
2. $\epsilon(cf+g,v)= c\epsilon(f,v)+\epsilon(g,v)$
Comment: @ErickWong It did not specify which field V was over, but taking the field to be  the real numbers, is this not an issue? I feel like there must be something obvious I'm missing here.
Comment: @OpenBall Ah yes, I meant to say $V^*$.  The square root function could belong to $V^*$, I suppose, if $V$ is the $1$-dimensional vector space over $\mathbb F_2$ :)
Comment: @Duncan Read Henning's comment.  Why do you believe the square root function over the reals is an element of the dual space of $V$?
Answer: I don't understand. Presumably $V$ is a vector space and $V^*$ is its dual. In this case, any $f\in V^*$ is a linear map $f:V\to\mathcal F$, so by definition $f(av)=af(v)$ for all $a\in\cal F$. So the "square root function" is not even an example of a possible $f$.
The map is bilinear because if you take another $f'\in V^*$ and $a\in\cal F$, then
$$\epsilon(v,f+af')=(f+af')(v)=f(v)+af'(v)=\epsilon(v,f)+a\epsilon(v,f')$$
and if you have another $v'\in V$, then
$$\epsilon(v+av',f)=f(v+av')=f(v)+af(v')=\epsilon(v,f)+a\epsilon(v',f),$$
where we used the linearity of $f$.

The Evaluation Map is Bilinear


How is confidence interval computed in statsmodels for ARIMA(p,d,q) parameters?

Question: I am using statsmodel package for fitting ARIMA(p,d,q) model to a time series. My question is how exactly does this package estimate confidence intervals of the parameters of this model? statsmodels documentation says that
"The confidence interval is based on the standard normal distribution if self.use_t is False. If self.use_t is True, then uses a Student's t with self.df_resid_inference (or self.df_resid if df_resid_inference is not defined) degrees of freedom."
Then the question is how is the variance of different parameters estimated to apply the standard Normal or t-distribution method?
Edit: I used the Hessian matrix method to compute the covariance matrix. But the confidence interval obtained using my approach are much wider than those produced by statsmodels. Which means that statsmodels is not using the Hessian matrix approach. Also, I noticed that as I increase the length of my time-series, the confidence intervals obtained by these approaches become similar.
Answer: The documentation for the cov_type argument to fit method describes the options for computing the covariance matrix associated with the parameter estimates.
The default method is the outer product of gradients estimator (cov_type='opg').
If you want to use the numerically approximated Hessian, you can choose cov_type='approx', but note that by default this will use complex step differentiation rather than finite differences, so it may still be different from what you compute by hand.


Add keywords that consist of two words to CDT

Question: To have custom keywords for I do the following:

Define a language in the plugin.xml and extend GPPLanguage class.
extend CLanguageKeywords and override getKeywords to return super.getKeywords plus custom keywords:
public class MyLanguageKeywords extends CLanguageKeywords {
    public MyLanguageKeywords(ParserLanguage language, IScannerExtensionConfiguration config) {
        super(language, config);
    }

    @Override
    public String[] getKeywords() {
    String[] cppKeywords = super.getKeywords();
        String[] myKeywords = new String[] {
            "input",
            "output",
            "input port",
            "output port",
        };
        return (String[]) ArrayUtils.addAll(cppKeywords, myKeywords);
    }
}

implement getAdapter() to return an instance of MyLanguageKeywords

This works for "input" and "output", but not for "input port" or "output port". How can I have keyword highlighting for "port" but only in the combinations "input port" or "output port"?
Answer: I can think of two options:

Modify CDT's lexer to support keywords containing whitespace. I don't think this is something you can do using the public API, you'd have to modify core CDT classes like org.eclipse.cdt.internal.core.parser.scanner.Lexer. (Alternatively, you could consider upstreaming a patch to add such support to the lexer.)
Use semantic highlighting to highlight your whitespace-containing keywords. There's an org.eclipse.cdt.ui.semanticHighlighting extension point that allows plugins to provide custom semantic highlighting.

The difference in the user experience would be that lexical highlighting is applied immediately after every keystroke, while semantic highlighting is applied after a short delay after typing stops (since it's more expensive to compute). You can see this effect if you compare how the override and final keywords are currently highlighted in C++, compared to other keywords: override and final use semantic highlighting because they're context-sensitive keywords.
I should also mention that whether the second approach works, depends on how your new keywords fit into the grammar. They need to be parsed as IASTName in order for semantic highlighting to be applied to them.
Comment: I could just inherit from Lexer and override a method to get the desired behavior, if the class wasn't declared final. I think the CDT code has too many of such restrictions. Forking CDT is undesired in my company, so I will try the second approach.
Comment: @Sadik A patch to remove a `final` from a class where it stands in the way of a plugin, would be considered.
Comment: >>They need to be parsed as IASTName<<  I have a concept very similar to 'struct' (but with two keywords). My parser parses as IASTDeclaration. So this approach won't work then, right?
Comment: @Sadik How are you customizing the parser?
Comment: My source parser class is inherits from GNUCPPSourceParser and is instantiated in my language class's createParser() method. My language class inherits from GPPLanguage.
Comment: @Sadik You could work around it by making your node an `IASTImplicitNameOwner` and creating an `IASTImplicitName` covering the region you want to highlight. It would still require a small CDT source change, to allow contributed semantic highlightings to process implicit names (https://git.eclipse.org/c/cdt/org.eclipse.cdt.git/tree/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/editor/ContributedSemanticHighlighting.java?h=cdt_9_8#n207), which could be upstreamed.


Sistema de login único

Question: Como criar um sistema de login único em PHP? Que dê acesso à vários sites para o usuário, sem precisar fazer o login em cada site. Como por exemplo o Google, que com um único login, você usa o Google e o YouTube.
Comment: Essa pergunta é muito ampla.... existem varias formas de se fazer, utilizando frameworks(zend, cake, laravel, joomla, entre muitos outros), ou php puro, utilizando mais recursos front-end, como storage em js, ou mais back-end, deixando mais a conta do servidor, assim como cadastrado usuários, validando dados e etc....

A rede não funciona assim, monte o escopo do seu projeto, se surgir alguma duvida em ferramentas ou funções especificas na construção, ai sim se torna mais cabível....
Comment: @WilliamNovak Obrigado
Comment: Acho válido o que o colega citou acima. De todo modo, algo parecido com que o que você citou me lembrou o [Oauth](https://www.google.com.br/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=Oauth), dá uma pesquisada.
Comment: @MarceloBonifazio Eu desejaria criar esse sistema em PHP puro, para estudo!
Comment: Melhor compreendendo a sua pergunta, depois que editou, creio que o Oauth não é uma solução nem mesmo uma base de estudo no seu caso, ainda mais devido a complexidade dele. No seu caso, seria um trabalho simples trabalhar com _session_ desde que elas fossem salvas no mesmo lugar. Dá uma olhada aqui [session.configuration](http://php.net/manual/pt_BR/session.configuration.php).
Comment: @WilliamNovak Obrigado
Answer: Qualquer sessão criada, por padrão é criado um cookie no navegador chamado PHPSESSID que é salvo o nome da sessão (em hash) criado pelo seu código na pasta temporária do servidor.
Você pode acessar esse cookie usando session_get_cookie_params() antes do session_start() que irá mostrar alguns parâmetros:
Array
(
[lifetime] => 0
[path] => /
[domain] =>
[secure] =>
[httponly] =>
)

o [lifetime] => 0 indica que quando o navegador for fechado o cookie irá desaparecer e assim a sessão será fechada.
Pensando desta maneira, na qual sempre que uma sessão é aberta um cookie é criado. Não vejo o porque de não usar cookies para este caso:

Criar um cookie com um nome definido para que os outros sites possam acessar.
Fazer o valor do cookie ser uma chave/token (hash) que você cria sempre que o usuário fizer o login em um dos sites participantes.
Essa hash é salva no banco de dados que todos os sites participantes tem acesso.
Fazer uma verificação no db (usuário / chave / cookie ) cada vez que o ele acessa algo em qualquer um dos sites para verificar a identidade deste usuário ou loga-lo automaticamente. Você pode usar ip da máquina também.

Assim ele fará apenas um login em qualquer um dos sites.
Claro que existe toda uma segurança envolvida que você terá que realizar.
Espero ter ajudado.
Abraço!

Sistema de login único


Intuitive understanding of covariance

Question: Note :  I have just started learning statistics and the question might be very basic. I know what is variance, standard deviation.
I have following 2 questions regarding covariance and correlation

What is the intuitive meaning of the product in the formula of Cov(X,Y). Why not add the two terms instead of multiplying ?

In addition to direction, why can't I use the magnitude of Cov(X,Y) to determine the strength of relation ? I know this is because of random variables being in different scales but I still lack the intuition to why this is problematic ?

Note : I understand what correlation and covariance means but I don't understand the intuition behind the formula, meaning, why this particular formula gives the meaning that these terms have.
Comment: https://stats.stackexchange.com/questions/tagged/covariance?tab=Votes
Answer:
Suppose we define covariance by adding the two terms instead of multiplying them. Assume X and Y follow each other very closely (also, for simplicity, assume we normalize the values by centring them so that both have a mean of zero). Following each other means when X is positive, Y is also very likely to be positive. The same holds when X is negative. In this case, you might end up with a correlation of X and Y being very close to zero, while, as we assumed, these two variables move very closely with each other. The reason is that when X and Y are both positive, their summation is also positive, and when they are negative, their summation is also negative, so when we take the expectation of the summations, these positive and negative values might cancel out each other, resulting in a correlation value of very close to zero! That's why we use the product operator rather than summation to define covariance.

The magnitude of the covariance is a function of the correspondence between two variables as well as the scale of two variables. So if you see a large covariance, you cannot say whether this is a sign of a high degree of correspondence between two variables or just the artefact of working with two variables with a large scale.

Intuitive understanding of covariance


How do you compute the annual standard error of a regression model when the model itself is based on monthly observations?

Question: Let's say you regress monthly stock returns, and the regression model has a standard error around such monthly stock returns of 2%.  Next, you forecast the next year annual stock return based on the regressed monthly returns.  What is the standard error around this annual stock return?
Some may think this is not a very good example.  Don't get hung up on what is the proper way to model stock returns.  This has nothing to do with the question.  The question is simply figuring out the calculation to convert a monthly standard error into an annual one.
Answer: The general rule is $\sqrt N$. So from daily data, annual volatility would be estimated as sd(v)* sqrt(255).
Hence for your example, multiply the estimated error by the square root of twelve.
Edit: In response to the follow-up comment, here is a complete worked example with real data. The annual volatility comes out to be around 16% which seems about right.  You could modify this for rolling volatilities, or weekly data, or ....
R> library(tseries)
Loading required package: quadprog
Loading required package: zoo

    'tseries' version: 0.10-22

    'tseries' is a package for time series analysis and computational finance.

    See 'library(help="tseries")' for details.

R> SP500 <- get.hist.quote("^GSPC", "2000-01-01", "2011-01-29", quote="Close", compression="m")
trying URL 'http://chart.yahoo.com/table.csv?s=^GSPC&a=0&b=01&c=2000&d=0&e=29&f=2011&g=m&q=q&y=0&z=^GSPC&x=.csv'
Content type 'text/csv' length unknown
opened URL
.......
downloaded 8162 bytes

time series starts 2000-01-03
time series ends   2011-01-03
R> head(SP500)
             Close
2000-01-03 1394.46
2000-02-01 1366.42
2000-03-01 1498.58
2000-04-03 1452.43
2000-05-01 1420.60
2000-06-01 1454.60
R> sd(diff(log(SP500)))
    Close
0.0478781
R> sd(diff(log(SP500)))*sqrt(12)
   Close
0.165855
R>

Comment: Correct. See the edit I just made to my initial answer.
Comment: This is the right approach, but for stock returns (and for many other time series) serial correlation has an important influence.  Ignoring it (by using $\sqrt{N}$) is going to be too optimistic.
Comment: So Dirk, in this example the annual standard error of stock returns would simply be: 2% times SQRT(12) = 6.93%.  Can you confirm that is correct.  It seems so straightforward, I am afraid I missed something.
Comment: Dirk, thanks much for the confirmation and the real data application.  To whuber, I know Benoit Mandelbrot argues there is a long term serial correlation of returns.  I remember looking at real data, and I saw no evidence of serial correlation using lags from - 1mth to - 12 mth.  Thus, I am not convinced that Dirk's approach is incorrect.  In any case, my main concern was understanding how to convert a monthly standard error into an annual one.  And, Dirk did a good job at giving me the straightforward answer to that.
Answer: Although this question has already been answered a useful way to remember for more general situations is the law of iterated expectations.  Note that the independence for prediction does not hold even if the "true process" is independent.  This is because the estimates are not independent, unless you have $Z^{T}Z$ and $Z_{new}Z_{new}^{T}$ both to be diagonal ("new" for the predictions)
So if you let $\hat{Y}_{ti}$ denote the estimated monthly values in year $t$ for month $i$, and $\hat{X}_{t}$ denote the estimated annual value, you have:
$$\hat{X}_{t}=\sum_{i=1}^{12}\hat{Y}_{ti}$$
$$Var(\hat{X}_{t})=E[Var(\hat{X}_{t}|\hat{Y}_{t,1},\dots,\hat{Y}_{t,12})]+Var[E(\hat{X}_{t}|\hat{Y}_{t,1},\dots,\hat{Y}_{t,12})]$$
(note sure if it should be an average or total, if average, then divide my final result for the standard error by $12$ and divide variance by $144$) Plugging one into the other we get:
$$Var(\hat{X}_{t})=E[Var(\sum_{i=1}^{12}\hat{Y}_{ti}|\hat{Y}_{t,1},\dots,\hat{Y}_{t,12})]+Var[E(\sum_{i=1}^{12}\hat{Y}_{ti}|\hat{Y}_{t,1},\dots,\hat{Y}_{t,12})]$$
$$=Var[\sum_{i=1}^{12}\hat{Y}_{ti}]=\sum_{i=1}^{12}\sum_{j=1}^{12}Cov(\hat{Y}_{tj},\hat{Y}_{ti})$$
Now when you condition on something, it is a constant, so that's why the "inner" variance term disappears.
Now you have a regression model for $Y_{ti}$ so we know that
$$\begin{array}{l l}
\hat{Y}_{ti}=Z_{ti,new}^{T}\hat{\beta} & Cov(\hat{Y}_{ti},\hat{Y}_{sj})=s^{2}Z_{ti,new}^{T}(Z^{T}Z)^{-1}Z_{sj,new} \\
\hat{\beta}=(Z^{T}Z)^{-1}Z^{T}Y & s^{2}=\frac{1}{n-dim(\hat{\beta})}(Y-Z\hat{\beta})^{T}(Y-Z\hat{\beta})
\end{array}$$
Where $Z$ and $Y$ are the matrix and vector that you used to actually fit the regression (I am assuming OLS regression here), $dim(\hat{\beta})$ is the number of betas that you have fitted (including the intercept).  $Z_{ti,new}$ is a new set of regression co-efficients to be used in the prediction.
Note that for prediction, your estimates of $Y$ are not independent, even if the "true values" are.  So the square root of $N$ rule doesn't apply, unless your $Z$ variables are orthogonal so that $(Z^{T}Z)^{-1}=I$ and $Z_{ti}^{T}Z_{sj}=0$ when $s\neq t$ or $i\neq j$.
Plugging this into the variance formula for $\hat{X}_{t}$ we get:
$$Var(\hat{X}_{t})=\sum_{i=1}^{12}\sum_{j=1}^{12}s^{2}Z_{ti,new}^{T}(Z^{T}Z)^{-1}Z_{tj,new}=s^{2}J^{T}Z_{t,new}(Z^{T}Z)^{-1}Z_{t,new}^{T}J$$
Where $J$ is a column of 12 ones, and $Z_{t,new}$ is the twelve $Z_{ti}^{T}$ rows for prediction stacked on top of each other, of dimension $12\times dim(\hat{\beta})$.
But note that we also have the "true" process $X_{t}$, assumed to be governed by the regression model, so we apply the law of iterated expectations again, but conditioning on $\hat{X}_{t}$ this time:
$$Var(X_{t})=E[Var(X_{t}|\hat{X}_{t})]+Var[E(X_{t}|\hat{X}_{t})]=E[Var(\sum_{i=1}^{12}Y_{t}|\hat{Y}_{ti})]+Var[\hat{X}_{t}]$$
$$=E[\sum_{i=1}^{12}Var(Y_{ti})]+Var[\hat{X}_{t}]=12s^{2}+s^{2}J^{T}Z_{t,new}(Z^{T}Z)^{-1}Z_{t,new}^{T}J$$
I probably should put approx because this is a "plug-in" of $s^{2}$ for the "true variance" $\sigma^{2}$ - however I don't know of many people who don't just do this.  It is also justified on Bayesian grounds as the proper way to account for uncertainty in estimating $\sigma^{2}$ for the normal model, plus it is an unbiased estimator on frequentist grounds.  So the annual standard error should really be
$$s\sqrt{12+J^{T}Z_{t,new}(Z^{T}Z)^{-1}Z_{t,new}^{T}J}$$
So what the $\sqrt{12}$ rule is essentially doing here is ignoring the uncertainty in estimating the betas.  If you already estimate the betas pretty well, then this will make little difference to the $\sqrt{12}$ rule - probably something like $\sqrt{13}$.  If the betas are not estimated well, or you are close to multi-collinearity, then the extra term may be important.hb**
text
**


Confusion over a proof that gradient is perpendicular to the level set

Question: To prove that the vector $\nabla{f}(x_0)$ is orthogonal to the tangent vector to "an arbitrary smooth curve" passing through $x_0$ on the level set determined by $f(x)=f(x_0)$ the following proof is outlined in Chong and Zak :
It takes a special curve $\gamma$ lying in the level set and passing through $x_0$ and parameterized by a continuously differentiable function $g:\Bbb R \to \Bbb R^n$ such that $g(t_0) =x_0$ and $Dg(t_0)=v \neq 0$, so that $v$ is a tangent vector to $\gamma$ at $x_0$. Then it proves that $\nabla{f}(x_0) ^T v =0$. This proof is not correct. It does not consider any arbitrary smooth curve. The condition that $v$ is tangent to $\gamma$ at $x_0$ may not be true always. Am I correct ?
Answer: The curve must satisfy $\gamma(0) = x_0$, $f(\gamma(t)) = f(x_0)$ for $t \in [0,\delta)$ and $\gamma'(0) = v$. Then $\langle \nabla f(x_0), v \rangle = 0$ from the chain rule.
Unless $\nabla f(x_0) = 0$, it cannot be true for arbitrary $v$.
If $v \bot \nabla f(x_0)$, and $\nabla f(x_0) \neq 0$, then we can use the implicit function theorem to construct a suitable curve.
If $v = 0$, it is trivial, just let $\gamma(t) = x_0$.
If $v \neq 0$, consider the function $\phi(\alpha,\beta) = f(\alpha v + \beta \nabla f(x_0)+x_0) - f(x_0)$. Note that $\frac{\partial \phi(0,0)}{\partial \beta} = \| \nabla f(x_0)\|^2 \neq 0$, and use the implicit function theorem with $\phi(\alpha,\beta) = 0$ to find a differentiable $\xi$ such that $\phi(\alpha, \xi(\alpha)) = 0$, $\xi(0) = 0$, and $\frac{\partial \xi(0)}{\partial \alpha}= - \frac{\frac{\partial \phi(0,0)}{\partial \alpha}}{\frac{\partial \phi(0,0)}{\partial \beta}} = 0$.
Then let $\gamma(t) = t v + \xi(t) \nabla f(x_0)+ x_0$. Note that $\gamma(0) = x_0$, $f(\gamma(t)) = f(x_0)$, and $\gamma'(0) = v$.
Comment: The inputs $f$ takes is quite confusing, isnt $v$ a vector??
Comment: I meant while defining $\phi(\alpha,\beta)$.
Comment: Yes, $v$ is a vector, $\alpha, \beta$ are scalars.
Comment: But $x_0$ is a point, right??I am still confused.Sorry about this. So $f$ takes both vector and points??
Comment: Draw a picture. I am just using the notation you used in the question. $f$ is defined on $\mathbb{R}^n$. we have $v,x_0, \nabla f(x_0) \in \mathbb{R}^n$, $\alpha,\beta \in \mathbb{R}$, so $\alpha v + \beta \nabla f(x_0)+x_0 \in \mathbb{R}^n$.
Comment: Oh ok. Its just the notation misled me into looking at $f$ as a function acting on points and vectors. Of course in this case they can be identified with each other, sort of like the affine space and vector space structure on $\mathbb{R}^n$ , right?
Comment: I'm not sure how you distinguish points from vectors in $\mathbb{R}^n$?
Comment: Just that the points are turned into vectors on identifying an origin and bringing in the notion of position vectors w.r.t that origin.I apologise if I have bothered you for a seemingly non-existent issue.Its just that since the answer began with $\gamma(0) = x_o$ and $\gamma '(0) =v$ , I fumbled.Note that the latter is a vector based at $x_0$.


AngularJS: Requisição $http para consumir API externa da do dominio dando erro

Question: Eu tenho uma aplicação AngularJS que faz login. Eu estou tentando após o login, requisitar de uma API que estou rodando na minha máquina rodando em C# para ao menos conseguir se comunicar com ela. Porém deu diversos erros na minha tentativa, desde
<code>  $http.get('http://localhost:5001/Login').then(function(data){
     console.log('entrou algo');
  }, function(data){ console.log(data); });
</code>
Erro 1: Pedido de origem cruzada bloqueado: A política de mesma origem não permite a leitura do recurso remoto em http://localhost:5001/Login. (Motivo: o pedido CORS não foi bem sucedido)
<code>    $http({method:'GET',
           url: 'https://localhost:5001',
           headers: 'Access-Control-Allow-Origin: *'
         }).then(function(data){
        return data;
    });
</code>
Erro2: Pedido de origem cruzada bloqueado: A política da mesma origem não permite a leitura do recurso remoto em https://localhost:5001/. (Motivo: cabeçalho CORS 'Access-Control-Allow-Origin' em falta).
Alguem poderia me ajudar?
Comment: tem que configurar o serviço para aceitar e liberar o `cors`!
Comment: o que haver index.php com C#?
Comment: Eu tentei colocar no index.php, no .htacess e ainda pela requisição e ainda continua com o erro. Não sei se fiz certo também...
Answer: Seu problema não parece ser originado no cliente onde o trecho em AngularJS está sendo executado.
Assumindo que sua API está escrita em .NET Core 3.1, a solução seria adicionar policies que permitem o acesso local.
Exemplo de configuração:
<code>public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy(name: "Acesso Local",
            builder =>
            {
                builder.WithOrigins("http://localhost") // <- URL do conteúdo AngularJS
                        .WithMethods("PUT", "DELETE", "GET");
            });
    });
}

public void Configure(IApplicationBuilder app)
{
    app.UseCors();
}
</code>


ExtJS 4 code assist in Aptana 3

Question: I started using ExtJS 4 framework for generating chart report in a web app development project.
I am looking for up-to-date code assist for ExtJS 4 to release me from too much typing. I tried for long to find one, but it looks like all of them are out-of-date.
If anyone currently using ExtJS 4 code assist in Aptana (or some other IDE). Please give me a hand. Thanks!
Answer: Great! Finally find this thread which answers my question.
Download extjs4.1.beta-v0.1.sdocml can add code hinting into your ExtJS 4 Aptana project.
There is a lot instructions for adding Spket plugin to Eclipse/Aptana for ExtJS support. But it just never works for me...Not sure if anyone used it and get it worked out.
UPDATE: I am using WebStorm for ExtJS 4 development now, it has very good ExtJS support. Actually all the js files included in the project can be identified in WebStorm and thus code hinting is listed.
Comment: After years of searching, I finally found this in 2013!!

ExtJS 4 code assist in Aptana 3


How to alter add content form to include a new setting panel?

Question: Here is the code for creating a new Tab in the settings panel on "Add article" node.
But it is not displaying.. what could be the errors ?
function mltag_form_alter(&$form, &$form_state, $form_id) {
if ($form_id == 'article_node_form') {
drupal_set_message('Editing a node');
$form['mltag'] = array(
    '#type' => 'fieldset',
    '#title' => t('MLTag settings'),
    '#access' => TRUE,
    '#collapsible' => TRUE,
    '#group' => 'additional_settings',
    //'#attached' => array(
    //        'js' => array(drupal_get_path('module', 'autordf').'/autordf.js'),
    //),
    '#tree' => TRUE,
    '#weight' => -2,
    '#attributes' => array('class' => array('mltag-settings')),
);
$form['mltag']['enabled'] = array(
    '#type' => 'checkbox',
    '#title' => t('Generate tags use Mltag'),
    //'#default_value' => (empty($form['nid']['#value'])),
);
}
}

Answer: Your code works perfectly for me; dropped straight into a form alter hook I get the following on the article add page:

There are 3 reasons I can think of that might explain why you're not seeing the new tab:

You haven't cleared Drupal's caches since implementing the new hook (probably the most common cause for problems like this).
Your module isn't actually called "mltag", in which case your form alter hook will never actually be run.
Your code is in a file other than the main .module file. Hooks declared in files that are not explicitly included from the .module file will not necessarily be found when Drupal is updating the module_implements cache.
Comment: i've cleared the cache a number of times and the module name is also "mltag" there are other hooks working by the same module name.. but still not working for me..
Comment: Something else must be interfering with it then (as I say it works perfectly for me without any alteration); your best bet would be to try disabling modules methodically until you find the culprit
Comment: i did something like this too-
function mltag_form_alter(&$form, &$form_state, $form_id) {

  drupal_set_message($form_id);
}
but did not get any message either !
Comment: Is the hook in a file called mltag.module?
Comment: yeah clive! evrything else is working fine.. dunno y this simple function is stuck and not working !


Choosing Excerpts for Concerto Audition

Question: I have been practicing Prokofiev Piano Concerto No. 3 and I have an audition coming up. It requires me to choose a 15-minute excerpt, covering all three movements. As this is my first time auditioning for a concerto soloist, I have no idea what to look for when choosing an excerpt. For instance:

Should I choose parts where I'm most comfortable with? But in that case, would it not showcase enough technicality if I just choose the easier parts?

Should I avoid jumping around in movements? i.e. is 3 continuous excerpts, one from each movement the best?

Should I start with the actual opening of the concerto, and end with the actual ending of the concerto?

In general, does anyone have any other tips on choosing excerpts, or just auditioning for a concerto position? Thanks.
Comment: I'm puzzled about how a 15 minute excerpt can cover all three movements.  Do you mean three different excerpts, one from each movement with a total of 15 minutes?  Also will you have orchestral accompaniment?
Comment: @JimM Yes, that is what I mean (sorry for the confusion). There will be a piano accompaniment for the orchestral part.
Answer: There really are no instructions, besides "15 minutes, three movements"? It's unusual that they let you pick your own passages. If I were judging a competition, I would ask for a selection of passages demonstrating contrasting skills. Technically challenging passages—whether fast or challenging in some other way—and lyrical expressive passages. Consider: if the judges' job is "find out who plays this concerto best," what are the parts they would skip to save time? And what are the must-hear parts?
Comment: Unfortunately, that is the only instruction they give. But thanks for the advice! I was wondering: what if the must-hear parts are scattered throughout the movement? Would it be normal in an audition if I suddenly cut off after a section and skip to another section in the same movement?
Comment: @blastzit - don't join all the passages together - instead announce what you're going to perform, so the panel know what to expect. It also tells the panel how comfortable you are talking to the audience about the music. (The performance starts the moment you walk into the room!) And think about how your chosen passages fit together - perhaps your final selection should be the closing part of the third movement.

Choosing Excerpts for Concerto Audition


Why do we create instances of classes?

Question: I'm learning C# and I want to know why we create instances of classes.
Customer myCustomer = new Customer();
myCustomer.name = "harry";

When I search online I always get "How to make instances" but that's not my question.
I know how to make them.
Why is my question.
Is it because we use them like datatypes? Like complex datatypes.
Comment: Exactly, it's because we use them as data types.
Answer: Lets say you are building some contacts application. Then, there will be a class called Contact. You will create an instance of Contact class for each contact you need to save. You cant save all contacts in single instance. Each contact will have different attributes. Like First Name, Last Name , email, phone number etc.
In the above code example, you are trying to create an instance of customer. If you have lot of customers, then you definitely create an instance for each customer to keep track of all customers.
Answer: Often we use a class to represent a particular entity in our system. In your example you have a class to represent a Customer. However (hopefully) you have more than one customer! To represent this you have two instances of a customer class, one for Harry and one for Jerry.
Jerry and Harry are two different customers but your system contains the same information about each (their name, customer order, recent purchases etc).
When the time comes to expand your system to include different shops you would create a new Class called Shop with instances representing your London, New York and Sydney stores.
Answer: An instance of a class gets a chunk of memory allocated to it to store it's internal variables. This means that the variables of one instance are isolated from the variables of another instance.
Answer: If it's your first object oriented programming language you're doing right by asking this, it's important to understand how this works.
A class is defined by its methods and atributes but you need to instantiate it to start using those methods and giving values to attributes, for example :
myCustomer.name = " harry"

In this case "name" is an attribute of Customer class and you set the name of harry to this one instantiated Customer only, not to the class, the class won't have any values, only defined attributes and methods.
Same thing goes with methods, for example:
myCustomer.setName("harry");

(in case the attribute "name" would be private)
you instantiate and call methods from the main class, other classes are made to define methods and attributes and then use them instantiating.
See also: CodeProject introduction to OOP, Wikipedia article Class.
Comment: The class can have values though, and methods as well, without being instanced.
Answer: Well i think you basically answered your own question no?
Its because a class is just a type. If i say, Customer came into the store today, you get an idea of a type of a person, a customer. But if i say that "Harry" is a customer at my store, you understand that i am only talking about one Customer in particular. What i say about "Harry" is singular to him, and has little to do with all of the other Customers as a whole.
Customer myCustomer = new Customer();
myCustomer.name = "harry";

I mean, its almost completely human legible. Think about it this way:
// Type   // instance
Color     myColor = new Color(255,0,0); // red

Why do we create instances of classes?


Composing covers with epis

Question: I am beginner of sheaf-theory and beg your pardon for this maybe silly question.
Let $\mathcal{C}$ be a Grothendieck site and $T$ the category of sheaves on $\mathcal{C}$ and let $f:X\rightarrow Y$ be an epic morphism in $T$ into a representable sheaf $Y$.
I have a general lack of understanding how such epic morphisms look like and this leads to the the questions:

Suppose $\{Y_\alpha\to Y\}$ is a cover of $Y$. Is $Y_\alpha\times_Y X$ representable? I see no formal reason why this is true but somehow my miserable intuition still thinks it might be.
(If the answer to the first point is ''no'', please assume a representable $X$) Suppose $\{X_\alpha\to X\}$ is a cover of $X$. Is the composition $\{X_\alpha\to X\xrightarrow{f} Y\}$ a cover of $Y$?
Comment: The fibre product of two representable sheaves over a representable sheaf is itself representable... if the site itself has those fibre products.
Answer: In more detail.

By definition, limits commute with hom:
$$\mathcal{C}(-, \varprojlim x_\bullet) \cong \varprojlim \mathcal{C} (-, x_\bullet)$$
In particular, fibre products commute with hom:
$$\mathcal{C}(-, x \times_z y) \cong \mathcal{C}(-, x) \times_{\mathcal{C}(-, z)} \mathcal{C}(-, y)$$
So far this has nothing to do with Grothendieck topologies. If you have a subcanonical Grothendieck topology then all this still applies verbatim; otherwise you have to replace $\mathcal{C}(-, x)$ with its sheafification, and the claim only holds for finite limits because sheafification is only left exact.
Now, if $Y$ and $Z$ are representable but $X$ is not, then it does not follow that $X \times_Z Y$ is representable. For example, $\mathcal{C}$ could be a site with finitely many objects and finitely many morphisms, while $X$ (and hence $X \times_Z Y$ could be infinite.)
I presume by 'cover' you mean jointly epimorphic. The answer is yes. In a Grothendieck topos, all small coproducts exist, so you can replace a jointly epimorphic family $\{ X_\alpha \to X \}$ with a single epimorphism $\coprod_\alpha X_\alpha \to X$. It is a fact about general categories that the latter morphism, when it exists, is epimorphic if and only if the original family is jointly epimorphic. The composition of two epimorphisms is obviously an epimorphism, hence, $\{ X_\alpha \to X \to Y \}$ is jointly epimorphic if $X \to Y$ is an epimorphism.
The question is slightly more subtle if we work in the underlying site. There, one cannot take coproducts (even if they exist) and one must look at the Grothendieck topology $J$ itself. One of the axioms of Grothendieck topologies is that covers compose: if $\mathfrak{U}$ is a sieve on $Y$ such that the pullback sive $f^* \mathfrak{U}$ is a $J$-covering sieve on $U$ for each $f : U \to Y$ in $\mathfrak{U}$, then $\mathfrak{U}$ is also a $J$-covering sieve. In terms of a Grothendieck pretopology $K$, if $\{ U_\beta \to Y \}$ is a $K$-covering family and $\{ X_{\alpha, \beta} \to U_\beta \}$ is a $K$-covering family for each $U_\beta$, then the composite family $\{ X_{\alpha, \beta} \to U_\beta \to Y \}$ is also a $K$-covering family.
Comment: I need help with your second answer. In my situation $f:X\rightarrow Y$ is a morphism of the site $\mathcal{C}$ such that the *Yoneda embedded* $\tilde f:\tilde X\rightarrow\tilde Y$ is en epi of sheaves. If now $\{X_\alpha\rightarrow X\}$ is a sieve on $X$, is the composition $\{X_\alpha\rightarrow X\rightarrow Y\}$ a sieve on $Y$? My problem is then the relation between epis (or jointly epimorphic families) in the site $\mathcal{C}$ and epis (or jointly epimorphic families) in the category of sheaves on $\mathcal{C}$. How are they related?
Comment: A family of morphisms generates a $J$-covering sieve in the site if and only if it becomes jointly epimorphic in the sheaf topos. ($J$ really has to be a Grothendieck topology for this to be true.)
Comment: Wow, this would be perfect. I think, I can show that if $\{X_\alpha\rightarrow X\}$ is a cover, then it becomes jointly epimorphic in the sheaf topos. Do you know how I can show the converse?
Comment: The joint _presheaf_ image of $\{ \tilde{X}_\alpha \to \tilde{X} \}$ is a _presheaf_ subobject of $\tilde{X}$, and there is a bijective correspondence between _presheaf_ subobjects of $\tilde{X}$ and (not necessarily covering) sieves on $X$. If the joint _sheaf_ image is the whole of $\tilde{X}$, then the joint _presheaf_ image is dense, and a dense _presheaf_ subobject of $\tilde{X}$ is exactly a $J$-covering sieve.
Comment: I think I understand it better now, thanks. Doesn't this mean, that when I take a Grothendieck pretopology $K$ which is maximal in the sense that it can't be refined anymore without changing the associated Grothendieck topos, then a family $\{\tilde X_\alpha\rightarrow \tilde X\}$ of representables is jointly epimorphic iff $\{X_\alpha\rightarrow X\}$ is a cover of $K$?
Comment: Grothendieck pretopologies are still relatively well behaved. If $K$ is a Grothendieck pretopology and $J$ is the Grothendieck topology it generates, then a family is $K$-covering if and only if the sieve it generates is $J$-covering.
Comment: Suppose $F=\{X_\alpha\to X\}$ is a family of morphisms of the site with Grothendieck pretopology $K$ and generated Grothendieck topology $J$. You are saying that "$F$ becomes jointly epimorphic in the sheaf topos" $\Leftrightarrow$ "$F$ generates a $J$-covering sieve" $\Leftrightarrow$ "$F$ is a $K$-covering", right? But there are different Grothendieck pretopologies $K$, $K'$ that give rise to the same Grothendieck topology $J$ and then the sheaf topos is the same and certainly has the same epimorphisms. Doesn't one have to require some saturation condition on $K$?
Comment: @Shinze: Sorry, I misspoke. A sieve is $J$-covering if and only if it contains _some_ $K$-covering family. So you have to look at the sieve a family generates.
Comment: Sorry, but I am confused. "$F$ becomes jointly epimorphic in the sheaf topos" $\Leftrightarrow$ "$F$ generates a $J$-covering sieve" is still correct, right? I would like to see that this implies that $F$ is a $K$-covering in a *maximal* Grothendieck pretopology $K$ giving rise to $J$. This $K$ is defined as $F\in K(X)\Leftrightarrow \{f\circ g\mid f\in F\}\in J(X)$. It should be implied that for such a maximal Grothendieck pretopology $K$ and a family $F$: "$F$ becomes jointly epimorphic in the sheaf topos" $\Leftrightarrow$ "$F$ is a $K$-covering", right?
Comment: If this is true, it would answer the second point of my initial question together with your answer. By *cover* in the initial question, I meant $K$-covering where $K$ is a *maximal* Grothendieck pretopology in the above sense.
Comment: The maximal Grothendieck pretopology $\overline{K}$ generating a Grothendieck topology $J$ can be described explicitly as follows: a family is $\overline{K}$-covering if and only if it generates a $J$-covering sieve. So the short answer is yes.

Composing covers with epis


Personalizar o botão do Fullcalendar

Question: Estou querendo personalizar o botão do fullcalendar, porém não estou conseguindo. Estou usando o Bootstrap. O código CSS do fullcalendar, coloquei depois do CSS do Bootstrap e antes da tag . Vejam o código abaixo:
CSS
.fc-right button{
      text-transform: uppercase;
      border-radius: 2px;
      font-size: 13px;
      font-weight: 600;
      transition: box-shadow linear 0.4s;
      background-color: #2196F3;
      border-color: #2196F3;
      margin-top: 10px;
}

HTML

            Calendário de Eventos

     <button class="btn btn-default">Ver todos os eventos</button>

JQuery
$(document).ready(function() {
     $('#calendario').fullCalendar({
          height: 250,
          contentHeight: 273,
          editable: false,
          eventLimit: false,
          events: 'eventos.php',
          eventColor: '#dd6777',

          eventClick:  function(event, jsEvent, view) {
          $('#modalTitle').html(" " + event.title);
          $('#modalBody').html(event.description);
          $('#eventUrl').attr('href',event.url);
          $('#fullCalModal').modal();
      }
      });
});

Ele fica dessa forma:

E quando passo o mouse:

Como faço para que ele pegue a formatação que coloquei acima?
Comment: O que você está usando? Poste seu HTML.
Comment: Uma boa seria colocar o seu código no JSfiddle, não da pra saber se voce está usando, se é um hover ou se é um proprio atributo dessa fullcalendar. Ou então colocar aqui mesmo, pra executar.
Comment: Dê uma olhada [aqui](https://fullcalendar.io/docs/display/customButtons/).
Comment: Olá Jorge. Tem razão. Coloquei os trechos que se referem ao calendário, já que o HTML está muito grande. Estou usando o Bootstrap.
Comment: Olá Marcelo. Vou tentar isolar o código e colocar no JSfiddle.
Comment: Vc quer que ele mude a aparência ao passar o mouse em cima?
Comment: Olá Leandro, quero implementar o CSS que coloquei no post, mas não estou conseguindo. E se possível, alterar também ao passar o mouse.
Comment: Seria legal se vc coloca-se aqui o Hml inteiro, pois não estou vendo a classe *fc-right button* que vc está aplicando o Css.
Answer: Consegui resolver. Abri o CSS do próprio Fullcalendar e alterei essas linhas:
.fc button {
    text-transform: uppercase;
      border-radius: 2px;
      font-size: 13px;
      font-weight: 600;
      transition: box-shadow linear 0.4s;
      background-color: #2196F3;
      border-color: #2196F3;
      margin-top: 10px;
    cursor: pointer;
}

.fc .fc-button-group > * { /* extra precedence b/c buttons have margin set to zero */
    float: left;
    /*margin: 0 0 0 -1px;*/
}

.fc-state-default {
/*
    background-color: #f5f5f5;
    background-image: -moz-linear-gradient(top, #ffffff, #e6e6e6);
    background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ffffff), to(#e6e6e6));
    background-image: -webkit-linear-gradient(top, #ffffff, #e6e6e6);
    background-image: -o-linear-gradient(top, #ffffff, #e6e6e6);
    background-image: linear-gradient(to bottom, #ffffff, #e6e6e6);
    background-repeat: repeat-x;
    border-color: #e6e6e6 #e6e6e6 #bfbfbf;
    border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);
    color: #333;
    text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75);
    box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05);
*/
}

Comment: Obrigado a todos.
Comment: Não é bom você editar diretamente o código de uma biblioteca, seria melhor você sobrescrever essas classes em um outro css após o carregamento dela.
Comment: Olá Leandro. Sim, concordo com você, mas infelizmente por algum motivo, ao tentar sobrescrever, não estava surtindo efeito no calendário. Acredito que deve ter sido algum conflito com o template que estou usando. Como vou usar o calendário em apenas uma página, tive que fazer dessa forma, mesmo não sendo boas práticas.
Comment: O problema é que se algum momento, você atualizar essa biblioteca perderá suas customizações.

Personalizar o botão do Fullcalendar


update attribute that is html

Question: I have a anchor  with an attribute rel. in the rel value there is html, such as <a rel="html=
This is a test
. I want to update html inside of rel value, I can update the actual change on the page but if i go to the next slide and come back, its back to what it was before because the rel value is not updated. I am not sure how to go about doing this. Any suggestions, I am using Clearbox by the way.
Example(I know the html is incorrect on here, but it is correct on my page. I just need to know how to update it through jquery or any other way)
<a rel="html=
 This is a test

a piece of the html element (not the a) Needs to be changed to
<a rel="html=
 No more testing

Comment: `rel` is not a place to put arbitrary data. In fact, you shouldn't be storing HTML markup within HTML attributes.
Comment: That's not even valid HTML. Your first `a` tag never gets closed. Should at least be ` This is a test">
`.
Comment: If you want to put HTML in your rel, which you shouldn't do, at least escape your quotes, and close the rel attribute like so ` This is a test">link`
Comment: I did, i just wrote that for an example. Just image that the quotes are not there like that, just know that the html is all correct, but how do I update it
Answer: You can (But SHOULDN'T) do that with
this.rel = 'html=
But you shouldnt do that
';

JSFiddle here
Answer: I think you need to avoid the use of double quotes inside another double quotes, if you are using double quotes to wrap a string use single quotes inside that string and vice versa.
See this --> http://jsfiddle.net/Galled/rXKCL/14/

update attribute that is html


virtualenv/virtualenvwrapper confusion - how to properly use

Question: Sorry if this is dumb but every piece of documentation i read doesn't ever seem to answer this question in a direct way. How do i properly use virtualenv so that I have a virtualenv i can call with workon?
When i do tutorials like "Effective Django" they use the virtualenv command on an empty folder, then activate it. That works, until tomorrow when I want to work on the app again at which point the virtualenv is gone. What do i do at this point, I've used mkvirtualenv before and that creates a "permanent" virtualenv i can call with "workon" but I don't understand how i would use mkvirtualenv on an existing project or if this is a good idea or not, as it stands i have a project I virtualenv yesterday that has a bin folder in it and I am not sure if I need to source it again or what. Ideally i want to just workon project and get to work.
Comment: To reactivate an existing virtualenvironment, you should do: `source ENV/bin/activate`, `ENV` being whatever directory your environment resides in.
Comment: Your libraries are still there, I'm not sure why you think they're not. Have you done the tutorial? http://virtualenvwrapper.readthedocs.org/en/latest/
Comment: @ThomasOrozco Is there a way of making the pre-existing virtualenv a permanent virtualenv like mkvirtualenv works? Also in the documentation it says mkvirtualenv accepts a path and enviroment_name but when I attempt to run mkvirtualenv path/to/app env_name i get an error stating it only accepts a path argument alone.
Answer:
When i do tutorials like "Effective Django" they use the virtualenv command on an empty folder, then activate it. That works, until tomorrow when I want to work on the app again at which point the virtualenv is gone.

I strongly doubt that this is the case, unless something is deleting your directories overnight. If that is the case, stop putting your code where it is being deleted.
Assuming that is not the case, the solution is for you to go back to the directory you created as a virtualenv, and reactivate it.


Update core via Pantheon

Question: I push all my local changes to the Pantheon git repository, then I update core via the pantheon dashboard. Now I pull from the Pantheon repository with git pull git://github.com/pantheon-systems/drops-7.git master. I am assuming that both versions are identical now. However, when I run git status, I get a message about my branch being ahead of origin/master.
Can somebody explain this to me? How can I get the local and remote repository in sync?
Answer: Yes that makes perfect sense - you've merged changes from the core repo, so your working copy is one commit ahead of your site's dev repo on Pantheon. Note that origin/master refers to the remote representing your repo, not drops-7.git
git push

to send the changes up to your dev site when you're ready to test, then pull them through the dashboard as normal.
Comment: Thanks Clive, That clears it up. I had assumed that the remote repo and drops-7.git were the same.

Update core via Pantheon


Filtro de Buscar por algum motivo não esta buscando o produto

Question: <?php include ('conecta.php'); ?>

    Buscar

      <input type="text" name="buscar" id="buscar" />
    <input type="submit" name="Aceitar" id="Aceitar" value="Buscar" />

    LISTA DE PRODUTOS

    ID
    IMAGEM
    NOME
    DESCRIÇÃO
    PREÇO
    QUANTIDADE
    DATA
    ADICIONAR

  <?php
  $consulta = mysql_query("SELECT * FROM produtos");

  if (isset($_POST['buscar'])){
    $consulta = mysql_query("SELECT * FROM produtos where nome like '%".$_POST['buscar']."%'");
  }

  while($linha = mysql_fetch_array($consulta)) {

    $id = $linha['id'];
    $imagem = $linha['imagem'];
    $nome = $linha['nome'];
    $desc = $linha['descricao'];
    $preco = $linha['preco'];
    $quant = $linha['quantidade'];
    $data = $linha['data'];
    //$adicionar = ' Adicionar '
  ?>

    <?php echo $id; ?>
    <img src="<?php echo $imagem; ?>" width="70" height="70">
    <?php echo $nome; ?>
    <?php echo $desc; ?>
    <?php echo $preco; ?>
    <?php echo $quant; ?>
    <?php echo $data; ?>

      <form action="carrinho.php" method="post" name="comprar">
        <input name="id_txt" type="hidden" value="<?php echo $id; ?>" />
        <input name="nome" type="hidden" value="<?php echo $nome; ?>" />
        <input name="preco" type="hidden" value="<?php echo $preco; ?>" />
        <input name="quantidade" type="hidden" value="1" />
        <input name="Comprar" type="submit" value="Comprar" />
      </form>

  <?php } ?>

Comment: Primeiro problema é utilizar funções `mysql_*`. Elas estão obsoletas no PHP 5 e já foram removidas do PHP 7.
Comment: Qual o problema do código? Qual a sua duvida? Sem você falar, não tem como advinhar.
Answer: Para funcionar os campos input deve estar dentro da tag form
<form action="" method="POST" >
<input type="text" name="buscar" id="buscar" /><input type="submit" name="Aceitar" id="Aceitar" value="Buscar" />
</form>


Lines on a quadric surface

Question: I want to show that:
Let $Q$ be a quadric surface of rank 3 in $\mathbf{P}^3$(over $\mathbf{C}$), then any line in $Q$ must pass through the only singular point of $Q$.
I know that up to a transform of coordinate, we can assume that $Q=\{x_0^2+x_1^2+x_2^2=0\}$ and therefore the singular point is $(0:0:0:1)$. But I have no idea how to proceed. Thanks for any help.
Answer: Suppose for contradiction that some  line $l$ lies on $Q$ ($l\subset Q$) but does not go through the apex (=singular point) $S$ of $Q$.
Then the whole plane $\Pi$ determined by $S$ and $l$ is contained in $Q$ ($\Pi\subset Q$): indeed  for any $L\in l\subset Q$ the line $\overline {SL}$ lies on   $Q$ and $\Pi$ is the union of all those lines $\overline {SL}$ when $L$ runs through $l$.
But any  quadric   containing a plane (here $\Pi\subset Q$)  has rank $\leq 2$ : contradiction to the hypothesis that $Q$ has rank $3$.
Comment: Thanks for your answer! It's very clear and I understand it :)
Comment: Dear user 243987,  I'm glad the answer was useful to you

Lines on a quadric surface


Testing change in categories?

Question: I hope that someone will be willing to help me with the following question. I have data on the numbers of hours participants spent in 6 programs over 2 years. I have already tested whether the number of hours increased over time, but I also want to know whether the proportion of time spent in each of the programs changed over time.
Eg. Program1/Time1 = 2920 hrs/10000hrs; Program1/Time 2 =3200/12000; Program2/Time1 = 4200/10000; Program2/Time2 = 3800/12000, etc.
Would a 2 sample z test for proportion change on each program (perhaps with Bonferoni correction) be appropriate? And/or is there another test(s) That I should be using? Any help would be much appreciated! I am comfortable with SPSS and am starting to learn R, if that makes a difference...
Comment: Oops! Thanks for offering me the opportunity to correct! Your first understanding was correct; I meant for the total hours in Time 1 to be 10000 and Time 2 to be 12000; I have now edited.
Comment: The nature of your data are not yet clear. Are you saying that at time 1 a total of 10000 hours were spent and of those, 2920 were in program 1 and 4200 in program 2, etc.?  If that's the case, why does it look like the total for time 2 is both 10000 hours and 12000 hours?
Answer: Proportion test should be adequate here. prop.test function in R will calculate that.
I don't think you need a multiple hypothesis testing correction here. You only doing a few tests. And in any case  Bonferoni is a very conservative correction. A Benjamini-Hochberg FDR is often a better choice.

Testing change in categories?


Tracking outbound Google Adsense clicks

Question: I would like to be able to track how many clicks are done on Google adsense ads from each node of my site.
The purpose of doing so is to be able to do revenue sharing with the authors of each article that will be published.
This module may seem to be useful: http://drupal.org/project/adsense
Except that it says "Click Tracking: tries to track clicks on the displayed ads, usually failing to do so."
Are there any alternatives?
Thanks in advance for your answers.
Answer: The problem is links are generated by Google. I assume Google tools does not suffice, and you can't generate report of enough quality using Google Analytics - if you could, you wouldn't ask here.
You cannot alter links. If what you display is not what Google provided, you are not getting any money. So the only sure way - generate link like http://example.org/count_ad_click/123dwe324), record click and redirect user - is closed for you.
You could cover ads with transparent link to your counting address, to avoid altering the real one. That counts as click hijacking and can hurt your reputation, badly. Browsers can start to display "possible malware" alerts, SEO position will drown and so on. Oh, and of course no money.
You still can use jQuery to append onclick to those links, and either push events to Analytics or to your own counting mechanism. Both are prone to manipulation, as they happen on a client side and user can fake those clicks all he wants, so you can get any number of false positives. On the other hand, if your reader will have javascript turned off, it will not count him at all, and some anty-hijacking plugins can prevent click count, too. Last but not least, that's the way AdSense module works now, anyway.

Tracking outbound Google Adsense clicks


Installing Redis on CentOS 6.6 final - no package available

Question: I've added the "EPEL" repo:
Loaded plugins: changelog, downloadonly, fastestmirror, presto
Loading mirror speeds from cached hostfile
 * elrepo: repos.mia.lax-noc.com
 * epel: epel.gtdinternet.com
 * remi-safe: remi.xpg.com.br
 * rpmforge: mirror.rit.edu
repo id         repo name                                                   status
base            CentOS-6 - Base                                              6,518
elrepo          ELRepo.org Community Enterprise Linux Repository - el6         333
epel            Extra Packages for Enterprise Linux 6 - x86_64              11,743
extras          CentOS-6 - Extras                                               38
mongodb-org-3.0 MongoDB Repository                                              40
remi-safe       Safe Remi's RPM repository for Enterprise Linux 6 - x86_64      11
rpmforge        RHEL 6 - RPMforge.net - dag                                  4,718
updates         CentOS-6 - Updates                                           1,370
zabbix          Zabbix Official Repository - x86_64                            289
repolist: 25,060

But every time I run:
sudo yum install redis

I get this:
No package redis available.
Error: Nothing to do

NOTE:
I've already ran:
sudo yum clean metadata

But still, can't install redis.
Comment: Did you exclude it?
Comment: No that I know. How can I check?
Comment: Look for exclude directives in yum.conf and in all the .repo files.
Comment: No, there is no such directive in any repo file nor yum.conf
Answer: How did you add the EPEL repo?  Here's what works for me on CentOS 6.6-final
wget http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm
wget http://rpms.famillecollet.com/enterprise/remi-release-6.rpm
rpm -Uvh remi-release-6*.rpm epel-release-6*.rpm
yum install redis -y

Answer: rpm -Uvh http://download.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm

yum --enablerepo=remi,remi-test install redis

Comment: You need to install remi-release, not epel-release, which is already installed ;)
Answer: sudo yum list redis
sudo yum install redis.x86_64  # something list before.

You could list the packages by yum list and then choose which to install.
You get package not available is because the name you type is not exist, so list before you install.


Cloudflare e Github Pages com erro de DNS

Question: Criei uma page estática e publiquei no Github pages, até então com o domínio padrão username.github.io/repo tava funcionando tudo de boas, mas então comprei um domínio .net na Locaweb, e quando tentei conectar com Cloudflare também, não ta funcionando, sempre dá o erro DNS_PROBE_FINISHED_NXDOMAIN.
Configurações Cloudflare:

Github:

Erro apresentado no Chrome:

Alguém sabe o que pode estar errado?
Tentei seguir alguns vários tutoriais, mas nenhum antecipou esse erro e como resolver
Comment: Seu domínio já está direcionando para o cloudflare, mas o subdomínio "www" não parece corretamente configurado. Ao entrar no endereço natanapps(...) responde com 404. Recomendava configurar o redirecionamento do www para a raiz do domínio diretamente no cloudflare inclusive forçando o uso de https.
Answer: A propagação de DNS pode demorar até 48h para ocorrer em todo o mundo. Entretanto, geralmente demora poucas horas.
Para verificar a propagação de DNS recomendo utilizar o site https://www.whatsmydns.net/, colocando o seu domínio e a opção A, para verificar o IP que está respondendo pelo mesmo. Ou um subdomínio e A ou CNAME, de acordo com a sua configuração. Também pode fazer o mesmo com outros tipos de configurações, como MX, para verificar o servidor de emails.
Comment: Entendi! Lá com subdomínio e ```CNAME``` está tudo marcado em vermelho ainda, só com ```A``` que só falta um...


How do I correctly manage the disposing of a DataContext?

Question: I have a web service that is quite heavy on database access. It works fine in test, but as soon as I put it in production and ramp up the load it starts churning out errors that are raised when something calls a method in the DataContext. The error is normally one of these:

Object reference not set to an instance of an object
Cannot access a disposed object. Object name: 'DataContext accessed after Dispose.'.

but not always.
Any single web service requests can result as many as 10 or 15 database queries, and 1 or 2 updates.
I've designed my application with a data access layer which is a bunch of objects that represent the tables in my database which hold all the business logic. The is a separate project to my web service as it's shared with a Web GUI.
The data access objects derive from a base class which has a GetDataContext() method to initiate an instance of the data context whenever it's needed.
All throughout my data access objects I've written this:
using (db = GetDataContext())
{
    // do some stuff
}

which happily creates/uses/disposes my DataContext (created by sqlmetal.exe) object for each and every database interaction.
After many hours of head scratching, I think I've decided that the cause of my errors is that under load the datacontext object is being created and disposed way too much, and I need to change things to share the same datacontext for the duration of the web service request.
I found this article on the internet which has a DataContextFactory that seems to do exactly what I need.
However, now that I've implemented this, and the DataContext is saved as an item in the HttpContext, I get...

Cannot access a disposed object.
Object name: 'DataContext accessed after Dispose.'

...whenever my datacontext is used more than once. This is because my using (...) {} code is disposing my datacontext after its first use.
So, my question is... before I go through my entire data access layer and remove loads of usings, what is the correct way to do this? I don't want to cause a memory leak by taking out the usings, but at the same time I want to share my datacontext across different data access objects.
Should I just remove the usings, and manually call the dispose method just before I return from the web service request? If so then how go I make sure I capture everything bearing in mind I have several try-catch blocks that could get messy.
Is there another better way to do this? Should I just forget about disposing and hope everything is implicitly cleaned up?
UPDATE
The problem doesn't appear to be a performance issue... requests are handled very quickly, no more than about 200ms. In fact I have load tested it by generating lots of fake requests with no problems.
As far as I can see, it is load related for one of two reasons:

A high number of requests causes concurrent requests to affect each other
The problem happens more frequently simply because there are a lot of requests.

When the problem does occur, the application pool goes into a bad state, and requires a recycle to get it working again.
Comment: 17 `DataContext` instances per request doesn't seem much to me. The creation of a `DataContext` is very light. It might win you some performance, because it caches entities, but that's all. Did you profile the queries send to the database? How many queries are fired during 1 request?
Comment: @abatishchev: Thanks for the retag... but why did you revert all my typo fixes?
Comment: @Steven: All of the queries are done via stored procs which may contain a few queries. It does around 24 sql queries in total per request. The performance is not the problem though, the request completes in around 200ms (measured by log file timestamps). The problem is when more than 20 requests hit in quick succession, that's when it starts to error.
Comment: What makes you think that the error Object reference not set to an instance of an object has anything to do with the disposing of the datacontext? I would rather think about a problem with deferred loading of related entities or something like that?
Comment: @BG100: @Plean might be spot on, and again, 24 sql queries and 24 `DataContext` creations is peanuts. I advice you to do some more performance measuring to find the actual bottleneck in the system. I'm pretty sure the number of `DataContext` is not the problem. Run the creations in a tight loop to see how many you can do in a second.
Comment: @Plean: Can you explain a bit more about "deferred loading of related entities"? I'm not sure what this means...
Comment: @Steven: This doesn't seem to be a performance problem in the sense things take too long.... the problem occurs when there are lots of requests per min, either due to high load or it could be because there are more requests so the problem occurs more frequently. When it does occur, the app pool seems to go into a bad state and I need to recycle to get it working again.
Comment: @BG100: I can't imagine this being caused by L2S. Could it be a race condition? Are you storing the `DataContext` somewhere?
Comment: @Steven: It could be a race condition, but I have no idea how to debug this! No, I'm diligently creating a new DataContext for each and every database interaction surrounding it in a using block... hence my thoughts about changing it to share the DataContext between queries... but as yet I haven't done this.
Answer: Although I would prefer the unit-of-work approach using using, sometimes it doesn't always fit into your design. Ideally you'd want to ensure that you are freeing up your SqlConnection when you're done with it so that anothe request has a chance of grabbing that connection from the pool. If that is not possible, what you would need is some assurance that the context is disposed of after each request. This could be done a couple of ways:

If you're using WebForms, you can tie the disposal of the DataContext at the end of the page lifecycle. Make a check to the HttpContext.Items collection to determine if the last page had a data context, and if so, dispose of it.
Create a dedicated IHttpModule which attaches an event to the end of the request, where you do the same as above.

The problem with both of the above solutions, is that if you are under heavy load, you'll find that a lot of requests hang about waiting for a connection to be made available, likely timing out. You'll have to weigh up the risks.
All in all, the unit-of-work approach would still be favoured, as you are releasing the resource as soon as it is no longer required.
Answer: I managed to fix this myself...
I had a base class that had a method that would create the DataContext instance, like this:
public abstract class MyBase {

    protected static DataContext db = null;

    protected static DataContext GetDataContext() {
        return new DataContext("My Connection String");
    }

    // rest of class
}

And then, in the classes that inherited MyBase where I wanted to do my queries, I had statements like this:
using (db = GetDataContext()) { ... }

The thing is, I wanted to access the database from both static methods and non-static methods, and so in my base class, I'd declared the db variable as static... Big mistake!
If the DataContext variable is declared as static, during heavy loads when lots of things are happening at the same time the DataContext is shared among the requests, and if something happens on the DataContext at exactly the same time it screws up the instance of the DataContext, and the Database connection stored in the Application pool for all subsequent requested until it's recycled, and the database connection is refreshed.
So, the simple fix is to change this:
protected static DataContext db = null;

to this:
protected DataContext db = null;

...which will break all of the using statements in the static methods. But this can easily be fixed by declaring the DataContext variable in the using instead, like this:
using (DataContext db = GetDataContext()) { ... }

Answer: This happens if you have, for example, an object that references another object (i.e. a join between two tables) and you try to access the referenced object after the context has been disposed of. Something like this:
IEnumerable<Father> fathers;
using (var db = GetDataContext())
{
  // Assume a Father as a field called Sons of type IEnumerable<Son>
  fathers = db.Fathers.ToList();
}

foreach (var father in fathers)
{
  // This will get the exception you got
  Console.WriteLine(father.Sons.FirstOrDefault());
}

This can be avoided by forcing it to load all the referenced objects like this:
IEnumerable<Father> fathers;
using (var db = GetDataContext())
{
  var options = new System.Data.Linq.DataLoadOptions();
  options.LoadWith<Father>(f => f.Sons);
  db.LoadOptions = options;
  fathers = db.Fathers.ToList();
}

foreach (var father in fathers)
{
  // This will no longer throw
  Console.WriteLine(father.Sons.FirstOrDefault());
}

Comment: This was my initial thoughts on what the problem was, however I have checked and there is no reference to an object returned from the datacontext outside of the using block. This is a non-deterministic problem that I cannot replicate in a development environment. If your suggestion was the problem then I'd easily be able to replicate this.
Comment: @BG100: Indeed. Best of luck then. Heisenbugs are always a pain.


Carregar Window Form dentro Container VB.net

Question: Opa
Tenho uma função para abertura de forms dentro de um container geral.
Function carrega_form(ByRef ctl As Control, ByRef frm As Form)
    If ctl IsNot Nothing AndAlso frm IsNot Nothing Then
        frm.TopLevel = False
        frm.FormBorderStyle = FormBorderStyle.None
        frm.Dock = DockStyle.Fill
        frm.Visible = True
        ctl.Controls.Add(frm)
    End If
End Function

Para chama-la uso:
carrega_form(container, New frm_content_cadastro_botoes)

Senha que o containerfica num form principal, o que tenho que fazer é apenas carregar outros forms dentro deste container, o problema é que isso ocorre apenas uma vez, ou seja, ao executar a função o form é aberto, mas, ao executar novamente não acontece nada.
Tentei antes de chamar a função usar: Me.hide, mas, ainda não chama o form como deveria.
Se usar a chamada para containers diferentes funciona.
O objeto container é um Panel
Answer: Os comentários explicam todas alterações que fiz. Alguma delas pode resolver seu problema.
'                                              | você não precisa de uma
'                                              | referência para uma forma
'                                              | que está chamando sem
'                                              | referência
' Isso não retorna nada, então                 |
' não precisa ser uma Function                \ /
Public Sub carrega_form(ByRef ctl As Control, ByVal frm As Form)
    ' Verificação nula sempre no início do código
    ' Vamos economizar processador, galera
    If ctl Is Nothing Then Exit Sub
    ' Remove os controles antigos
    For i As Integer = 0 To ctrl.Controls.Count - 1
        ctrl.Controls.RemoveAt(i)
    Next
    ' Converte implícitamente a form para control
    Dim c As Control = frm
    ' Não precisamos mais da form
    frm.Dispose()
    ' Isso já define local e tamanho do controle.
    c.Dock = DockStyle.Fill
    ' Será visível?
    c.Visible = True
    ' Adiciona o controle.
    ctl.Controls.Add(c)
End Sub


.click() causing repeat confirm() & double duplication result

Question: Working CRUD app

I have/had a successful CRUD CMS working using AJAX...that is, until I added pagination with click ajax events (I'll share this script below).
+-----------------------------New-----Edit-----Duplicate-----Delete-----+
|---+---------+----------------+--------------------------------------------------|
| O | .Title | Description | ............................................................|
|---+---------+----------------+--------------------------------------------------|
| O | Item 1 | .Blah Blah. | ............................................................|
|---+---------+----------------+--------------------------------------------------|
| O | Item 2 | .Blah Blah. | ............................................................|
|---+---------+----------------+--------------------------------------------------|
| O | Item 3 | .Blah Blah. | ............................................................|
|---+---------+----------------+--------------------------------------------------|
How it works:
When the buttons edit/duplicate/delete are clicked...
1. the user gets a confirmation alert "Are you sure...?"
2. the selected checkboxes are sent via ajax to the corresponding href [.php] be actioned.
3. the page refreshes
function actionButton () {
  if($(this+' span').hasClass("dead")) { }else{
        page    = $(this).attr("href");
        ids     = new Array()
        a       = 0;
        $(".chk:checked").each(function(){
           ids[a] = $(this).val();
           a++;
        })
        if (confirm("Are you sure you want to affect the selected record(s)?")) {
         $.ajax({
                url         :   page,
                type        :   "POST",
                data        :   "id="+ids,
                cache       :   false,
                dataType    :   'json'
                })                              // end AJAX
         .done(function(data) {
              window.console.log(data);         // log data to the console so we can see
                                            // Handle ERRORS
                                            // After form submission, redirect a user
                                            // to another page
                window.location.reload();

          })
         .fail(function(data) {             // promise callback
              window.console.log(data);         // show any errors in console
          });
        }                                       // end CONFIRMed
        return false;
  };
};

Click:
$(document).ready(function() {
    $('#btn_del').click(actionButton);          // DELETE record(s) button

    $('#btn_pub').click(actionButton);          // PUBLISH record(s) button

    $('#btn_unpub').click(actionButton);        // UNPUBLISH record(s) button

    $('#btn_dup').click(actionButton);          // DUPLICATE record(s) button
                                                // ----------------------------------
                                                // This feature is currently configured
                                                // to only allow duplication of
                                                // one(1) x record at a time
                                                // The configurations above disable
                                                // the DUPLICATE button when more
                                                // than one(1) record is checked
});

The Change:
I added an ajax click pagination manager that populate id=pagination...with $('#pagination').html(response);. This pagination is working as I'd hoped.
+-----------------------------New-----Edit-----Duplicate-----Delete-----+
|---+---------+----------------+--------------------------------------------------|
| .... < 1  2 3 4 5 >  .........................................................................|
| O | .Title | Description | ............................................................|
|---+---------+----------------+--------------------------------------------------|
| O | Item 1 | .Blah Blah. | ............................................................|
paginate.js
$(function(){
    $.ajax({
          url       : "populateRecordsPaginate.php",
          type      : "POST",
          data      : "actionfunction=showData&page=1",
          cache     : false,
          success   : function(response){
                        $('#pagination').html(response);
                      }
    });
          $('#pagination').on('click','.page-numbers',function(){
               $page = $(this).attr('href');
               $pageind = $page.indexOf('page=');
               $page = $page.substring(($pageind+5));

                $.ajax({
                    url     : "populateRecordsPaginate.php",
                    type        : "POST",
                    data        : "actionfunction=showData&page="+$page,
                    cache       : false,
                    success : function(response){
                                  $('#pagination').html(response);
                                }
                });
                return false;
          });
});

Problem:
Since adding the pagination.js, now...

If I DO NOT click on any of the pagination links, the button actions work correctly as before.
If I DO click on any of the pagination links, the button actions behave differently:

the confirm alert happens to repeat once, twice, sometimes three times
if I confirm each time is pops up, then the action finally works, with the exception of DUPLICATE...this seems to produce double duplicates depending on the number of times I've confirmed
Comment: When is actionButton() called?
Comment: @WingLian Apologies. I had the click action written in there before. I must've deleted by accident. I've `edited` the original post to include `Click` details.
Comment: does there happen to be any javascript in the ajax response? more specifically the $(document).ready() section?
Comment: @WingLian Thanks for your assistance. I just managed to finally get it to work. See the answer I've just posted. Simply had to add `e.stopImmediatelyPropogation();` to the actionButton function.
Answer: Found it with help from stackoverflow.
I found I simply had to add e.stopImmediatePropagation() to the start of the the actionButton function. That seems to have fixed the problem nicely.
function actionButton (e) {
    e.stopImmediatePropagation();


Para que serve o arquivo .env no Laravel 5?

Question:
Para que serve o arquivo .env?
No app.php tem env => env('APP_ENV','production'). O que seria esse production? Qual outra string pode ir ali?
E a var APP_ENV? O que significa?
Answer: No arquivo .env ficam armazenadas as configurações de ambiente do Laravel.
De acordo com a documentação:
Configurações do Ambiente
É muito útil ter diferentes valores de configuração baseado no ambiente em que a aplicação está rodando. Por exemplo, você pode querer usar diferentes drivers de cache localmente e outro no servidor de produção. Isso é muito fácil usando as configurações baseadas em ambiente.
Para tornar isso fácil, o Laravel utiliza a Biblioteca PHP DotEnv do Vance Lucas (vlucas). Numa instalação inicial do Laravel, no diretório principal da aplicação conterá o arquivo env.example. Se você instalou o Laravel via Composer, esse arquivo será automaticamente copiado para .env. Entretanto, você pode copiar ou renomeá-lo manualmente.
Todas as variáveis listadas nesse arquivo serão carregadas a variável super global do PHP $_ENV quando sua aplicação receber uma requisição. Você pode usar a função utilitária env para pegar esses valores. Se você revisou os arquivos de configuração do Laravel, você deve ter percebido que muitas das opções já utilizam essa função utilitária.
Você é livre para modificar suas variáveis de ambiente como quiser, para sua aplicação local ou para seu servidor de produção. Entretanto, seu arquivo .env não deve ser versionado, por que cada desenvolvedor / servidor podem precisar de uma configuração diferente desse arquivo.
Se você está desenvolvendo em equipe, você pode incluir o arquivo .env.example e adicionar lá alguns comentários sobre a configuração do arquivo, para que cada desenvolvedor entenda claramente quais configurações eles devem fazer em seus próprios .env para rodar sua aplicação.
Acessando o Ambiente da Aplicação Atual
Você pode acessar o ambiente atual da sua aplicação pelo método environmentdo facade App:
$environment = App::environment();

Você também pode passar arguementos para o método environment para verificar se o ambiente atual é o que foi passado por argumento. Você pode até passar multiplos ambientes ou fazer a chamada ao método múltiplas vezes, se necessário:
if (App::environment('local')) {
    // Aqui instruções para rodar no ambiente local
}

if (App::environment('local', 'staging')) {
    // Aqui instruções para rodar no ambiente local OU staging
}

Uma instancia da aplicação também pode ser acessada pela função utilitária app:
$environment = app()->environment();

Answer:
Pra que serve o arquivo .env?

O arquivo .env é uma maneira mais fácil de carregar variáveis de configuração personalizadas que o seu aplicativo precisará ter.
Isso significa que você terá que modificar o arquivo fora do projeto, e todas as variáveis de ambiente serão sempre definidas não importando como você execute seu código isso se reflete até em servidores embutidos do PHP.

O que seria esse production?

O production é o ambiente que sua aplicação se encontra, podendo também ser definido como local.

E a var APP_ENV? O que significa?

ENV vem de Environment, que significa Ambiente. Toda configuração criada gera uma chave com esse valor para definição do ambiente em que se encontra seu projeto.
Detalhes

Environment Detection & Environment Variables
Configurando Environment


strtok() function automatically ignores data that isn't my separation character

Question: I have a text file I am trying to use strtok to separate the data.  The text file looks like this.
SET,SDI,1,Test1
SET,SDI,2,Test 2
SET,SDI,3,Test Test 3
SET,SDI,4, Test 4
SET,SDI,5,Test  5

My strtok code works up until the point where spaces are introduced into the 4th value ("Test x"). Even though I specifically defined my separation character to be a comma (",").
Here is the output.
printf("%s, %s, %s, %s\n", values[0], values[1], values[2], values[3]);
SET, SDI, 1, Test1
SET, SDI, 2, Test
SET, SDI, 3, Test
SET, SDI, 4, Test
SET, SDI, 5, Test

Is there a way I can get strtok to recognize the 4th value as one value instead of losing the data after the whitespace?
Here is my strtok code:
void openfile(char *file_name){
    FILE *file;
    char line[100];
    char sep_char[] = ",";
    char* token;

    char var[20];
    char values[10][20];
    int i;

    file = fopen(file_name, "r");
    if (file != NULL) {
        while (fgets(line, 100, file) != NULL) {
            i = 0;
            token = strtok(line, sep_char);
            while (token != NULL) {
                sscanf (token, "%s", &var);
                strcpy(values[i++], var);
                token = strtok(NULL, sep_char);
            }
            printf("%s, %s, %s, %s\n", values[0], values[1], values[2], values[3]);

        }
        fclose(file);
    }
    else {
        printf("Error");
    }
}

Thanks all!
Answer: The problem is with your sscanf statement: it scans the token up to the first space. Just leave that line out and do
strcpy(values[i++], token);

I think that would do it.
Answer: This is a common problem with using scanf. It stops when it hits a white space character. Read the whole line using fgets, then use strtok on it. Here's the man page for fgets.
Edit: I didn't look closely enough at your implementation. You are using fgets to read the line. I agree with Floris. You don't need the scanf in there. You already have a reference to the token, simply just copy it to your value array.