an extension for one of two homotopic maps implies the existence of a homotopic extension for another map.

Question: Consider $A \subset X$ closed and $X$ as a compact metric space and $f,g : A \rightarrow S^{1}$ as two homotopic maps.$f$ has a continuous extension to a map $F:X \rightarrow S^{1}$. prove that $g$ has a continuous extension homotopic with $F$.
Is there an hint?
Thank you very much.
Answer: Let $D(Y)$ be the diameter of the set $Y$. Let $t(x)$, for $x \in A$  be the biggest real number such that both $D(F(X\cap B(x,t(x)))) < \frac 13$ and $D(g(A \cap B(x,t(x)))) < \frac 13$. We have $t(x)>0$ for all $x \in X$ thanks to continuity.
Now we will extend the function to a set $T = A \cup (B(x,t(x)/2) \cap X)$. Let $V=(B(x,t(x)/2) \cap X)$. As the image of $V$ by $g$ has a small diameter, it can be identified with $\Re$ , and therefore one can apply Tietze Urysohn extension theorem with the bounded property to get the function $g_2$. As the image of $V$ by $F$ can also be identified to $\Re$, so let's call this function $F_2$ Also, let $h$ be the restriction of the homotopy to $T$. For every $x \in T$ one can lift the path $h(x , \cdot)$. This lifted paths can be joined continuous(easy to see), in order to have a function $h_2$ whose codomain is $\Re$. By combining the functions $F_2$,$h_2$ and $g_2$ over the domain $V \times [0] \cup (V \cap A) \times [0,1] \cup  V \times [1]$ (on this order), we can apply Tietze Urysohn extension theorem again. This (when reprojected back to $S_1$) give the extended homotopic function for $T$.
Now we can se the problem changing $g$ by $g_2$ and $A$ by $T$. All the given properties are the same, and as we bounded the extension, the function $t$ is still the same for this new problem. This means the the same $B(x,t(x))$ can be chosen to extend $g_2$. As $X$ is compact, we have a finite cover of this balls, and therefore we can repeat this extension a finite number of times to get the extension over all $X$.
The balls mentioned above are sometimes open and sometimes closed, it's not hard figure out which is which so that all the theorems apply.


Retornar valor correspondente a data

Question: Tenho uma tabela com valores e com datas referente ao custo de um veículo. Porém a tabela é preenchida da seguinte forma:
data_saida | custo_saida
-------------------------
2019-11-17 | 25
2019-11-18 | 20
null       | 10

O preenchimento é feito dessa forma pois os dias específicos são menos comuns, e agiliza no input de informação do usuário.
Eu preciso que quando a data_saida for 17/11 retorne o custo_saida 25, quando for 18/11 retorne 20, e quaisquer outros dias retorne 10 (exemplo: 19, 20 e 21/11).
Já tentei diversas querys e nenhuma obtive sucesso:
SELECT custo_saida
FROM tabela WHERE data_saida = COALESCE('2019-11-19', null::date)

A query acima retorna o custo_saida correto quando a data procurada corresponde com as datas na tabela, porém não retorna nenhum valor quando a data_saida é outra data qualquer, como no exemplo 19/11.
SELECT custo_saida
FROM tabela WHERE (data_saida = '2019-11-19' OR data_saida is null)

Já a query anterior retorna correto quando a data procurada não foi definida no campo data_saida da tabela, porém quando procuro por uma data que esteja definida, por exemplo 18/11, ele me retorna os valores 20 e 10.
E eu preciso dessa query para ser subquery de uma principal, sendo assim, ela precisa retornar apenas um valor.
Há alguma forma para fazer isso?
Comment: Pela sua explicação podemos concluir que podem existir data_saida em sua tabela que não estejam associadas a um custo_saida?
Comment: @anonimo Na verdade é o contrário, há custo_saida sem data_saida associada. Se for informada uma data que não conter na planilha, essa data_saida receberá o custo_saida onde a data_saida é null. E quando for informada uma data_saida que conter na planilha, retornará o valor do custo_saida correspondente.
Answer: Tente dessa forma.
SELECT CASE WHEN data_saida is null THEN 10 ELSE custo_saida END AS custo_saida
FROM tabela

Answer: Tente dessa forma. Basta substituir a data 2019-11-19 pela data que deseja procurar.
SELECT custo_saida
FROM tabela
WHERE (data_saida = '2019-11-19' OR data_saida IS NULL)
ORDER BY data_saida DESC NULLS LAST
LIMIT 1

Comment: @thiagofred, este comando resolveu a sua necessidade? Na outra resposta você disse que tinha que retornar o campo *data_desejada*. Basta adicionar no SELECT após o campo *custo_saida*
Comment: Sim, este comando também é uma forma de resolver a minha necessidade.
Answer: Veja se é isto:
SELECT (CASE WHEN EXISTS (SELECT 1 FROM tabela aux1 WHERE aux1.data_saida = data_desejada::date)
                        THEN (SELECT custo_saida FROM tabela WHERE data_saida = data_desejada::date)
                        ELSE (SELECT custo_saida FROM tabela WHERE data_saida IS NULL)
          END) AS custo_saida;

Comment: Funciona para o que eu perguntei porém preciso retornar também a data_saida (eu esqueci de editar a pergunta).
Comment: Você precisa retornar a data_saida ou a data_desejada? Note que a data_saida será NULL se ela não existir em sua tabela.
Comment: Isso, preciso da data_desejada, consegui fazer inserindo a data_desejada após o custo_saida. Vou avaliar qual  é a melhor opção.

Retornar valor correspondente a data


Binary version of Probabilistic Matrix Factorization in pymc?

Question: I'm a newby in statistics, this is my first post, sorry for any possible mistake.
There is a good Bayesian Probabilistic Matrix Factorization model introduced in:
    Bayesian Probabilistic Matrix Factorization using Markov Chain Monte Carlo
I was trying to implement a Binary version of it, i.e., all the Entries in the rating matrix is 0 or 1, you may think of it as indicating whether each rating is missing or not. So I guess the latent vectors U and V should also be changed to Binary.
Now, since I'm not good at statistics, my guess is that I should make the following change on the generative model of 1:
Change the Multivariate Gaussian Priors on U,V into a set of Bernoulli priors, e.g.,
for a latent vector $U_i$, its elements are deemed to be generated from
$$
U_{i,k} \sim \mathrm{Bernoulli}(\pi_k) \\
\pi_k \sim \mathrm{Beta}(\alpha,\beta)
$$
$k=1...D$, $D$ is the dimension of latent factors, $\alpha,\beta$ are certain hyperparameters.
Is this the right model? If so, is it possible to implement its MCMC parameter estimation using pymc? Just show me a simple outline of the pymc code will be perfect.

This is a huge problem for me. Thanks in advance!
Answer: You don't necessarily need to change $U$ and $V$ to be binary as well; in fact, doing so will probably be somewhat harmful. Remember that $\mathbb{E} R_{ij} = \sum_k U_{ik} V_{jk}$, so that if $U$ and $V$ have binary entries, for $\mathbb{E} R_{ij}$ to be 0 or 1, at most one corresponding pair of entries can be 1.
One thing you could do is just to use the BPMF model as-is, probably centering your data (subtracting the mean) beforehand. I would expect this to work reasonably well.
A better option might be to keep the same distributions on $U$ and $V$, but change the mean of $R$ to be "squashed" through, say, a logistic function $\mathbb{E} R_{ij} = 1/(1 + \exp(- U_i^T V_j)$ (and still modeling R as normal); this is what was done in the original (non-MCMC) PMF paper. This makes the model predictions not actually binary, but at least they're in the right range. I'm not sure how easily pymc allows you to model this (I've never used it).
A more "pure" option, to keep the data types of the models correct, would be to model $R$ as Bernoulli with parameter based on $U_i^T V_j$; probably squash it as above, or at least make sure that in your code it's truncated into [0, 1].
I don't know how the different options will affect the efficacy of the simple Metropolis-Hastings algorithm that the current version of pymc uses. I believe it would be less of an issue with the more powerful algorithms in the alpha version (pymc3), but I have no idea how stable or usable that code is yet.
Comment: Good point, U and V can't be binary! I think your second model is what I need, but I need to work out the inference. I will post another question on the Gibbs sampling of [that paper](http://www.cs.toronto.edu/~rsalakhu/papers/bpmf.pdf), hope you could answer. Many thanks!
Answer: According to this post, it seems I have to give up pymc --- The ratings are 'determinitic' given U and V, while pymc only allows observations to be 'stochastic', maybe that's why I can't find any pymc implementation of PMF out there.
This maybe useful for someone trying to use pymc in MF like me.
Comment: In the original model the ratings have a normal distribution around $U_i^T V_j$. An alternative to pymc is [Stan](http://mc-stan.org), for which I have a [somewhat-optimized BPMF model](http://git.sccs.swarthmore.edu/web/dougal/active-matrix-factorization/tree/stan-bpmf/bpmf.stan) (and [one with $W_0$ hardcoded to the identity](http://git.sccs.swarthmore.edu/web/dougal/active-matrix-factorization/tree/stan-bpmf/bpmf_w0identity.stan), and a [more straightforward but slower one](http://git.sccs.swarthmore.edu/web/dougal/active-matrix-factorization/tree/stan-bpmf/bpmf_straightforward.stan)).
Comment: Thanks for pointing out, and sharing the code! I'll try to get it running for my problem.
Comment: @Dougal I have eventually worked out the 2nd model you mentioned by using your Stan code with some modifications. Thanks for introducing me to Stan, a really wonderful tool!
Comment: great! Glad I could help. :)


Indexed families and subsets

Question: Having some trouble being able to do this question and would really appreciate some help with it.

Perhaps I would say that for 1. that the union for i belonging to I that Ai = {x | x belonging to Ai for at least i belonging to I} and
the intersection for i belonging to I that Bi = {x | x belonging to Bi for every i belonging to I}
I am still quite lost on how to solve this though.
Answer: Hint: You should assume that $x$ is some element in $\bigcup_{i\in I} (A_i - B_i)$ and then show that it must also be an element of $\left(\bigcup_{i\in I} A_i - \bigcap_{i\in I} B_i\right)$.
Possible solution:

If $x \in \bigcup_{i\in I} (A_i - B_i)$, there exists some $k$, such that $x\in(A_k-B_k)$. This means that $x\in A_k$ and $x\not\in B_k$. It follows that $x\in \bigcup_{i\in I} A_i$, since this is the union of all $A_i$, and that $x\not\in \bigcap_{i\in I} B_i$ as it is not in all $B_i$ (in particular, $x\not\in B_k$). Thus we have $x\in \left(\bigcup_{i\in I} A_i - \bigcap_{i\in I} B_i\right)$.

Indexed families and subsets


Formula for $\sum\limits_{j=1}^{m-1}\frac{1}{\sin^{2p}(\frac{j\pi}{m})}$

Question: Let $m\geq 2$ be an integer, then there is the well known formula
$$\sum\limits_{j=1}^{m-1}\frac{1}{\sin^2(\frac{j\pi}{m})}=\frac{m^2-1}{3},$$
I'm interested in similar equations for the following expression
$$\sum\limits_{j=1}^{m-1}\frac{1}{\sin^{2p}(\frac{j\pi}{m})}=(...),$$
for any $p\in\mathbb{N}$. Does someone know whether there are well known formulas like for $p=1$?
Best wishes
Comment: Each side is of the form $$\sum_1^{\infty}{c_r\over r^2}$$ for some integer coefficient $c_r$ which counts the (net) number of times the term $1/r^2$ appears on that side. So maybe you can show that $c_r$ is the same on the left side as on the right.
Comment: Taking $\frac{d^2}{dx^2}\log$ of the Weierstrass sine product gives $\sum_{k \in \mathbb{z}} (mk-j)^{-2}=\pi^2 m^{-2} \csc^2(\pi j/m)$ so it suffices to prove $$\sum_{j=1}^{m-1} \frac{1}{\sin^2(\frac{\pi j}{m})} = \frac{m^2-1}{3}$$
Comment: A related question http://math.stackexchange.com/questions/544228/is-sum-k-1m-1-frac1-sin2-frack-pim-fracm2-13-true-for-m/544488#544488
Comment: @Gerry Myerson: I had this idea, but I could not prove it by this idea. But I will try it again, maybe I had a mistake in my calculations.
Comment: @nospoon: actually the equality which I asked for is used in my book to prove the equality you wrote down. By the way, I'm interested in equations of the type $\sum\limits_{j=1}^{m-1}\frac{1}{sin^(2p)(\frac{j\pi}{m})}=(...)$ for any $p\in\mathbb{N}$ are there formulas known for that?
Answer: Your sums may be seen (with a minor fix) as
$$ \sum_{\zeta\in Z} \zeta^{-2p} $$
where $Z$ is the set given by the roots of a Chebyshev polynomial of the second kind. By Newton's identities, in order to compute our power sums it is enough to compute the right number of coefficients of a Chebyshev polynomial of the second kind. In order to do that, we just need to exploit the binomial theorem, giving:
$$ U_n(x)=\sum_{k=0}^{\left\lfloor\frac{n}{2}\right\rfloor}\binom{n-k}{k}(-1)^k (2x)^{n-2k}.$$


Notating Sheet Music with Strict Tempo for Accompaniment but Rubato for Vocalist

Question: I have some sheet music for vocal + piano accompaniment where I want to notate that the vocalist should feel out the rhythms and phrases and sing expressively while the pianist maintains a steady tempo. I'm concerned marking it simply "rubato" might be misleading and the pianist may think they're supposed to follow the vocalist. Is there a better way to notate that or is it enough to notate the tempo as "Expressively" or "Rubato" (plus a bpm) and assume that, if the piano part is rhythmic (mostly 8th notes in 4/4), the pianist will understand they should stick to the beat?
Comment: Note, adding a metronome marking does nothing to indicate rhythmic rigidity or flexibility. Even the most flexible piece has a tempo, and might indicate it. Also: if you have a score showing both parts, you can align expressive text with the staves separately.
Comment: How bad would it be if the pianist _did_ follow the singer?  What if the pianist took some liberty with the meter or rhythm but to a lesser degree than the singer?  I suspect that you don't really want the pianist to be mechanically strict, for example as strict as a computer would be.
Comment:  How about "Vocals with feeling.  Pianist, no, just no"
Answer: I posted this as a comment but @Bob_Broadley suggested I post it as an answer so here goes:
This is pretty wordy but sometimes using a verbal description is the best way to go. There is no rule that says musical instructions must be only one or two words long. How about: "vocalist ad-lib rhythm over steady piano accompaniment" ?
Answer: So often in cases like this, using words clears things up really easily. Why not use a marking for the tempo such as "Vocals - Rubato; Piano - Tempo Giusto". It's short and to the point. Alternatively, use English, as @John Belzaguy suggests.
Answer: This happens all the time in popular music.  Streisand rarely ever DOESN'T do it!
If it's not obvious from the style, give plain text instructions.  'Maintain rhythm, vocalist may float'.
Best not to include the literal melody in the accompaniment  if this is going to happen!
This can be a bugbear when accompanying at sight.   It isn't always clear whether the singer wants to play around rhythmically over a steady beat, or wants 'colla voce'.   I've had sticky moments over this as a club/audition pianist!
Comment: A few words with a vocalist who knows what they're doing usually clears away the problem!
Comment: "A few words with a vocalist who knows what they're doing..."   Yes, that sort of vocalist is no problem!


Rayleigh quotient on circular region of radius 2

Question: I' m struggling with the following problem.
We have the eigenvalue problem:
$$u'' + \lambda u = 0$$
with associated boundary condition:
$$u' + 3u = 0$$
Now by using the Rayleigh quotient for $0 \leq r \leq 2$and the trial function:
$$\psi_0(r)= \alpha - r $$
where $\alpha$ is chosen so that $\psi_0(r)$ satisfies the boundary condition at $r=2$.
Find the lowest eigenvalue $\lambda_1$
Own work:
I started finding the correct $\alpha$ that suites the BC, hence:
$$ -1 + 3 (\alpha -2) = 0$$
Hence $\alpha = \frac{7}{3}$
An upper bound to $\lambda_1$ is given by the Rayleigh quotient,
$$J[\psi_0] = \frac {D[\psi_0]}{H[\psi_0]}$$ where
$$D[\psi_0] = \int_{\Omega}|\bigtriangledown \psi_0|^2 dx + \int_{\partial \Omega} \psi_{0}(2)^2 dx \quad H[\psi_0] = \int_\Omega \psi_0^2 dx$$
(in polar form)
$$\bigtriangledown = \frac{\partial}{\partial r} + \frac {1}{r} \frac{\partial}{\partial \theta}$$
Thus $|\bigtriangledown \psi_0| = |\psi'_0(r)|=-1 $ and
$$\int_\Omega f(r)dx = \int_0^2 2\pi r f(r)dr$$
so that:$$J[\psi_0] = \frac {\int_0^2 (r + \frac{1}{9}r)dr}{\int_0^2 r(\alpha -r)^2dr}$$
(Already cancelled the $2\pi$ out and left in $\alpha$)
These integrals can be evaluated as:
$$\int_0^2 \frac{10}{9}r dr = \big[\frac {10}{18} r^2 \big]_{0}^{2} = \frac {20}{9}$$
and
$$\int_0^2 r(\alpha -r)^2dr = \big[\frac{1}{2} r^2 \alpha^2 - \frac{2}{3} \alpha r^3+ \frac{1}{4} r^4 \big]_{0}^{2} = 2\alpha^2 - \frac{16 \alpha}{3}+4 = \frac {22}{9}$$
Which would give $$J[\psi_0]= \frac{10}{11}$$
Which is not correct $\big(\lambda_1 \leq \frac {12}{11} \big)$
Perhaps someone can help me, I think I go wrong by defining $D[\psi_0]$
Comment: Looks like you edited the question, The domain is still the unit disk? The derivative in the initial equation is the Laplacian or just differentiation with respect to the radius $r$? For the boundary condition the normal derivative is the same as differentiation with respect to the radius $r$. Note also that you test function is not an eigenfunction either way, so Rayleigh only gives you an estimate, not the exact eigenvalue.
Comment: Where did you come up with $u''+\lambda u = 0$? Is this supposed to be the resulting $r$ equation after separation of variables?
Comment: I edited the question because I made a computation error in the integral. The $u"+ \lambda u$ is the the given DE on the circular region of radius 2. The trialfunction is given in the book, to use a trial function. The answer in the book gives a value of $\frac {12}{11}$ but I can't get to this answer.
Answer: \begin{equation}
J(\psi_0) \geq \lambda_1
\end{equation}
Where in this case $\psi_0$ is the trialfunction.
In order to understand the Rayleigh-quotient, now assume the same eigenvalue problem as the example above, but now by using the Rayleigh quotient method.
$$ \Delta u + \lambda u = 0$$
with associated boundary condition:
$$\frac {\partial u}{\partial r}  + 3u = 0$$
Now by using the Rayleigh quotient for $0 \leq r \leq 2$ and the trial function:
\begin{equation}
\label{eq:trial}
\psi_0(r)= \alpha - r
\end{equation}
where $\alpha$ is chosen so that $\psi_0(r)$ satisfies the boundary condition at $r=2$.
to find the lowest eigenvalue $\lambda_1$
The correct $\alpha$ that suits the boundary conditions,
$$ -1 + 3 (\alpha -2) = 0$$
Hence $\alpha = \frac{7}{3}$
An upper bound to $\lambda_1$ is given by the Rayleigh quotient \cite{courantvol22008methods},
\begin{equation}
J[\psi_0] = \frac {\mathfrak{D} [\psi_0]}{H[\psi_0]}
\end{equation}
where
\begin{equation}
\label{eq:quadratic}
\mathfrak {D} [\psi_0] = \int_{\Omega}|\bigtriangledown \psi_0|^2 dx +  \int_{\partial \Omega} \psi_0(2)^2 ds                                          \quad H[\psi_0] = \int_\Omega \psi_0^2 dx
\end{equation}
In the next chapter, a more detailled discussion will be given concerning these quadratic functionals.
(in polar form)
$$\bigtriangledown \psi =\underline e_r  \frac{\partial \psi}{\partial r} + \frac {1}{r} \underline e_{\theta} \frac{\partial \psi}{\partial \theta}$$
Where:
$$\underline e_r = \left( \begin{array}{c} \cos \theta \\ \sin \theta \end{array} \right), \quad   \underline e_\theta = \left( \begin{array}{c}- \sin \theta \\ \cos \theta \end{array} \right) $$
Thus $|\bigtriangledown \psi_0| = |\psi'_0(r)|=-1 $ and
$$\int_\Omega f(r)dx = \int_0^2 2\pi r f(r)dr$$
so that:$$J[\psi_0] = \frac {2 \pi \int_0^2 (r dr) +3 (\alpha - 2)^2 \int_{\partial \Omega} ds }{2 \pi \int_0^2 r(\alpha -r)^2dr}$$
(For readability, the $\alpha$ is left in.)
which leads to:
$$J[\psi_0] = \frac {2 \pi \int_0^2 (r dr) +3 (\alpha - 2)^2 \ 4\pi }{2 \pi \int_0^2 r(\alpha -r)^2dr}$$
$$J[\psi_0] = \frac {2 \pi \int_0^2 (r dr) + \frac{4\pi}{3} }{2 \pi \int_0^2 r(\alpha -r)^2dr}$$
These integrals can be evaluated as:
$$2 \pi \int_0^2 (r dr)= \frac {36 \pi}{9}$$
and
$$2 \pi\int_0^2 r(\alpha -r)^2dr = 2 \pi \big[\frac{1}{2} r^2 \alpha^2 - \frac{2}{3} \alpha r^3+ \frac{1}{4} r^4 \big]_{0}^{2} = 2\alpha^2 - \frac{16 \alpha}{3}+4 = \frac {44 \pi}{9}$$
Which would give $$J[\psi_0]= \frac{\frac {36}{9} + \frac {12}{9}} {\frac{44}{9}}  =  \frac{12}{11}$$
Hence an upper bound for $\lambda_1 = \frac {12}{11}$
Answer: First, the gradient in polar coordinates is $\frac{\partial}{\partial r} + \frac{1}{r}\frac{\partial}{\partial \theta}$, see for example here, but that doesn't change anything in your answer. Secondly you have a computation error after plugging in the value of $\alpha$, you should get $\frac{22}{9}$ for the integral. Integrating a positive function and getting a negative answer should raise some warning flags.
This gives a bound of $\frac{9}{11}$. Where does the $\frac{12}{11}$ you mention at the end come from?
Comment: The$ \frac{12}{11}$ is the correct answer as a a values for $\lambda$
Comment: I adjusted some of your remarks in my own work.
Comment: I can't figure out where I went wrong, my 'feeling' says: I have to put in the BC somewhere in the $D[\Psi]$


configuring bind to serve a default IP for DNS queries

Question: I'm setting up a meeting and I'd like to have the computers here (which are for accessing the meeting website only) blocked from accessing the public Internet.
I'd like to set up bind to return the same IP for ALL DNS queries - no passing upstream, no "not found". Is this possible?
Answer: To do this I believe you would create a master zone named "." in your named.conf (comment out the default "." zone with the hints information).  Then, create a zone file which contains a series of wildcard records for the IP that you want to have everyone directed to.
If other people will be connecting their own computers to this network for the meeting, then keep in mind that some people will use their own DNS settings (OpenDNS, Google Public DNS, etc.) instead of the DNS server issued by DHCP, so unless you're blocking DNS at the firewall there is still a way around it.  An HTTP proxy server at your routing point might be a better solution if that is the case.
Comment: Thanks! People with their own computers are welcome to surf, we just want to ensure the public terminals aren't taken up with folks checking webmail. This'll work nicely. :-)
Comment: In that case you might also consider running the web browser with a kiosk plug-in which limits what they can do with the computer.  Webconverger.org has a free Debian LiveCD you can customize to go to a specific URL and disable the address bar, etc.  This gets people to the web site and also locks the system down so they can't use the computer for anything else.


Is there any way to remove cross symbol from input fields in IE browser?

Question: Whenever I enter something to the input box in IE browser, a cross symbol appears at the other end. I am using CSS to add card image to display card type using jquery.addClass at the same place where the cross symbol appears and the card image overlaps with the cross symbol. Please let me know if there is any way I can remove the cross symbol.
Comment: can you please show us the demo or provide any jsfiddle?
Answer: Sure, this works in IE10 and above, I haven't tried other browsers..
<code>.someinput::-ms-clear {
   display: none;
}
</code>
Or if you want to remove the padding as well:
<code>.someinput::-ms-clear {
   width : 0;
   height: 0;
}
</code>
Comment: Thank you Robin. This works.
Comment: @abhiagNitk In that case, would you kindly mark my response as the solutions? Thanks.


Consulta Simples Nacional Optantes (por CNPJ) - C#

Question: Estou implementando em C# uma Consulta de Empresa Optante pelo Regime Tributário Simples Nacional através deste link http://www8.receita.fazenda.gov.br/SimplesNacional/Aplicacoes/ATBHE/ConsultaOptantes.app/ConsultarOpcao.aspx
Já possuo implementado uma outra consulta semelhante (busca os dados cadastrais do CNPJ informado) e tentei me basear na mesma estrutura de busca... porém quando implemento o POST na URL citada um erro 404 (não localizado) é retornado...
Não conheço muito dos protocolos WEB então será que alguém poderia me ajudar?
Tenho problemas com o Cookie e também com o envio dos dados para consulta... Estou testando com uma URL da Receita que me retorna o CAPTCHA, mas devo ter problemas com isto também...
<code>    public class ConsultaCNPJSimplesNacional
{

    //public static int c=0;
    private readonly CookieContainer _cookies = new CookieContainer();
    private const String urlBaseReceitaFederalCNPJ = "http://www8.receita.fazenda.gov.br/SimplesNacional/Aplicacoes/ATBHE/ConsultaOptantes.app/";
    //private const String paginaValidacaoCNPJ = "ConsultarOpcao.aspx";
    private const String paginaPrincipalCNPJ = "ConsultarOpcao.aspx";
    private const String paginaCaptchaCNPJ = "http://www.receita.fazenda.gov.br/scripts/srf/intercepta/captcha.aspx?opt=image";

    public Bitmap GetCaptchaCNPJ()
    {
        String htmlResult;
        Bitmap retorno;

        using (var wc = new CookieAwareWebClient())
        {
            wc.SetCookieContainer(_cookies);
            wc.Headers[HttpRequestHeader.UserAgent] = "Mozilla/4.0 (compatible; Synapse)";
            wc.Headers[HttpRequestHeader.KeepAlive] = "300";
            htmlResult = wc.DownloadString(urlBaseReceitaFederalCNPJ + paginaPrincipalCNPJ);
        }
        if (htmlResult.Length > 0)
        {
            var wc2 = new CookieAwareWebClient();
            wc2.SetCookieContainer(_cookies);
            wc2.Headers[HttpRequestHeader.UserAgent] = "Mozilla/4.0 (compatible; Synapse)";
            wc2.Headers[HttpRequestHeader.KeepAlive] = "300";

            retorno = new System.Drawing.Bitmap(new System.IO.MemoryStream(wc2.DownloadData(paginaCaptchaCNPJ)));

            return retorno;

        }
        return null;
    }

    public String ConsultaCNPJ(string aCNPJ, string aCaptcha)
    {
        var request = (HttpWebRequest)WebRequest.Create(urlBaseReceitaFederalCNPJ + paginaPrincipalCNPJ);
        request.ProtocolVersion = HttpVersion.Version10;
        request.CookieContainer = _cookies;
        request.Method = "POST";

        string postData = "";
        postData = string.Format("{0}__EVENTTARGET={1}&", postData, "null");
        postData = string.Format("{0}__EVENTARGUMENT={1}&", postData, "null");
        postData = string.Format("{0}__VIEWSTATE={1}&", postData, "/wEPDwUKLTI4MDEzODYyMg9kFgJmD2QWAgIDD2QWAgICD2QWAgIDD2QWBAIBD2QWAgIDDw8WAh4RQ29udHJvbFRvVmFsaWRhdGUFEjYzNTg5NjgxMjAzOTYzMjk2MmRkAgMPDxYCHgdWaXNpYmxlaGQWCAITD2QWBAIDDzwrABEBARAWABYAFgBkAgcPPCsAEQEBEBYAFgAWAGQCGQ9kFgICAw88KwARAQEQFgAWABYAZAIfD2QWAgIDDzwrABEBARAWABYAFgBkAiUPZBYCAgMPPCsAEQEBEBYAFgAWAGQYBQU7Y3RsMDAkQ29udGVudFBsYWNlSG9sZGVyQ29udGV1ZG8kZ3JkUGVyaW9kb3NBbnRlcmlvcmVzU0lNRUkPZ2QFOmN0bDAwJENvbnRlbnRQbGFjZUhvbGRlckNvbnRldWRvJGdyZEFnZW5kYW1lbnRvc09wY2FvU2luYWMPZ2QFOWN0bDAwJENvbnRlbnRQbGFjZUhvbGRlckNvbnRldWRvJEdyaWRWaWV3T3Bjb2VzQW50ZXJpb3Jlcw9nZAUyY3RsMDAkQ29udGVudFBsYWNlSG9sZGVyQ29udGV1ZG8kZ3JkRXZlbnRvc0Z1dHVyb3MPZ2QFN2N0bDAwJENvbnRlbnRQbGFjZUhvbGRlckNvbnRldWRvJGdyZEV2ZW50b3NGdXR1cm9zU2ltZWkPZ2RVew7KgLxLzgzTZSEUz2W7HMrmi/hfWwILEBUqE+RWxg==");
        postData = string.Format("{0}__EVENTVALIDATION={1}&", postData, "/wEWBgLq/eloAqye/fEBAubugugBArTc7JALAoj16KgKAsPCk6ABUmPOXmbrPKdGe79cSZ5xd7+tpvEhZPqniHtlSzKz9g0=");
        postData = string.Format("{0}ctl00$ContentPlaceHolderConteudo$635896812039632962={1}&", postData, new Regex(@"[^\d]").Replace(aCNPJ, string.Empty));
        postData = string.Format("{0}ctl00$ContentPlaceHolderConteudo$HiddenField1={1}&", postData, "635896812039632962");
        postData = string.Format("{0}ctl00$ContentPlaceHolderConteudo$hddServidorCaptcha={1}&", postData, "pro");
        postData = string.Format("{0}ctl00$ContentPlaceHolderConteudo$txtTexto_captcha_serpro_gov_br={1}&", postData, aCaptcha);
        postData = string.Format("{0}ctl00$ContentPlaceHolderConteudo$btnConfirmar={1}&", postData, "Consultar");

        byte[] byteArray = Encoding.UTF8.GetBytes(postData);
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = byteArray.Length;

        Stream dataStream = request.GetRequestStream();
        dataStream.Write(byteArray, 0, byteArray.Length);
        dataStream.Close();

        WebResponse response = request.GetResponse();
        StreamReader stHtml = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("ISO-8859-1"));
        String retorno = stHtml.ReadToEnd();

        if (retorno.Contains("Verifique se o mesmo foi digitado corretamente"))
            throw new System.InvalidOperationException("O número do CNPJ não foi digitado corretamente");
        if (retorno.Contains("Erro na Consulta"))
            throw new System.InvalidOperationException("Os caracteres digitados não correspondem com a imagem");
        if (retorno.Contains("Esta página tem como objetivo permitir"))
            throw new System.InvalidOperationException("Erro não mapeado...");

        return retorno;
    }
}
</code>
Alguém por ai já implementou ou pode me ajudar a implementar este tipo de Consulta?
Answer: Depois de muito quebrar a cabeça e obter ajuda de um colega de profissão na área WEB eu consegui reformular os métodos e obter o resultado desejado...
Abaixo código detalhado e funcional...!
PS.: Estava falhando na hora de enviar os parametros e também na passagem do cookie contendo o TOKEN do Captcha...
Que sirva de exemplo pra outros muitos que precisaram e desistiram no meio do caminho...
<code>public class ConsultaCNPJSimplesNacional
{
    private string viewState, eventValidation, hiddenField1, servidorCaptcha, stringCookies, token = string.Empty, img = string.Empty;

    private const String urlBaseReceitaFederalCNPJ = "http://www8.receita.fazenda.gov.br/SimplesNacional/Aplicacoes/ATBHE/ConsultaOptantes.app/ConsultarOpcao.aspx";
    private const String paginaCaptchaCNPJ = "http://www8.receita.fazenda.gov.br/SimplesNacional/Aplicacoes/ATBHE/ConsultaOptantes.app/Captcha/Inicializa.ashx";

    /// <summary>
    /// Captura Captcha e também armazena valores de alguns parametros a serem enviados na Consulta
    /// </summary>
    /// <returns>Retorna BITMAP contendo imagem Captcha</returns>
    public Bitmap GetCaptchaCNPJ()
    {
        String htmlResult = string.Empty;
        Bitmap retorno = null;

        try
        {
            WebClient wc = new WebClient();

            wc.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");

            //requisita valores das variaveis para armazenamento
            htmlResult = wc.DownloadString(urlBaseReceitaFederalCNPJ);

            if (htmlResult.Length > 0)
            {
                var doc = new HtmlDocument();
                doc.LoadHtml(htmlResult);

                servidorCaptcha = doc.DocumentNode.Descendants("input")
                                .First(i => i.Attributes["id"] != null &&
                                            i.Attributes["id"].Value == "hddServidorCaptcha")
                                .Attributes["value"].Value;

                viewState = doc.DocumentNode.Descendants("input")
                                .First(i => i.Attributes["id"] != null &&
                                            i.Attributes["id"].Value == "__VIEWSTATE")
                                .Attributes["value"].Value;

                eventValidation = doc.DocumentNode.Descendants("input")
                                .First(i => i.Attributes["id"] != null &&
                                            i.Attributes["id"].Value == "__EVENTVALIDATION")
                                .Attributes["value"].Value;

                hiddenField1 = doc.DocumentNode.Descendants("input")
                                .First(i => i.Attributes["id"] != null &&
                                            i.Attributes["id"].Value == "ctl00_ContentPlaceHolderConteudo_HiddenField1")
                                .Attributes["value"].Value;

                //requisita Captcha armazenando TOKEN a ser utilizado na Consulta
                htmlResult = wc.DownloadString(paginaCaptchaCNPJ);

                if (htmlResult.Length > 0)
                {
                    stringCookies = htmlResult;

                    string[] x = Regex.Split(htmlResult, "\",\"");

                    foreach (string s in x)
                    {
                        if (s.IndexOf("Token") >= 0)
                            token = new Regex(@"[^\d]").Replace(s, string.Empty);
                        else if (s.IndexOf("Dados") >= 0)
                            img = s.Substring(8);
                    }

                    if (img.Length > 0)
                    {
                        byte[] imageBytes = Convert.FromBase64String(img);
                        MemoryStream ms = new MemoryStream(imageBytes);

                        Image image = Image.FromStream(ms, true, true);

                        retorno = (Bitmap)image;
                    }
                }
            }

        }
        catch (Exception)
        {
            throw;
        }

        return retorno;

    }

    /// <summary>
    /// Faz Consulta do CNPJ informado pelo Usuário, verificando se o mesmo é Optante pelo Simples Nacional
    /// </summary>
    /// <param name="aCNPJ">CNPJ sem traços</param>
    /// <param name="aCaptcha">Conteúdo Captcha informado</param>
    /// <returns>Retorna Dados Cadastrais CNPJ e Regime Tributário Optado</returns>
    public List<KeyValuePair<string, string>> ConsultaCNPJ(string aCNPJ, string aCaptcha)
    {
        try
        {
            using (WebClient wc = new WebClient())
            {
                wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
                wc.Headers[HttpRequestHeader.Cookie] = "captcha_token=" + token;
                wc.Headers[HttpRequestHeader.Accept] = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
                wc.Headers[HttpRequestHeader.AcceptLanguage] = "pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4";
                wc.Headers[HttpRequestHeader.AcceptEncoding] = "gzip, deflate";
                wc.Headers[HttpRequestHeader.Host] = "www8.receita.fazenda.gov.br";
                wc.Headers[HttpRequestHeader.UserAgent] = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.152 Safari/537.36";

                byte[] response =
                wc.UploadValues(urlBaseReceitaFederalCNPJ, new NameValueCollection()
                {
                    { "__EVENTTARGET", "null" }, //conteudo estático, sempre nulo
                    { "__EVENTARGUMENT", "null" }, //conteudo estático, sempre nulo
                    { "__VIEWSTATE", viewState }, //conteudo armazenado durante consulta Captcha
                    { "__EVENTVALIDATION", eventValidation },//conteudo armazenado durante consulta Captcha
                    { string.Format("ctl00$ContentPlaceHolderConteudo${0}", hiddenField1), new Regex(@"[^\d]").Replace(aCNPJ, string.Empty) }, //identifica parametro CNPJ adicionando à propriedade NAME o conteudo dinâmico da varíavel armazenada durante captura Captcha
                    { "ctl00$ContentPlaceHolderConteudo$HiddenField1", hiddenField1 }, //conteudo armazenado durante consulta Captcha
                    { "ctl00$ContentPlaceHolderConteudo$hddServidorCaptcha", servidorCaptcha }, //conteudo armazenado durante consulta Captcha
                    { "ctl00$ContentPlaceHolderConteudo$txtTexto_captcha_serpro_gov_br", aCaptcha }, //Captcha digitado
                    { "ctl00$ContentPlaceHolderConteudo$btnConfirmar", "Consultar" } //conteúdo estático de consulta
                });

                string result = System.Text.Encoding.UTF8.GetString(response);

                //trata e retorna valores encontrados
                return TratarRetorno(result);
            }
        }
        catch (Exception)
        {
            throw;
        }
    }

    /// <summary>
    /// Captura os dados de Retorno do Site da Receita Federal
    /// </summary>
    /// <param name="resultado">STRING contendo Retorno da Consulta Realizada na Receita Federal</param>
    /// <returns>Retorna lista contendo Dados Cadastrais e Situação do CNPJ na Receita Federal</returns>
    private static List<KeyValuePair<string, string>> TratarRetorno(string resultado)
    {
        List<KeyValuePair<string, string>> retorno = new List<KeyValuePair<string, string>>();

        try
        {
            var doc = new HtmlDocument();
            doc.LoadHtml(resultado);

            #region ... Validação CAPTCHA ERROR...
            var itemError = (HtmlAgilityPack.HtmlNodeCollection)doc.DocumentNode.SelectNodes("//div[@id='ctl00_ContentPlaceHolderConteudo_pnlConsulta']");

            if (itemError != null)
            {
                foreach (HtmlAgilityPack.HtmlNode node in itemError)
                {
                    if (node.SelectNodes("//span[@id='ctl00_ContentPlaceHolderConteudo_lblErroCaptcha']") != null)
                        throw new Exception("Caracteres Captcha Inválidos.");
                }
            }
            #endregion

            #region ...Dados Empresa...
            var dadosEmpresa = (HtmlAgilityPack.HtmlNodeCollection)doc.DocumentNode.SelectNodes("//div[@id='ctl00_ContentPlaceHolderConteudo_Panel1']");

            if (dadosEmpresa != null)
            {
                foreach (HtmlAgilityPack.HtmlNode node in dadosEmpresa)
                {
                    foreach (HtmlAgilityPack.HtmlNode node2 in node.SelectNodes("//span[@id]"))
                    {
                        string attributeValue = node2.GetAttributeValue("id", "");
                        if (attributeValue == "ctl00_ContentPlaceHolderConteudo_lblCNPJ")
                        {
                            retorno.Add(new KeyValuePair<string, string>("CNPJ", node2.InnerText));
                        }
                        else if (attributeValue == "ctl00_ContentPlaceHolderConteudo_lblNomeEmpresa")
                        {
                            retorno.Add(new KeyValuePair<string, string>("EMPRESA", node2.InnerText));
                        }
                    }
                }

            }
            #endregion

            #region ...Situação do CNPJ...
            var dadosRetorno = (HtmlAgilityPack.HtmlNodeCollection)doc.DocumentNode.SelectNodes("//div[@id='ctl00_ContentPlaceHolderConteudo_Panel2']");

            if (dadosRetorno != null)
            {
                foreach (HtmlAgilityPack.HtmlNode node in dadosRetorno)
                {
                    foreach (HtmlAgilityPack.HtmlNode node2 in node.SelectNodes("//span[@id]"))
                    {
                        string attributeValue = node2.GetAttributeValue("id", "");
                        if (attributeValue == "ctl00_ContentPlaceHolderConteudo_lblSituacaoSimples")
                        {
                            retorno.Add(new KeyValuePair<string, string>("SITUAÇÃO", node2.InnerText));
                        }
                    }
                }
            }
            #endregion
        }
        catch (Exception)
        {
            throw;
        }

        return retorno;
    }
}
</code>


Got "Uncaught ReferenceError: exports is not defined" when including a simple Component JS file in my HTML file (without Node.js)

Question: What I want to do is actually really simple, BUT I want do to it without using Node.js.
Juste a simple HTML file with a Component in a separate .js file.
Here is the HTML file :
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>React Local</title>

You can see that I import my component file with type="text/babel" data-type="module"
Here is the TestComponent.js file :
// Create a ES6 class component
class TestComponent extends React.Component {
    render() {
        return (
        HELLO
      );
      }
    }

export default TestComponent;

But the .js file is not loaded, and in the Chrome console I see :
VM99:3 Uncaught ReferenceError: exports is not defined
    at <anonymous>:3:23
    at run (babel.js:61531:11)
    at check (babel.js:61597:10)
    at result.<computed>._extends.content (babel.js:61624:10)
    at xhr.onreadystatechange (babel.js:61549:10)

I did not except that almost all React tutorials are related with Node.js.
I have a PHP application, and I only need React for small simple stuff, don't want to add nodeJS just for that.
Any clue ?
Thanks
Answer: OK, I found out. Just remove the line : export default TestComponent;
No need to "export" the component in that case.


Delete only referenced Nodes

Question:
I have created a report of each students with their paid fee invoices.
Now I would like to delete the invoices only.
Please help me out from this.
Comment: Do you want to delete all invoices? Invoices of a particular student?
Comment: Yes Mr. AjitS.. only Invoices... Not the Student..
Students data I need for the next academic year....
Comment: Just for the sake of clarification : I assume Student is a content type, so is Invoice. Right? And how are you referring invoice from student? Using a node reference or an entity reference?
Comment: Through Node references only
Comment: Now the actual problem is when I delete the invoices using VBO it delete the student also... :(
Comment: Answered. Let me know if you have any issues.
Answer: This could be solved by creating a simple view with VBO. Try this steps:

Create a view of content, without any filter criteria.
Add a relationship to the view of the reference field in the 'student' content type. Say 'field_invoice'.
Add a filter to the view of "content type", select 'invoice'. Use the relationship in the filter that was created in step 2.
Add a filter of "content title". Expose this filter. Use the relationship in this filter too.
Add a VBO field of type  "Bulk operations: Content (Content)". Select 'delete' from the operations.

From this view, you should be able to filter by name of any student. It will list the invoices. And using VBO, you should be able to delete them.
Comment: ohhh My God.. at last I got the solutions thank you AjitS

Delete only referenced Nodes


Why can I not simply add fractions statistics?

Question: This is a really elementary question for kids but I have difficulties at the moment to find my mistake. I stepped over the problem in my statistics course at which we use bayes theorem and it appears when I have to give the probability of a certain event:
Say, I ask 100 people, 52 female and 48 male, what kind of superpower they would like to have.
26 male persons picked "flying" and 12 female persons picked flying. What is the probability that someone is male, given that he picked "flying" ? If you use bayes theorem you come very easily to the result of about ~68% :
$ p(male|fly)=\frac{p(fly|male)*p(male)}{p(fly)}$
My question belongs to $p(fly)$ : The probability  $p(fly)$ is $38/100$.Because 100 people were asked and in sum 38 of them picked "flying". But I calculated in my first attempt : "26 out of 48 male persons picked flying and 12 out of 52 female persons picked flying  $\implies \frac{26}{48}+\frac{12}{52} = \frac{77}{100}$
What is the error of thinking that I did here  ? Because I can obviously see that in total 38 of 100 persons picked flying and 77/100 is wrong but I don't understand if 26 of 48 and 12 of 52 picked flying,why adding those does not give me the correct result.
To make the question more clear :
Why do we do in this case :
$\frac{26+12}{48+52}$ and not $\frac{26}{48}+\frac{12}{52}$,, while having $\frac{26}{48}$ and $\frac{12}{52}$ flying people.
Or another way would be : I have 100 sweets, 48 chocolate taste, 52strawberry taste. I eat 12 strawberry ones and 26 chocolate ones. Why can I not get the total of eaten sweets by (26 out of 48) + (12 out of 52) but by (26+12) out of (100=52+48).
Answer: You forgot to multiply the probabilities with $\frac{48}{100}$ and $\frac{52}{100}$ respective depending on whether we have a male or female. If you do that, you get the correct result because you add P(male and fly) and P(female and fly)
Comment: You just have to split $P(fly)$ into the two cases $P(male\ and\ fly)$ and $P(female\ and\ fly)$ which cannot occur both at the same time. Therefore those probabilities simply add. But we have $P(male\ and\ fly) = P(male) \cdot P(fly|male)$ and analogue for female. You have to add the products and not only the conditiona probabilities. Perhaps you understand the issue better by studying Simpson's paradox which is about forbidden aggregation of observation material.
Comment: Yes now it's obvious - thanks for this one ! :)
Comment: Could you be a little more precise ? Because I am not exactly sure, what I shall calculate. I edited another example at the end, which might make my question more clear
Answer: Let's take other numbers: All $52$ females and all $48$ males said they wanted "flying". Your calculation would find that
$$\frac{52}{52} + \frac{48}{48}=2 = 200\%$$
of the asked people wanted to fly.
Your main error is that relative values (like $\frac{26}{48}$) only have an absolute  meaning if you attach them to the value they reference (in this case the $48$ males that got asked).
Adding relative values that belong to different reference numbers makes no sense.
Answer: If you look at your distribution of the 100 guys (you can do a $2\times 2$ table for that purpose) you see that

26 guys are Male and Flying
22 guys are Male and NOT Flying
12 guys are Female and Flying
40 guys are Female and NOT flying,

so, given a guy is Flying ($26+12=38$ possible choices) only 26 are male.
Thus the result is $\frac{26}{38}=\frac{13}{19}\approx 68\%$
Comment: That makes the result more clear, but I am not sure, if this answers my question


Maven dependecy versions

Question: I am working on an old Struts 1 application. I have added Quartz as I need to schedule a job to run using this tutorial.
I do however now get a run time error, where it is complaining about the version of slf4j I am using.

10:15:07,813 ERROR [stderr] (MSC service thread 1-13) SLF4J: slf4j-api
  1.6.x (or later) is incompatible with this binding. 10:15:07,814 ERROR [stderr] (MSC service thread 1-13) SLF4J: Your binding is version
  1.5.5 or earlier. 10:15:07,814 ERROR [stderr] (MSC service thread 1-13) SLF4J: Upgrade your binding to version 1.6.x. 10:15:07,814
  SEVERE [org.apache.struts.action.ActionServlet] (MSC service thread
  1-13) Unable to initialize Struts ActionServlet due to an unexpected
  exception or error thrown, so marking the servlet as unavailable.
  Most likely, this is due to an incorrect or missing library
  dependency.: java.lang.NoSuchMethodError:
  org.slf4j.impl.StaticLoggerBinder.getSingleton()Lorg/slf4j/impl/StaticLoggerBinder;
    at org.slf4j.LoggerFactory.bind(LoggerFactory.java:129)
  [slf4j-api-1.7.7.jar:]    at
  org.slf4j.LoggerFactory.performInitialization(LoggerFactory.java:108)
  [slf4j-api-1.7.7.jar:]    at
  org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:302)
  [slf4j-api-1.7.7.jar:]    at
  org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:276)
  [slf4j-api-1.7.7.jar:]    at
  org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:288)
  [slf4j-api-1.7.7.jar:]    at
  org.quartz.impl.triggers.CronTriggerImpl.(CronTriggerImpl.java:67)
  [quartz-2.3.2.jar:]   at
  org.quartz.CronScheduleBuilder.build(CronScheduleBuilder.java:84)
  [quartz-2.3.2.jar:]   at
  org.quartz.TriggerBuilder.build(TriggerBuilder.java:101)
  [quartz-2.3.2.jar:]   at
  com.travellinck.plugin.QuartzPlugin.init(QuartzPlugin.java:33)
  [classes:]    at
  org.apache.struts.action.ActionServlet.initModulePlugIns(ActionServlet.java:884)
  [struts-core-1.4.1-ee6.jar:]  at
  org.apache.struts.action.ActionServlet.init(ActionServlet.java:352)
  [struts-core-1.4.1-ee6.jar:]  at
  javax.servlet.GenericServlet.init(GenericServlet.java:242)
  [jboss-servlet-api_3.0_spec-1.0.0.Final.jar:1.0.0.Final]  at
  org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1202)
  [jbossweb-7.0.1.Final.jar:7.0.2.Final]    at
  org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1102)
  [jbossweb-7.0.1.Final.jar:7.0.2.Final]    at
  org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:3631)
  [jbossweb-7.0.1.Final.jar:7.0.2.Final]    at
  org.apache.catalina.core.StandardContext.start(StandardContext.java:3844)
  [jbossweb-7.0.1.Final.jar:7.0.2.Final]    at
  org.jboss.as.web.deployment.WebDeploymentService.start(WebDeploymentService.java:70)
  [jboss-as-web-7.0.2.Final.jar:7.0.2.Final]    at
  org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1824)
    at
  org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1759)
    at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
  [:1.7.0_80]   at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
  [:1.7.0_80]   at java.lang.Thread.run(Thread.java:745) [:1.7.0_80]

My pom file already had this profile using slf4j-log4j12 version 1.5.8:
    <profile>
        <id>jspCompile</id>
        <activation>

            <activeByDefault>false</activeByDefault>
        </activation>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.codehaus.mojo.jspc</groupId>
                    <artifactId>jspc-maven-plugin</artifactId>
                    <executions>
                        <execution>
                            <goals>
                                <goal>compile</goal>
                            </goals>
                            <phase>compile</phase>
                        </execution>
                    </executions>
                    <configuration>
                        <includeInProject>false</includeInProject>
                        <source>1.5</source>
                        <target>1.5</target>
                    </configuration>

                    <dependencies>
                        <dependency>
                            <groupId>org.codehaus.mojo.jspc</groupId>
                            <artifactId>jspc-compiler-tomcat6</artifactId>
                            <version>2.0-alpha-3</version>
                        </dependency>
                        <dependency>
                            <groupId>org.slf4j</groupId>
                            <artifactId>slf4j-log4j12</artifactId>
                            <version>1.5.8</version>
                        </dependency>
                    </dependencies>
                </plugin>
            </plugins>
        </build>
    </profile>

I added the following dependency to my pom file:
    <dependency>
        <groupId>org.quartz-scheduler</groupId>
        <artifactId>quartz</artifactId>
        <version>1.7.2</version>
    </dependency>

I have tried changing the plugins dependency to 1.7.7.
                        <dependency>
                            <groupId>org.slf4j</groupId>
                            <artifactId>slf4j-log4j12</artifactId>
                            <version>1.7.7</version>
                        </dependency>
                    </dependencies>
                </plugin>

I have also tried adding the following dependencies outside the <profile>:
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.7</version>
</dependency>

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.7</version>
    <scope>test</scope>
</dependency>

But I still get the above error.
Question
How do I configure my dependencies so that I can get Quartz to work?
Thanks
Answer: Try the latest slf4j-log4j version and make sure there is only version of slf4j-log4j
Comment: Thanks for the answer, do you mean this? https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12/1.7.30

Maven dependecy versions


Django Python With Gspread: 'choices' must be an iterable containing (actual value, human readable name) tuples

Question: I am trying to do something that I have never seen done before with django, I am trying to make a model field(path_choices) that shows all of the unique path_names from my google sheet in a choice box so that the user can select one of them. However when I tried to make my choices CharField I am getting the error:

ERRORS:

dashboard.Robot.path_choices: (fields.E005) 'choices' must be an iterable containing (actual value, human readable name) tuples.

Right now the google sheet that I am trying to pull from with gspread only has two path-names, so if anybody has any idea on what is causing this problem or what I can do better with this, the help would be appreciated!
My Code (UPDATED CODE):
from django.db import models

class Robot(models.Model):
    name = models.CharField(max_length=100)
    status_choices = [('driving', 'driving'), ('waiting', 'waiting'), ('stuck', 'stuck')]
    status = models.CharField(choices=status_choices, max_length=7, default='waiting')
    path_choices = models.CharField(max_length=255)

My Form:
from django import forms
from django import forms
from .models import Robot
import gspread
from oauth2client.service_account import ServiceAccountCredentials

class RobotForm(forms.ModelForm):
    def _generate_choices():
        scope = ["REDACTED",'REDACTED',"REDACTED","REDACTED"]
        creds = ServiceAccountCredentials.from_json_keyfile_name("dashboard/Files/creds.json", scope)
        client = gspread.authorize(creds)
        sheet = client.open("tutorial").sheet1
        path_name_fetch =  sheet.col_values(1)
        path_names = []
        temp_list = []
        path_options = []
        for i in path_name_fetch:
            if i not in path_names:
                path_names.append(i)
        for path_name_options in path_names:
            temp_list.append(f'{path_name_options}')
            temp_list.append(f'{path_name_options}')
            path_options.append(tuple(temp_list))

    path_choices = forms.ChoiceField(choices=_generate_choices())
    class Meta:
        model = Robot
        fields = {'path_choices'}

Comment: @Garberchov, that is not the problem because I have tested this code in just a straight python file and it has worked without a problem.
Comment: Are you sure that the problem isn't from gspread(perhaps not fetching properly etc)?
Answer: What you're trying to do may not be in line with the intended use of Choices. Whenever the possibilities of a Choice change at the Model level, new migrations must be made.
Your implementation of Choice for Robot.status is static and in line with the example in the Django documentation.
If instead you wanted to use a dynamic Choice for your path_choices that is retrieved from Google Sheets, I would recommend doing this in the ModelForm using a ChoiceField.
According to the documentation, the available choices can come from a callable, which would be your path_options wrapped in a function. path_options should then become a CharField without choices, since you manage those in the submission, rather than at the model level.
Models.py
class Robot(models.Model):
    ...
    path_choices = models.CharField(max_length=255)

ModelForms.py
class RobotForm(ModelForm):
      def _generate_choices():
            # Query GSpread
            choices = [('choice','choice'), ...]
            return choices

      path_choices = forms.ChoiceField(choices=_generate_choices())
      class Meta:
            model = Robot
            fields = ['path_choices', ...]

Comment: I am really confused by what you mean in this, in how `path_options` would become wrapped in a function but also become a `char_field` Do you have an example of this besides that documentation as that example doesn't seem as well sell suited to this use?
Comment: A `CharField` does not have any restrictions on the content that is saved aside from being a string of characters, you limit the inputs by defining `choices`. By moving the logic away from the model, and into the modelform, you can dynamically change the choices that are submitted to the path_options.
Comment: I am still confused as I am already using a `CharField`, is there a documentation or example that you can show that shows this more clearly?
Comment: There is no drop down box on the image, I don't know what I did wrong? https://imgur.com/a/ihPqKLZ
Comment: I've updated my answer with examples. I have limited experience with ModelForms, but this is the gist of what I mean. The key difference is that a ChoiceField in a Form (and ModelForm) can be dynamic: "If the argument is a callable, it is **evaluated each time the field's form is initialized**, in addition to during rendering. Defaults to an empty list."
Comment: Thanks a bunch, that makes much more sense as I didn't sink in that the model form would be a separate file. Will give it a shot
Comment: I assumed you were already using ModelForms to expose your Model to the user through a web interface, either way I hope this helps and do let me know if it doesn't work.
Comment: It didn't work, I got the error `TypeError: 'NoneType' object is not iterable`, I think it is a problem with the form but I don't know what I did wrong.
Comment: This is probably because the underlying model has a `CharField` instead of a `ChoiceField`. Have you tried explicitly defining the HTML Widget that should be created in the ModelForm? `path_choices = forms.ChoiceField(widget=forms.Select, choices=_generate_choices())`


How to change pop view controller animation on back button?

Question: I am pushing my view controller with the following statement :
<code>[[self navigationController] pushViewController:self.customViewController animatedWithTransition:UIViewAnimationTransitionFlipFromLeft];
</code>
Now  when I am pressing the back button I want to animate it with the uiviewanimationtransitionflipfromright .
like
<code>[self.navigationController popViewControllerAnimatedWithTransition:UIViewAnimationTransitionFlipFromLeft];
</code>
How Can I do so ?
Thanks
Answer: This helps you to animating the view in back button.
<code>[UIView  beginAnimations:nil context:NULL];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationDuration:0.75];
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:self.navigationController.view cache:NO];
[UIView commitAnimations];

[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDelay:0.375];
[self.navigationController popViewControllerAnimated:NO];
[UIView commitAnimations];
</code>
Answer: For Push:
<code>MainView *nextView = [[MainView alloc] init];
[UIView animateWithDuration:0.75
                     animations:^{
                         [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
                         [self.navigationController pushViewController:nextView animated:NO];
                         [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:self.navigationController.view cache:NO];
                     }];
</code>
For Pop:
<code>[UIView animateWithDuration:0.75
                     animations:^{
                         [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
                         [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:self.navigationController.view cache:NO];
                     }];
[self.navigationController popViewControllerAnimated:NO];
</code>
https://stackoverflow.com/a/5889757/1915820
Answer: See here for doing custom back anim:
Prevent the animation when clicking "Back" button in a navigation bar?


rails assest:precomplie , when load file not correct

Question: I have web RoR, I ran assets:precomplie, and i got file
**/application-dfaaca6b25e0d101d80f81c5cb194f6d39d331886613c0a392283b01b9911cb0.css**

but my web was loaded another file
**application.self-a429e1a197d1ad3e5a775f50a60fd344db3ba490db151ab8c7494a78cba792a2.css**.

i don't know reason. Anybody, can help me? Thanks a lot
Answer: I got the same questions. then finally I find the answer:
when you process assets:precomplie, you must specify the env as you run rails, because in different enviroments, the assets version is not same!

when you run rails in development env as rails s, you should process as rake assets:precomplie or assets:precomplie RAILS_ENV=development
when you run rails in production env as rails s -e p, you should process as rake assets:precomplie RAILS_ENV=production

hope this helps!
Comment: Thanks your support. assets:precomplie with RAILS_ENV is ok, but i don't know why all files added ".self" (application.self-a429e1a197d1ad3e5a775f50a60fd344db3ba490db151ab8c7494a78cba792a2.css).
Answer: Solution:
Deploy your application again
if still not solved

SSH into the system
delete the file your_app/manifest_backup
$ bundle exec rake assets:clear
$ bundle exec rake assets:precompile RAILS_ENV=production
restart the webserver ( for Nginx /etc/init.d/nginx restart or $ sudo service nginx restart )
if still not solved deploy your app again

For more info see my blog
https://cbabhusal.wordpress.com/2015/07/20/ruby-on-rails-production-staging-when-asset-path-is-outdated/
Comment: https://cbabhusal.wordpress.com/2015/07/20/ruby-on-rails-production-staging-when-asset-path-is-outdated/ -> that's great. Thank you alot :-x
Comment: @thienhv if this works, don't forget to up-vote to notify future visitors :)


Cannot login as root to centos server

Question: I used to login as ssh root@servip with a password authentication into my CentOS 6 server.
I am not sure if what I have done has caused this, but while trying to get over my problem of accessing webmin remotely I followed the following tutorial until I reached:
adding auth required pam_google_authenticator.so into /etc/pam.d/sshd. Then by mistake, I have closed the ssh session. When I tried to login in back with the usual password, I get: Permission denied, please try again error. How can I get over this problem?
I don't have a physical access to the server.
Answer: Switch to the second ssh session that you should have opened, and fix it. The howto did explicitly warn you to do this, exactly because of the possibility of something like this happening.
At this point the only way you can recover is via the system console. If you don't have remote access to the console, e.g. with DRAC, iLO, IPMI, etc., you will have to physically visit the server.
Comment: Either undo your changes, or finish setting it up. Your choice.
Comment: and what exactly needs to be done physically to restore access, did adding pam_google_authenticator.so to the /etc/pam.d/sshd cause this? thanks
Comment: Ok, I have physical access to the server now, what do I need to do regain the access to the server, just remove auth required pam_google_authenticator.so from /etc/pam.d/sshd (I stopped there when following the tutorial) so I can regain ssh access? that's all ?
Comment: See my previous comment.

Cannot login as root to centos server


Setting commerce sales price with views

Question: I am trying to set up a sale price on certain products on a drupal site, however from the project page of commerce_saleprice there is this patch https://drupal.org/files/commerce-views_precalculated_price-1020050-5.patch that should be applied but am stack because i dont know to which module this has to be applied as i tried applying it to commerce_saleprice and it fails.
My requirement is to put some products on sale and then call them in a view... any insight on this, i already have price savings formatters installed.
Answer: From the looks of the patch file it needs to be applied to commerce_price -
cd to /sites/all/modules/commerce (or wherever you have the commerce module) and a command like this should do it:
<code>patch -p1 < /path/to/file.patch
</code>
And then write down what you've done so you don't forget next time you update the commerce module ;)
Comment: When you see this error, it is almost always because you're using a patch for the wrong version of the code you're patching. There are a few ways to work around this:
1. Get the new version of the module and apply the patch
2. apply it manually
Comment: Well thanks for the tip i actually have added the patch at sites/all/modules/commerce the its seems not to be applying properly

i get the following output
1 out of 1 hunk FAILED -- saving rejects to file modules/price/commerce_price.info.rej

Setting commerce sales price with views


Integração Spring MVC e catraca

Question: Estou desenvolvendo um sistema para o restaurante universitário da minha universidade com Spring MVC.

Preciso conectar o sistema com uma catraca da marca TopData, que controla o acesso dos clientes ao restaurante. Como nunca enfrentei tal problema, gostaria da opinião de vocês sobre qual caminho devo seguir!

Atualmente, estou pensando em criar uma aplicação Java Desktop para gerenciar a comunicação da catraca com o Sistema Web.
PS: a catraca tem saída de rede.
Comment: A fabricante da catraca certamente vai ter um manual descrevendo a API que você deve usar — e, caso você estivesse usando o modelo de conexão serial, provavelmente um _driver_ para se comunicar com o equipamento, também.
Answer:
Modelo Catraca Box - com comunicação serial padrões RS232 e RS485.
RS232: cabo com até 100m de comprimento RS485: cabo com até 1.500m de comprimento, permite a conexão de até 32 catracas ou Inners à mesma porta serial (necessário conversor RS232/RS485 conectado ao computador)
Modelo Catraca Box Net - comunicação Ethernet 10/100 Mbps (TCP/IP)

qual modelo de catraca?
E ai vc saberá qual caminho terá que utilizar.
Edit : vi que falou que é o modelo net, é a mais fácil, o próprio fabricante tem um sdk.
de qualquer maneira esse link vai lhe ser interessante
http://edn.embarcadero.com/article/20679
e este também.
http://www.devmedia.com.br/utilizando-a-api-rxtx-para-manipulacao-da-serial-parte-i/6722

Integração Spring MVC e catraca


Use of protected keyword in c#?

Question: I want to understand the use of "protected" keyword in the following code (line 3).
  public class  PlayerData
  {
     static protected PlayerData instance;
     static public PlayerData Instance { get { return instance; } }

     public int health;
  }

  public class GameManager
  {
      PlayerData.Instance.health = 10;
  }

Comment: Do you know what `protected` means?
Comment: i suggest asking the author. they oughta know why they did what they did.
Comment: A derived class could replace the instance completely, because it's protected. But that's bad design. Most design guidelines suggest that member variables (whether static or not) should always be private.
Comment: It has been written by Unity 3D developers. I found it in the game named Trash Dash. The name of the script is PlayerData.
Comment: Yes I know what protected means : A protected member is accessible within its class and by derived class instances. I ask this question because there is no inheritance here. So I thought he wrote this code for a specific reason. I just want to learn
Answer: A private field is not accessible from a child class.
A protected field can be.
If the field is protected, we can inherit from this class and use this field instead of the property.
This avoids the use of the getter which is a method, and that is a crazy time consuming via a CPU PROC CALL and RET using the CPU STACK to return the reference.
Thus it is more speed optimized to use the field instance instead of teh property Instance because we directly use the reference without the need of a method call that will slow down the process and the current thread, thus the game.
Approximately ~5x faster, way to speak vaguely, for each usage.
But that said, we must be carefull to not change the underlying object instance, unless we have a good reason. This field could be read-only, but it is not, who knows why. Perhaps to be able to change the object... either it is just an oversight, or this ref is assigned outside a constructor, or can be reassigner at any time.
Comment: Property getters and setters will almost always be inlined by the compiler or JIT optimization. Hence, your claimed 5x speed advantage is speculative to say the least.
Comment: @GoodNightNerdPride Indeed, what I said it theoric. I have no particular knowledge of what you mention. But we cannot rely on possible optimization at such a low-level as this is not guaranteed since .NET IL code is not inlined like C inline functions are. And that, depends on many things that can vary from one platform to another, and from one implementation to another.

Use of protected keyword in c#?


Restringir acesso por htaccess

Question: Tenho um servidor dedicado separado da hospedagem do meu site, alguns conteúdos como imagem, vídeos, textos e etc serão puxados desse dedicado, o problema é que eu gostaria de restringir o acesso a esses arquivos diretamente pela URL, e deixar eles acessiveis somente se a solicitação vier diretamente do site, já tentei usar o Allow from IP, porém o ip que vai é o IP do usuário e não o do meu site, o que poderia ser um problema no futuro... já tentei usar o HTTP REFERER porém não funcionou, alguém pode me dizer o que posso fazer para limitar e exibir esse conteúdo somente dentro do site?
Answer: Respondendo a pergunta, antes de mais nada, o bloqueio para requisições de fora via .htaccess é algo assim:
RewriteEngine on
RewriteBase /
RewriteCond %{HTTP_REFERER} !^http://www\.seusite\.com/ [NC]
RewriteCond %{HTTP_REFERER} !^http://seusite\.com/ [NC]
RewriteRule ^.*$ - [F]

Mas isto é só para dificultar um pouco para os curiosos, pois qualquer coisa que o navegador acessa sem restrição, pode ser acessado diretamente por uma requisição externa. Os cabeçalhos HTTP são facilmente simulados.
Para proteger contra acessos automatizados, um captcha ajudaria, mas isso é inviável para recursos normais, como imagens, JS, CSS, áudio etc que seriam usados normalmente pelo site. Além disso, nada impediria do usuário responder o captcha numa aplicação externa ao site.
É praticamente impossível um bloqueio razoável sem efeitos colaterais no contexto apresentado na pergunta.
A vantagem do bloqueio por REFERER é no caso de Hot Link, ele ao menos evita que seus recursos sejam linkados em sites de terceiros (porque neste caso, o terceiro não tem controle sobre o navegador do usuário, que estará fazendo a requisição). Você não tem como impedir que este terceiro acesse seus dados e tire uma cópia, mas ele mesmo não tem como fazer com que os usuários comuns (do site dele) contornem a sua proteção de maneira simples e acessem seus arquivos diretamente. Ao menos desincentiva o consumo indevido da banda de transmissão do seu servidor, pois neste caso ele é obrigado a ao menos intermediar o conteúdo.
Não posso negar nem confirmar que já fiz isso :P, mas controlando o REFERER diretamente na sua apliação, você poderia muito bem servir uma imagem extremamente inadequada se for linkada num site de terceiros, mas correta se a pessoa acessar pelo seu site ou se o REFERER estiver vazio (importante considerar que só é hotlink se vier preenchido, e com site errado). Não recomendo, pois pode ficar no cache da pessoa, e aparecer coisa errada se futuramente a mesma pessoa acessar seu site diretamente, dando um resultado desastroso. Mas sempre é bom saber que é possível ;)
Comment: Me parece ser um problema diferente (seria o caso de abrir pergunta separada). Lembre-se de postar o código na nova pergunta. Lembre-se de dar uma pesquisada antes se não tem alguma similar já.
Comment: Entendi, já estava pensando sobre isso mesmo, tenho uma função que verifica a existência de arquivos nesse servidor, porém o mesmo diz que os arquivos não existem, sendo que se eu acessar o mesmo arquivo direto pela URL ele existe, poderia me ajudar?
Comment: Ok obrigado, voltando a minha pergunta atual, então não existe nenhum método de bloquear requisições de arquivos no meu servidor dedicado, através do Firewall ou do próprio Apache? É que eu realmente gostaria de deixar esses arquivos visíveis só no site
Comment: Impossível. Tudo que o navegador faz, pode ser feito diretamente pelo cliente (que é basicamente o que eu já respondi acima).
Comment: Entendo, vou usar então o RewriteCond pra dificultar um pouco, já é um começo.
Comment: Não seria possível também colocar uma senha na pasta com esses arquivos e na hora de solicitar eles no site, mandas as informações de acesso junto com o embed?
Comment: E o que impede da pessoa linkar com as mesmas informações? Se ela copia o URL, pode copiar as credenciais. Minha sugestão é fazer algo que não dependa deste tipo de bloqueio. Você vai ficar perdendo horas para bolar algo que um atacante vai quebrar em minutos (seja lá que solução encontrar).
Comment: Elas não poderiam ser passadas de alguma forma oculta? Um post, algo do tipo? Ou posso criar um scripts para receber a requisição e então dizer de onde a mesma está vindo e preparar o arquivo para envio?
Comment: Hoje em dia sites como os Correios, Registro.br, Secretaria da fazenda, etc não consegem bloquear isso. Como eu já disse, não tem como. Só com artifícios como captcha e coisas do tipo, mas isso inviabiliza uso no próprio site. Não adiantaria eu listar todas as formas de contorno na resposta, mas tenha a clareza de que não tem solução que não comprometa o uso normal. Pode fazer o que for, vai sempre ter contorno. No máximo, cria dificuldades, mas sempre vai perder muito mais tempo do que quem for contornar. O mais "Barato" é o REFERER, quem passa ele passa o resto.
Comment: Entendi, vou trabalhar melhor na ocultação da URL do arquivo numa versão futura então ultilizando BLOB, de qualquer forma obrigado por sua ajuda <3 vou abrir outra questão para a verificação dos arquivos

Restringir acesso por htaccess


Why is the solution to this ODE as follows?

Question: $rV = \pi x − f + \mu x \frac{\partial V(x)}{\partial x} + 0.5\sigma^2 x^2 \frac{\partial^2 V(x)}{\partial x^2}$
Why is the general solution given by: $V(x) = A_0 + A_1 x + A_2 x^\lambda + A_3 x^\beta$?
I thought that since this is a second order non-homogenous differential equation, that the solution would consist of a particular + general solution, where the general solution would look something like $V(x) = c_1 e^{r_1 x} + c_2 e^{r_2 x}$ where $r_i$ the roots of the corresponding polynomial.
Could anyone please explain? Thanks in advance.
Answer: Hint:
see the Euler-Cauchy eqution https://en.wikipedia.org/wiki/Cauchy%E2%80%93Euler_equation
your solution should be $Y=Cx^{m}$ not $Y=Ce^{mx}$
Comment: Thank you, but I'm not entirely sure what you mean, could you please explain?
Answer: This is called a Cauchy–Euler equation. The important point is that the coefficients are not constant, but the terms containing derivatives are all of the form
$$ x^k \frac{d^k}{dx^k} V, $$
which means that substituting $y=\log{x}$,
$$ \frac{d}{dy} = \frac{1}{x} \frac{d}{dx}, \quad \text{or} \quad \frac{d}{dx} = e^y \frac{d}{dy} $$
which allows you to reduce it to a constant-coefficient equation (but beware that derivatives higher than the first create more than one term when you use the chain rule).
Comment: Thanks very much! But how would that lead us to believe that the general solution looks like the one in the OP?
Comment: Solving the constant-coefficient equation you generate gives a function that is a sum of terms of the form $e^{\lambda y}$. Substituting $x$ back in, $e^{\lambda y} = e^{\lambda \log{x}} = x^{\lambda}$.


NBA "and one" rule - an edge case

Question: My question is very similar to this one, although it is a little different and may have a different answer. (Also, I think the answer to that question somewhat misses the point).
Consider the following sequence of events:

an offensive player is fouled while driving to the basket,
the offensive player travels (because of the foul),
the offensive player shoots the ball and it goes in.

This occurred in a recent game I was watching (the foot came down just a fraction of a second before the ball left his hand, so it's easy to understand why the refs may have missed it or chose not to call it).
I can see three potential answers.

This is a non-shooting foul. Even though continuation would have been granted, he traveled first and thus no shot legally occurred.
Shooting foul, basket does not count, 2 shots are awarded. Since continuation is granted, and the offensive player is trying to shoot, it's a shooting foul. Since the shot was not legal, the basket doesn't count.
Shooting foul, basket counts, 1 shot is awarded. Similar to above, but for some reason the basket counts.

I get that this is an edge-case and might not come up very often. I watch a lot of basketball and have never seen this come up (unless the third proposed answer is correct).
An answer with a specific example where this occurred would be particularly welcome.
Comment: The other question doesn't even have an answer that deals with the situation of that question. It does not address whether continuation results in penalising the offensive foul by disallowing goal, penalising both by disallowing goal and penalising the defensive foul for 2 FT, or allowing goal and penalising defensive foul for +1 FT.
Comment: Not in this question, it hasn't, and not in the other one, either, so I don't know where that comes from or why it's relevant at all.
Comment: I know that you suggest this is not a good answer, but it really would be the same situation. [NBA Continuation Rule](https://sports.stackexchange.com/questions/24208/nba-continuation-rule)
Comment: @Nij "Any foul made after the whistle is called, is not considered."  The whistle has been blown so traveling would not be able to be called.
Comment: @kuhl  I agree with you that traveling won't be called. Unfortunately, this doesn't address the question in any way.
Answer: I believe this is at least mostly answerable from the rulebook, particularly post-Harden rule.  Two clarifications that don't actually answer (but make things more clear, I hope, by eliminating some murkiness), then the answer.
First: adding the definition of "the gather" into the rulebook made this a bit more clear, I believe, but didn't change anything.
Second: in this case, we are clearly talking about drives only, and specifically drives that finish in the lower defensive box (the area past the bottom of the free throw circle, and between the two marks three feet on either side of the lane).  Per the video on continuations, post-Harden Rule (i.e., summer 2017) at least, only fouls occuring on shots that end up there are allowed to be treated as fouls when occurring prior to the actual shot - all other shots must actually begin shooting, not just gathering the ball, in order to count as a continuation foul.

With that said: if the player travels, then the shot will not count.  The rulebook (rule 12, specifically) is specific in when it allows for the shot to count:

one free throw attempt if the personal foul is on the defender and there is a successful field goal or free throw on the play.

The field goal must be successful - which means no other rule violation occurred (for example, if the offensive player committed a foul, the basket would not count).
Per the video earlier, though, it would count as a shooting foul - the shot simply would not be counted as successful, so the player would get 2 shots.  The point at which the foul becomes a shooting foul is when he gathers his dribble - anything after that is irrelevant to the shooting/not shooting element.
Comment: And yes, the travel is often ignored, but that's true whether there is a shot or not. :)
Answer: Not an authoritative answer, due to the lack of a source. But according to the question/answer posted here, I think the answer is "the shot does not count, but two (or three, when relevant) shots will be awarded. This answer makes the most "logical" sense in my opinion. In practice, it seems that the basket, and one free throw, is typically awarded - unless the travel is blatant.
Answer: There is no travel call after a whistle for the foul. The question of whether the basket counts depends on whether the ref considers the shot to be a continuation of the move the shooter was making at the time he was fouled. (That's why the NBA continuation rule is relevant.) If the move was a continuation, the shot counts and the shooter gets one free throw for the foul. If the shot was not a continuation, then it isn't a shooting foul, the basket does not count, and free throws depend on whether the fouling team is in the penalty.
Comment: This answer, like the linked question, ignores the focus of this particular question. Of course there will be no travel call, but the question is "how can the shot count if it was an illegal shot (because of the uncalled travel)?". You may be right (although I doubt it), but your answer doesn't really address this in any way.

NBA "and one" rule - an edge case


Large amount of entity revision cleaning leads to connection abortion

Question: I am trying to remove revisions from each entity type which has the revision feature via drush command.
The amount of entities are quite a lot: around 10K nodes, 2k paragraphs.
On localhost everything is fine.
But in the cloud the drush_print($log) successfully runs and the following error appears:
<code> [warning] PDO::beginTransaction(): MySQL server has gone away Connection.php:1165
 [warning] PDO::beginTransaction(): Error reading result set's header Connection.php:1165

In Connection.php line 1165:

  SQLSTATE[HY000]: General error: 2006 MySQL server has gone away
</code>
The two environments are close to identical. Any suggestions where could I start to investigate?
Comment: You could do a diff on each environments php.ini and my.cnf.
Comment: Well here is a work around. Backup of live site, put live site in maintenance mode, import backup to local, do your clean up on local and then upload db to live site.
Comment: Additional information request.
RAM size, # cores, any SSD devices on MySQL Host server?
Post on pastebin.com and share the links.
From SSH login root, Text results of:
B) SHOW GLOBAL STATUS;    after minimum 24 hours UPTIME
C) SHOW GLOBAL VARIABLES;
E) complete MySQLTuner report
for server workload tuning analysis to provide suggestions.
Comment: What method are you removing revisions from entities?
Comment: @ssibal        Any chance you can post additional information requested Jan 15, 2020?
Answer: It turned out what the real issue was. I didn't mention (thought it's not important) that this was actually a Drush command pointing to another multi site.
The actions took "too long" on the other site and by the time it returned with success, the default Mysql connection was timed out and couldn't write to the database anymore. (even tho the corresponding Mysql timeout settings were way higher than the actual amount of time that was spent on the other site)
We solved with with
<code>$process = proc_open($command, [STDIN, STDOUT, STDERR], $pipes);
if (!is_resource($process)) {
  throw new \InvalidArgumentException("Could not execute `{$command}`.");
}
while (($status = proc_get_status($process)) && ($status['running'])) {
  $this->entityStorage->getQuery()->count()->execute();
  sleep(5);
}
proc_close($process);
</code>


SNT0-MC1-F20 Mailman issue

Question: We are having issues with our maling list, we are using MailMan, a piece of log that i thought it might help in tracking the issue,
Multiple lines like the following:
(lost connection with mx1.hotmail.com[184.108.40.206] while sending MAIL FROM

Then at the end the following is received:
(host mx1.hotmail.com[18.104.22.168] said: 550 SC-002 (SNT0-MC1-F20)

Checking that error message means:
SNT0-MC1-F20

Mail rejected by Outlook for policy reasons. The mail server IP connecting
to Outlook has exhibited namespace mining behavior.

I have tried to check if there is something wrong with our dns record, one thing i have noticed is that:
mail.example.com is a CNAME to example.com and example.com
is an A record to server ip.

I have mentioned here hotmail as an example of the servers we are trying to connect, some of these servers succeed, unfortunately most of them fails [i guess the ones that checks well before the receiving an email.]
Please suggest any idea that you might thing could be the cause, Could be the DNS record issue i mentioned be the cause?
Also please note that we already have a PTR rescod for the mail server IP.
Other logs:
 Dec 18 10:15:44 mail postfix/smtp[688]: D9FC3E000E0: to=<email@example.com>, relay=none,
 delay=319639, delays=319597/0.28/42/0, dsn=4.4.1, status=deferred (connect to
 mailbk.example.org[x.x.x.x]:25: Connection timed out)

 Dec 18 10:15:44 mail postfix/error[846]: 87571E000D7: to=<email@example.com>,
 relay=none, delay=332315, delays=332272/43/0/0.13, dsn=4.4.1, status=deferred
 (delivery temporarily suspended: connect to mailbk.example.org[x.x.x.x]:25:
 Connection timed out)

Comment: It will be easier to answer this if you tell us your source IP, as well as the destination one, so we can run it past the many RBL checkers in case one of them has any light to shed on why their outlook thinks this.  It may not be a decision they've reached themselves.
Comment: If you don't want to post the source IP here, you can check it against various blacklists at http://www.spamhaus.org/ . They also have information about how to get removed.
Comment: yes i guess it's not a good idea to expose private server ip.
Answer: Your DNS records have nothing to do with it. The error message talks about "mining behaviour" - this is a method used by spammers trying to verify recipient addresses by making a lot of simultaneous connections, or by sending a mail to a lot of different users and then collecting the responses from the mail server. So what happens is that when you send a mailinglist mail that has a lot of hotmail recipients, then hotmail can't distinguish it from actual spam and so they reject the mail.
I'd advise you to start by contacting hotmail directly; a web search for "hotmail deliverability support" should point you in the right direction.
You could also take a look at queue shaping to limit the number of concurrent delivery attempts specifically to hotmail. There are instructions for how to do that at the postfix documentation site; while it talks about backlogs, it's equally useful to this situation. The basic steps for postfix 2.5 are:
In master.cf you set up a separate service for hotmail, like this:
# service type  private unpriv  chroot  wakeup  maxproc command
hotmail   unix     -       -       n       -      5    smtp

Add that transport to the domain hotmail.com in /etc/postfix/transport:
hotmail.com  hotmail:

In main.cf, configure the transport map and set cohort limits:
transport_maps = hash:/etc/postfix/transport
hotmail_destination_concurrency_failed_cohort_limit = 100
hotmail_destination_concurrency_limit = 5

For more information, and for the configuration for previous postfix versions, please look at the postfix documentation site.
Comment: Thanks, i thought it's related cause it does not only happen to hotmail, it happens to other mail servers and most of them return 550 error. I will try to contact hotmail support now. Thanks again.
Comment: Are the other mail servers also part of Microsoft's email services? If so, I'd just add them to the transport map with the same setting, i.e. `othersite.com hotmail:` If not, there may be different reasons for the rejection; it would help if you'd post the log lines for those rejections as well.
Comment: i have added other logs at the end of the question, most logs are the same, connection time out.
Comment: A timeout is an entirely different thing. It means that the server you're trying to send to isn't answering at all, and your server will try to send the email again later. I think it would be useful for you to read a little about how email connections and error messages work - a good place to start is http://email.about.com/cs/standards/a/smtp_error_code.htm

SNT0-MC1-F20 Mailman issue


Controle de acesso Access-Control-Allow-Origin no lado servidor Apache PHP

Question: Não entendo muito de PHP e estou tentando criar um aplicativo para cadastrar automaticamente os produtos da minha loja virtual diretamente no MercadoLivre.
Os dados do anuncio são capturados com JavaScript e enviados para a API do ML via $.ajax, o que acontece é que as imagens que são passadas somente a URL para a API não estão subindo para o site, conferi as URLs e estão corretas.
Tentei setar a URL da logo do site (que é menor) e mesmo assim não vai (não recebo nenhum retorno da API se a imagem foi ou não, ela só não aparece no anuncio).
Se eu pego a URL de uma imagem de outro site (peguei uma do Wikipedia), ela sobe corretamente.
A loja virtual é em PHP  (Opencart) no servidor Apache, será que este bloqueio pode estar ocorrendo no lado servidor pelo PHP ou Apache?
Answer: Esse é um tipo de bloqueio que ocorre no servidor da aplicação você pode contornado enviando um herdade que aceita todas as origens
header('Access-Control-Allow-Origin: *');

Muito importante que isso seja chamado antes de qualquer outra coisa
Errado

<?php
header('Access-Control-Allow-Origin: *');
?>

Correto
<?php
header('Access-Control-Allow-Origin: *');
?>

Comment: Mas como a API do ML vai requisitar diretamente o arquivo JPG, onde eu posso inserir este código?
Answer: Consegui resolver desativando o "Always use HTTPS" do CloudFlare.


My few doubts about the fact that the minimal cut set of the maximal plane graph induces to a cycle.

Question: I read the paper [Baybars, Ilker. "On k-path hamiltonian maximal planar graphs." Discrete Mathematics 40.1 (1982): 119-121.] and noticed following lemma like this

Lemma. Let $G=(V,E)$ be a maximal planar graph and let $S \subset V$ be a minimal separating set (i.e. $G-S$ is disconnected. Then $S$
induces a cycle in $G$.

However, the author did not prove this theorem. So I went to find an original manuscript [see here ] that seemed to be the same author. Here it provided a relatively detailed proof, but I still have some doubts about this proof.

Let $\kappa(G)$ denote the connectivity number of the graph. Lemma 4 refers to the following:

Lemma 4   If G is maximal planar, then $3 \le \kappa(G) \le 5$.

My doubts are listed below:

This article does not mention the meaning of minimal separating set . According to the standard definition, should be defined like this:

A minimal seperating set $S$ is  seperating set such that no proper subset of
$S$  is a seperating set.

The minimum seperating set is seperating set  with the minimum number of elements.

Note that  minimal seperating set  is not minimum seperating set in some cases. As shown in the figure below. Vertex set $\{ 4,5,6,7,8,9 \}$ is minimal seperating set but not minimum seperating set.

Therefore, we can't seem to get $|S| \le 5$.

I noticed this sentence in the proof.

Clearly, exactly two vertices in $S$ must lie in the exterior face of $G$.

I'm not sure why.

$S$ induces a cycle in $G$. Is there  a chord on the cycle $G[S]$?

A cycle has a chord if there are a pair of vertices that are adjacent, but not along the cycle.

Based on the above questions, it is not clear whether this lemma is really correct. So ask for help. Thank you in advance!
Comment: What I found is that "minimal" refers to a cut with a minimal amount of vertices - NOT a separating set that cannot be shrunken anymore. Taking $2,7,11,5,1$ would be sufficient for the minimal set, thus $\kappa(G) = 5$.
Comment: @LegNaiB This is really my confusion about what "minimal"  refers. If according to what you say, there is no problem with this part.  But here's the curious thing is whether is also true for a separating set that cannot be shrunken anymore.
Comment: As your example shows it's possible to get sets that are non-shrunkable with more than 5 nodes. So I assume the author is not referring to this definition.
Comment: Thank you for your remind. In the subsequent analysis,  the  fact that | S | is less than or equal to 5 does not seem to be used.  I estimate the lemma  is  also right for non-shrunkable  separating set.
Answer:
As you mentioned in comments, it doesn't seem to matter whether minimal or minimum separating sets are meant; although a non-shrinkable separating set may have more than 5 vertices, that doesn't seem to play a further role.
This statement "exactly two vertices in $S$ must lie in the exterior face of $G$" isn't actually true, as seen in the example graph in your question. Examples which are actually a minimum separating set (size three, for example) can be come up with as well.

What the author seems to mean is something like "Assuming to the contrary that $S$ does not induce a cycle in $G$, then exactly two vertices in $S$ must lie on the exterior face of $G$."
Suppose $G_1$ and $G_2$ are the connected components left after removing $S$. If there is no path from the exterior face to any point in S, then there must be edges between $G_1$ and $G_2$. This is true, but it seems kind of tricky to establish (and it's definitely not "clear" as the author claims.)

No, there does not have to be a chord on $G[S]$. Consider this graph of a triangular bipyramid, with separating set $\{a,b,c\}$:
Comment: Thank you for your answer. I think your first and second points are correct. I didn't make it clear for the third point. What I mean is that the circle is induce subgraph ( i.e. It must not contain any chord). My idea is that if not, then there must be a vertex falling in one of sub-separated-circle, which contradicts that S is a minimally separated set.
Comment: Yes, that sounds correct! If there were a chord, you could shrink the separating set.


Possibly insufficient data on a shuffling problem

Question: A company controls its employees' access to a restricted area with magnetic cards and passwords. Each of the $k$ employees received an anonymous card and chose an $n$-digit numerical password to associate to their card. Suppose the cards were shuffled and randomly redistributed, and let $A$ be an employee.
a) What is the probability that $A$ enters the restricted area using his password and the card he got after the shuffle?
b) If $A$ was able to enter with his password, what is the probability that he received the same card before and after the shuffle?

a) One easily notes that the probability that an employee picked a given password is $p=10^{-n}$. Now let $L$ be how many of the $k$ cards are associated to $A$'s password, that is, how many employees (including $A$) chose $A$'s password. Then the probability is $L/k$.

b) Let $E_1$ be the event "$A$ entered the restricted area" and $E_2$ be "$A$ got his own card after the shuffle". $E_1$ is just the event asked on a, and since $E_2\subset E_1$, this probability is
$$\mathbb P(E_2\,|\,E_1)=\frac{\mathbb P(E_2\cap E_1)}{\mathbb P(E_1)}=\frac{\mathbb P(E_2)}{\mathbb P(E_1)} =\frac{1/k}{L/k} =\frac1L\quad.$$

Clearly, all there is left is to calculate $L$. How do I get it deterministically? All I know how it is distributed:
$$\begin{align}
\mathbb P(L=l\,|\,L\ge1) &=\frac{\mathbb P(L=l\wedge L\ge1)}{\mathbb P(L\ge1)} =\\
&=\frac{\displaystyle{\binom kl}p^l(1-p)^{k-l}I_{\{1,...,k\}}(l)}
{\mathbb P(L\neq0)} =\\\,\\\,\\
&=\frac{\ldots}
{1-\displaystyle{\binom k0}p^0(1-p)^{k-0}} =\\\,\\\,\\
&=\frac{\ldots}{1-(1-p)^k}\quad,
\end{align}$$
and so
$$\mathbb P(L=l)=\frac1{1-(1-10^{-n})^k}\binom kl10^{-nl}(1-10^{-n})^{k-l}I_{\{1,...,k\}}(l)\quad.$$
Comment: Do we actually have any reason on the basis of the wording of the question to think that people choose their passwords randomly? If n=4 and half the people choose "1234" (... "*the kind of password an idiot would have on his luggage*") the chance of getting the password with someone else's card is quite high.
Comment: We do have some experience of the sorts of passwords people choose in practice (such as when choosing PINs) ... and the assumption that people choose randomly from the set of possible choices isn't close to actual human behavior.
Comment: @Glen_b Since we don't know their thought process, I guess we have to assume the passwords are equiprobable, for simplicity. But you have a point; in practice, some passwords are chosen by no-one.
Answer: Doing other exercises, it occurred to me that if the answers depend on the r. v. $L$, they are conditional, so that my answer for item a is actually $\mathbb P(E_1\,|\,L=l)$ and for b $\mathbb P(E_2\,|\,E_1,L=l)$, therefore,
$$\begin{align}
\mathbb P(E_1) &= \sum_l\mathbb P(E_1\,|\,L=l)\,\mathbb P(L=l) =\\
&= \sum_{l=1}^k\frac 1{1-(1-10^{-n})^k}\frac lk\binom kl10^{-nl}(1-10^{-n})^{k-l} =\\
&= \frac 1{1-(1-10^{-n})^k}\left[10^{-nk} +
\sum_{l=1}^{k-1}\binom{k-1}{l-1}10^{-nl}(1-10^{-n})^{k-l}\right]
\end{align}$$
and
$$\begin{align}
\mathbb P(E_2\,|\,E_1) &= \sum_l\mathbb P(E_1\,|\,E_2,\,L=l)\,\mathbb P(L=l) =\\
&= \sum_{l=1}^k\frac 1{1-(1-10^{-n})^k}\frac 1l\binom kl10^{-nl}(1-10^{-n})^{k-l} =\\
&= \frac 1{1-(1-10^{-n})^k}\sum_{l=1}^k\binom kl\frac{10^{-nl}(1-10^{-n})^{k-l}}l\quad.
\end{align}$$
Answer: Your approach seems like a difficult way to address the problem.
For part (a), there are two cases: $A$ either gets his own card (with probability $1/k$), or he does not.  If he gets his own card, then the probability of gaining access to the secure area is 1.  If he does not, then it is $10^{-n}$.
You can now calculate the probabilities of the (disjoint) events:

$F$:=[$A$ gets his own card and gains access to the secure area]
$G$:=[$A$ gets someone else's card and nonetheless gains access to the secure area]

Note that the event of gaining access to the secure area is $H=F\cup G$, and the answer to part (b) is therefore $P[F\vert H]$.
Comment: That solution ignores how many employees chose the same password as $A$. For instance, if for a miracle every employee chose the same password, the probability on item *a* would be $1$, which is not $p$, because $n\neq0$.

The probability that $A$ managed to enter the restricted area is not just $p$; unfortunately, it involves a complicated truncated binomial variable with parameters $k$ and $p$.
Comment: Yes and no.  As @Glen_b noted in the comments to the main question, it may not be safe to assume that all passwords are equally likely.  But if they are, then it doesn't matter how many cards have the same password as $A$'s.  All that matters is whether the card that $A$ ends up with has the same password.

Sure, you can go about it by first calculating a distribution for $L$, as you do.  But ultimately you'll have to sum over possible values of $L$, and when you do, a lot of terms will cancel out.  This is what I meant when I said that you had chosen a difficult way to address the problem.