Why do we define the norm on the sequence space of $\mathbb{C}$ like this?

Question:
1.2-1 Sequence space $s$. This space consists of the set of all ( bounded or unbounded) sequences of complex numbers and the metric $d$ defined by:
$$ d(x,y) = \sum_{j} \frac{1}{2^j} \frac{|\epsilon_j -\eta_j |}{ 1+ | \epsilon_j - \eta_j |}$$
Where, $x= (\epsilon_j) , y=(\eta_j) \in s$
Functional Analysis by Kreyszig, Wiley student edition.

Why do we define the distance between sequences in this way?

My attempt:
$\epsilon_j - \eta_j$ can be thought of as the complex vector joining the $jth$ point between the two sequences. I don't quite get the idea behind the $2^j( 1+ | \epsilon_j - \eta_j |)$ in the denominator.
Comment: You haven't given us the relation between $x,y,\epsilon_i,\eta_i,$ although we can guess.
Comment: Note that the set of all complex numbers under the metric $d(u,v)=\frac{|u-v|}{1+|u-v|}$ is bounded, so the sequences are bounded *under this metric.*
Comment: Just a terminology quibble: the metric you wrote is _not_ a "norm" (in the contemporary sense), since it is not homogeneous, that is, $d(tx,ty)$ with scalar $t>0$ is rarely $t\cdot d(x,y)$.
Answer: This metric is one of many possible metrics which you can put on the product $\mathbb C^n$ (where I permit $n$ to be infinity) so that it induces the product topology. There are two things happening at once in that formula: replacing a metric with a bounded one, and using those to induce a metric on the product.
We start with the usual metric $d(x,y)=|x-y|$. There are several standard ways of replacing it with an equivalent metric which is bounded (that is, is values are bounded). The one the author uses here is $d'(x,y)=\frac{d(x,y)}{1+d(x,y)}$. Another common way is $d'(x,y)=\min(d(x,y),1)$.
Now, given a sequence of metrizable topological spaces $X_n$, the product topology on $\prod_n X_n$ is also metrizable, and this sort of sum is precisely one way to do that: on each $X_n$ pick a metric $d_n$ which is bounded by $1$, and metrize the product by $d((x_n),(y_n))=\sum\frac{1}{2^n}d_n(x_n,y_n)$. Note that this boundedness is only required in the case of infinite product, to guarantee convergence. In your question we take $X_n=\mathbb C$ for each $n$, and let $d_n$ be the metric $d'$ from the previous paragraph.
Comment: ... and, indeed, the $2^{-n}$ can be replaced by any sequence $a_n$ of positive reals with finite sum... So, really, even though a countable (infinite) product of metric spaces is _metrizable_, there is no canonical metric.


erro add chave ssh para conta no github

Question: pessoal alguém estou tentando add minha chave ssh para conta no github so qe esta dando erro,
ele pede um titulo ai eu coloco "windows"
depois pede uma chave ai eu ponho "id_rsa.pub"
aparece esse erro: Key is invalid. It must begin with 'ssh-ed25519', 'ssh-rsa', 'ssh-dss', 'ecdsa-sha2-nistp256', 'ecdsa-sha2-nistp384', or 'ecdsa-sha2-nistp521'. Check that you're copying the public half of the key
Answer: No título sugiro a você colocar algo que faça referência ao local que você está adicionando. Ex.: "Notebook Pessoal".
Supondo que você está utilizando um sistema Unix, na chave você deve colocar o conteúdo do arquivo id_rsa.pub, ele fica na pasta $HOME/.ssh, você pode verificar o contéudo do arquivo usando o comando cat: cat $HOME/.ssh/id_rsa.pub.
Explicação: O SSH usa criptografia assimétrica, que é baseada no uso de duas chaves: sendo uma (chave pública) usada pelo remetente para criptografar os dados antes de enviá-los, no seu caso o Github será o remetente, e a outra (chave privada) usada para recuperar a mensagem original, nesse caso a sua própria máquina.
Espero ter ajudado. =)
Comment: obrigado por responder, mais a solção era so ir na pasta que tinha sido gerada copiar o contedo dela e colar ali na chave

erro add chave ssh para conta no github


Evaluate $\int_0^\pi \left(\frac{\sin{2x}\sin{3x}\sin{5x}\sin{30x}}{\sin{x}\sin{6x}\sin{10x}\sin{15x}}\right)^2 dx$ (from MIT Integration Bee 2023)

Question: This is from the final round of MIT Integration Bee 2023.
$$\int_0^\pi \left(\frac{\sin({2x}) \sin({3x})\sin({5x})\sin({30x})}{\sin({x})\sin({6x})\sin({10x})\sin({15x})}\right)^2 dx$$
The given answer is $7\pi$.

I found a way to do it using contour integrals (see answer below), but this is not a calculation I can finish within 4 minutes (the time limit in the competition). I am still looking for other elegant methods, possibly without using contour integrals.
Comment: Something like [this](https://math.stackexchange.com/questions/4508185/evaluate-int2-pi-0-frac-cos2022x-sin10050x-sin10251x-sin50x-sin?rq=1) may be useful, not really sure but I do see some useful patterns.
Answer: Let $f(x)$ denote the egregious fraction of sines inside the square. Writing $w = e^{2ix}$, we have
\begin{align*}
f(x)
&:= \frac{(\sin 2x)(\sin 3x)(\sin 5x)(\sin 30x)}{(\sin x)(\sin 6x)(\sin 10x)(\sin 15x)} \\
&= w^{-4} \underbrace{ \frac{(w^2 - 1)(w^3 - 1)(w^5 - 1)(w^{30} - 1)}{(w - 1)(w^6 - 1)(w^{10} - 1)(w^{15} - 1)} }_{=:g(w)}.
\end{align*}
Writing the fraction part in the last line as $g(w)$, algebraic manipulation using the finite geometric series formula yields
\begin{align*}
g(w)
= \frac{(w + 1)(w^{15} + 1)}{(w^3 + 1)(w^5 + 1)}
= \frac{w^{10} - w^5 + 1}{w^2 - w + 1}
= w^8 + w^7 - w^5 - w^4 - w^3 + w + 1,
\end{align*}
where we utilized the long division in the last step.1) Now, we write
$$ g(w) = \sum_{k\geq 0} a_k w^k $$
for simplicity. Then by noting that $f(x)$ is real-valued,
\begin{align*}
\int_{0}^{\pi} f(x)^2 \, \mathrm{d}x
&= \int_{0}^{\pi} f(x)\overline{f(x)} \, \mathrm{d}x \\
&= \int_{0}^{\pi} \left( e^{-8ix} g(e^{2ix}) \right) \overline{\left( e^{-8ix} g(e^{2ix}) \right)} \, \mathrm{d}x \\
&= \sum_{j,k} a_j \overline{a_k} \int_{0}^{\pi} e^{2ix(j-k)} \, \mathrm{d}x \\
&= \pi \sum_{k \geq 0} |a_k|^2 \\
&= 7\pi.
\end{align*}

1) Alternatively, if OP is familiar with some abstract algebra, we can proceed as below:
\begin{align*}
g(w)
= \prod_{d \mid 30} (w^d - 1)^{\mu(30/d)}
= \Phi_{30}(w)
= w^8 + w^7 - w^5 - w^4 - w^3 + w + 1,
\end{align*}
where $\mu$ is the Möbius function and $\Phi_n$ is the cyclotomic polynomial.
Answer: Since we are squaring all the sine functions, we can extend the limit from $0$ to $2 \pi$.
$$I = \frac{1}{2} \int_0^{2\pi} \left(\frac{\sin{2x}\sin{3x}\sin{5x}\sin{30x}}{\sin{x}\sin{6x}\sin{10x}\sin{15x}}\right)^2 dx$$
Using $\sin{2y} = 2 \sin{y}\cos{y}$,
$$I  = \frac{1}{2} \int_0^{2\pi} \left(\frac{\cos{x}\cos{15x}}{\cos{3x}\cos{5x}}\right)^2 dx $$
Using $\frac{\cos{3y}}{\cos{y}} = 4 \cos^2 y - 3 = 2 \cos{2y} -1$,
$$I = \frac{1}{2} \int_0^{2\pi} \left(\frac{2\cos{10x}-1}{2\cos{2x}-1}\right)^2 dx $$
$$ = \frac{1}{2} \int_0^{2\pi} \left(\frac{e^{10 i x} + e^{-10 i x}-1}{e^{2 i x} + e^{-2 i x}-1}\right)^2 dx $$
Now, substitute $z = e^{i x}$
$$I = \frac{1}{2 i} \oint \left(\frac{z^{10} + z^{-10}-1}{z^{2} + z^{-2}-1}\right)^2 \frac{dz}{z} ,$$ where the contour is over the unit circle, along the anti-clockwise direction.
$$= \frac{1}{2 i} \oint \left(\frac{z^{20} - z^{10}+1}{z^{4} - z^{2}+1}\right)^2 \frac{dz}{z^{17}} $$
Now, let's use the fact that $y^2 - y + 1 =(y + \omega)(y+\omega^2)$, where $\omega$ and $\omega^2$ are the complex cube roots of 1.
Then $$\frac{z^{20} - z^{10}+1}{z^{4} - z^{2}+1} = \frac{(z^{10}+\omega)(z^{10} + \omega^2)}{(z^2+\omega)(z^2 + \omega^2)}$$
Notice that $\omega^5 = \omega^2$, and $(\omega^2)^5 = \omega$.
Using $\frac{a^5 + b^5}{a+b} = a^4 - a^3 b + a^2b^2 - ab^3 + b^4$, we get,
$$\frac{(z^{10}+\omega^2)}{(z^2 + \omega)} = z^8 - \omega z^6+\omega^2 z^4 -z^2+\omega .$$
Then, $$I = \frac{1}{2 i} \oint \left((z^8 - \omega z^6+\omega^2 z^4 -z^2+\omega)
(z^8 - \omega^2 z^6+\omega z^4 -z^2+\omega^2)
\right)^2 \frac{dz}{z^{17}} $$
Just count the powers and keep using the identity $\omega^2 + \omega = -1$ to simplify,
$$= \frac{1}{2 i} \oint \left(z^{16} + z^{14} - z^{10}-z^8-z^6+z^2+1\right)^2 \frac{dz}{z^{17}} $$
(Note: One can also use long division to show $\frac{z^{20} - z^{10}+1}{z^{4} - z^{2}+1} = z^{16} + z^{14} - z^{10}-z^8-z^6+z^2+1$)
The coefficient of $z^{16}$ in $\left(z^{16} + z^{14} - z^{10}-z^8-z^6+z^2+1\right)^2$ is 7.
Finally we use the residue therem, $$I = \frac{1}{2 i} \oint 7 z^{16} \frac{dz}{z^{17}} = \frac{1}{2i} 7 \cdot 2 i \pi = \boxed{7 \pi}$$
Answer: $$A=\frac{\sin (2 x)\, \sin (3 x)\, \sin (5 x) \,\sin (30 x) }{\sin (x) \,\sin (6 x) \,\sin (10 x) \,\sin (15 x) }$$ Simplifying $$A=-1-2 \cos (2 x)+2 \cos (6 x)+2 \cos (8 x)$$ Squaring and simplifying again
$$A^2=7+8 \cos (2 x)-2 \cos (4 x)-8 \cos (6 x)-8 \cos (8 x)-4 \cos (10
   x)+$$ $$2 \cos (12 x)+4 \cos (14 x)+2 \cos (16 x)$$
$$\int A^2\, dx=7 x+4 \sin (2 x)-\frac{1}{2} \sin (4 x)-\frac{4}{3} \sin (6
   x)-\sin (8 x)-$$ $$\frac{2}{5} \sin (10 x)+\frac{1}{6} \sin (12
   x)+\frac{2}{7} \sin (14 x)+\frac{1}{8} \sin (16 x)$$
Edit (detailed steps for the simplication)
Use the half-angle formulae for $\sin(2x)$, $\sin(30x)$ in numerator and for $\sin(6x)$, $\sin(10x)$ in denominator. This gives
$$A=\frac {\cos (x)\, \cos (15 x) }{\cos (3 x)\, \cos (5 x) }$$
Using product to sum and let $x=\frac t 2$
$$A=\frac{\cos (14 x)+\cos (16 x)}{\cos (2 x)+\cos (8 x)}=\frac{\cos (7 t)+\cos (8 t)}{\cos (t)+\cos (4 t)}$$
Now, $t=\cos ^{-1}(z)$ and multiple angle formulae to make
$$A=\frac{128 z^8+64 z^7-256 z^6-112 z^5+160 z^4+56 z^3-32 z^2-7z+1 } {8 z^4-8 z^2+z+1 }$$
Factorization
$$A=\frac{ (z+1) (2 z-1) \left(4 z^2-2 z-1\right) \left(16 z^4+8 z^3-16 z^2-8
   z+1\right)} {(z+1) (2 z-1) \left(4 z^2-2 z-1\right) }$$
Simplify and back to $t$
$$A=16 \cos ^4(t)+8 \cos ^3(t)-16 \cos ^2(t)-8 \cos (t)+1$$
Now, using
$$\cos^2(t)=\frac 12(1+\cos(2t))$$
$$\cos^3(t)=\frac 14 (3 \cos (t)+\cos (3 t))$$
$$\cos^4(t)=\frac{1}{8} (3+4 \cos (2 t)+\cos (4 t))$$
Replace, make $t=2x$ to find the result.
Comment: @SangchulLee. I did it but you can make it much faster. Have a look at my edit. Cheers :-)
Comment: Would you mind enlightening us as to how we simplify $A$ to a trig polynomial? All the other answers seem resorting to the substitution $z=e^{ix}$ followed by some algebra on the resulting rational function, so It would be nice if it can be done using trig identities or some slick tricks.
Comment: It is good to see that the substitution $z=\cos t$ works decently in this case! Thank you for the detailed explanation. :)
Answer: From @Archisman Panigrahi,
\begin{eqnarray}
I&=&\frac{1}{2} \int_0^{2\pi} \left(\frac{\cos{x}\cos{15x}}{\cos{3x}\cos{5x}}\right)^2 dx= \frac{1}{2} \int_0^{2\pi} \left(\frac{\cos{14x}+\cos{16x}}{\cos{2x}+\cos{8x}}\right)^2 dx\\
&=&\frac{1}{4} \int_0^{4\pi} \left(\frac{\cos{7x}+\cos{8x}}{\cos{x}+\cos{4x}}\right)^2 dx=\frac{1}{2} \int_0^{2\pi} \left(\frac{\cos{7x}+\cos{8x}}{\cos{x}+\cos{4x}}\right)^2 dx.
\end{eqnarray}
Using
$$ \cos\theta=\frac12(z+z^{-1}),z=e^{i\theta} $$
one has
\begin{eqnarray}
&&\frac{\cos{7x}+\cos{8x}}{\cos{x}+\cos{4x}}=\frac{z^7+z^{-7}+z^8+z^{-8}}{z+z^{-1}+z^4+z^{-4}}\\
&=&\frac{1+z+z^{15}+z^{16}}{z^4(1+z^3+z^5+z^8)}=-1-(z+z^{-1})+(z^3+z^{-3})+(z^4+z^{-4})\\
&=&-1-2\cos x+2\cos3x+2\cos4x
\end{eqnarray}
and hence
$$I=\frac{1}{2} \int_0^{2\pi} \left(\frac{\cos{7x}+\cos{8x}}{\cos{x}+\cos{4x}}\right)^2 dx=\frac12\int_0^{2\pi}(-1-2\cos x+2\cos3x+2\cos4x)^2=7\pi.$$
Comment: Use long division.
Comment: Got it. Long division works, and also the formula I found in my answer $\frac{z^{20} - z^{10}+1}{z^{4} - z^{2}+1} = z^{16} + z^{14} - z^{10}-z^8-z^6+z^2+1$ can be used (replacing $z^2 \rightarrow y$).
Comment: How did you get $\frac{1+z+z^{15}+z^{16}}{z^4(1+z^3+z^5+z^8)}=-1-(z+z^{-1})+(z^3+z^{-3})+(z^4+z^{-4})$ ?


Apache / mod_rewrite: Change TLD, but keep subdomain, protocol and query-string

Question: I thoroughly searched stackoverflow and found about 100 mod_rewrite-questions, but this was not covered...strange as it seems pretty common.
My problem: I have a web-application on a master-domain (mywebapp.com). Now I have additional country-specific TLDs (eg .ch) which I'd like to redirect on the .com-domain. Nothing special so far. But now to the other criteria:
Requirements

the protocol should be left unchanged
the query-string should be left unchanged
the subdomain-part should be left unchanged as the tenants are identified by those
only exchange the TLD!

Examples
So to put it all together some examples how it should be:

http:// demo.mywebapp.ch -> http:// demo.mywebapp.com
http:// other.mywebapp.ch/user/profile -> http:// other.mywebapp.com/user/profile
https:// third.mywebapp.ch/about -> https:// third.mywebapp.com/about

(spaces in urls are intentional to prevent stackoverflow from generating links)
and so on. I really only need to replace the TLD in protocol-generic manner. Of course it would be nice if the rule-set is SEO-conform (301).
Additional Information / details
The domains are currently set to point to the same webserver/IP which I have root-access upon. The server is managed by ISPConfig, but II can edit the vhosts manually as well.
Thanks already in advance!
cheers,
Pascal
Answer: I had problems with this script.
For example it would work fine normally, like:
domain.net => domain.com
domain.net/something => domain.com/something
but when I would try with a subdomain AND a different top level domain then this would happen
sub.domain.org => subdomain.com
but
sub.domain.com => sub.domain.com
So I changed the code, here is my version working:
RewriteCond %{HTTP_HOST} !.*\.com
RewriteCond %{HTTPS} ^on
RewriteCond %{HTTP_HOST} (?:([^.]+\.))?mywebapp\..*
RewriteRule ^.* https://%1mywebapp.com%{REQUEST_URI} [R=302,L]

RewriteCond %{HTTP_HOST} !.*\.com
RewriteCond %{HTTPS} !^on
RewriteCond %{HTTP_HOST} (?:([^.]+\.))?mywebapp\..*
RewriteRule ^.* http://%1mywebapp.com%{REQUEST_URI} [R=302,L]

Hope this helps someone,
rt-2
P.S. I would have added my comment to the current answer, but it said I didn't have enough reputation, for some reason.
Answer: I think the following would do the trick:
RewriteEngine on
RewriteBase /

RewriteCond %{HTTP_HOST} !.*\.com
RewriteCond %{HTTPS} ^on
RewriteCond %{HTTP_HOST} (?:([^.]+)\.)?mywebapp\..*
RewriteRule ^.* https://%1mywebapp.com%{REQUEST_URI} [R=302,L] #removed double slash

RewriteCond %{HTTP_HOST} !.*\.com
RewriteCond %{HTTPS} !^on
RewriteCond %{HTTP_HOST} (?:([^.]+)\.)?mywebapp\..*
RewriteRule ^.* http://%1mywebapp.com%{REQUEST_URI} [R=302,L] #removed double slash

Here's what it's saying:

Create a RewriteRule only if %{HTTP_HOST} does not contain .com
check protocol and only continue if is https
Run a regex to check if subdomain exists and store subdomain if it does (referenced by $1)
Manually force the .com, preceed it with subdomain, concatenate the %{REQUEST_URI} and then redirect (I left it as a 302 Temporary Redirect so you can play with it as needed. I would go to a 301 until you are 100% ready)

Edit: I duplicated the rule set to handle the protocol issue. So apparently you can only get the last backreference. Meaning that when the protocol was https, it would overwrite the subdomain stored in %1 backreference. By having a ruleset for either protocol, you circumvent the issue. Likely not the prettiest way, but it should get the job done.
Comment: Thanks a lot Sam! Two problems are left:

1. Your last line doesn't need a slash before the request_uri...if left like that, I had two slashes after the redirect. Removing the last slash in the rewriterule solved the problem.

2. subdomains don't work yet. If i call test.mywebapp.ch I get redirected to my mywebapp.com (without any subdomain). Do you have an idea how to solve this?

Query-parts on the other hand work flawlessly and I learned a lot looking at your solution. Thanks for taking your time!
Comment: Third problem, sorry: The protocol is now hardcoded in the rewriterule. I need this to be flexibel as both ssl and non-ssl are used. Can I save this in a var and the add it to the rewrite rule as well?
Comment: @PLM57: I updated the answer to account for `http` or `https`. I noticed I was using `$` instead of `%` for backreferencing as well which was likely causing the subdomain to not be included. Let me know how it works out for you.
Comment: Thanks sam! I couldn't test the protocol yet. the subdomain-party doesn't seem to work though. I get forwarded to the root-domain only (bla.mywebapp.ch -> mywebapp.com). This rule i found works for 1 level of subdomain only: RewriteCond %{HTTP_HOST} ^([^\.]+)\.mywebapp\..*

Anyway...as soon as i add the protocol rule, also the subdomains don't work anymore either. I don't know why!?

I think this is on a good path though. Any ideas?
Comment: Further success: after experimenting, i found the rule solving the subdomain-problem. It allows alpha-only-subdomains (unlimited number, or no subdomain at all). i updated your answer. Only problem lefdt: rule not cooperating with the protocol rule. As soon as i include it, nothing works anymore...
Comment: @PLM57 glad we're making progress! I've updated the answer to handle the protocol. I did a little research and it turns out you can't get backreferences from multiple RewriteCond's. Anyway, the updated code should do it for you-let me know how it goes.
Comment: Performance is not an issue. Its just to catch the guys initially calling the webapp with the local-domain. Further work and bookmarks will be on the com-domain. I rechanged the subdomain-matching as your solution didn't do the trick. the rule now defined checks the validity of subdomains (except length, which is very slow in regex). As the chooseable tenant-name (which is the subdomain) is validated, this is no problem though. I also moved to 301 for permanent redirect. If you accept the edit, i can mark your answer as the solution. Thank you so much for your help!
Comment: Glad you got it working. Still not sure why my subdomain regex wasn't working for you though, sorry. It looks like I can't accept your edits though, not sure why. Anyway, glad it's working for you and good luck.
Answer: My issue was little different but I was the impression that RewriteRule is causing protocol switch from https to http , even when i had canonicalname as on.
The property which did the trick for me is RequestHeader set ClientProtocol https , when LTM was doing the SSL off load.
Listen 8085
<VirtualHost *:8085>
UseCanonicalName On
ServerName https://vip-name
ProxyPreserveHost On
RequestHeader set ClientProtocol https
RewriteEngine On
#RewriteCond %{HTTPS} on
RewriteCond %{REQUEST_URI} !^/abc$
RewriteCond %{REQUEST_URI} ^/xyz$
RewriteRule ^ - [skip=1]
RewriteRule ^/xyz$  https://vip-name/xyz/bc/gui/xyz/language=EN$1 [R,L]
RewriteRule ^/xyz(.*) http://ip1:8085$0 [P,NC]
RewriteRule ^/(.*) http://ip2:8086$0 [P,NC]
</VirtualHost>


Como listar todos os followers de um perfil do usuário usando API do Github?

Question: Estou desenvolvendo uma aplicação em ReactJS que deveria me retornar uma lista com todos os seguidores de um usuário. No entanto, em um usuário com mais de 100 seguidores, meu código  retorna apenas uma array com, no máximo, 30 seguidores. Como faço pra listar todos eles e não apenas 30?
OBS: Estou usando ReactJS e Axios
const getUserData = event => {
  event.preventDefault();

  client.get(`/${loginValue}`)
  .then(response => {
    ctx.setUserData(response.data);
    nav('user');
  })
  .catch(err => console.log(err))

  client.get(`/${loginValue}/followers`)
   .then(response => {
     ctx.setFollowersList(response.data)
     console.log(response.data) //Retorna apenas 30 seguidores
  })
}

Comment: Por favor, esclareça seu problema ou forneça detalhes adicionais a fim de destacar exatamente o que você precisa. Da forma como está escrito atualmente é difícil dizer com exatidão o que você está perguntando.
Answer: Olhando a documentação da API do GitHub, podemos ver que essa requisição possui um parametro que define quantos usuários vão ser retornados por página. Esse limite é 30 por padrão, mas pode ser alterado para até 100.
O nome do parâmetro é per_page, então basta passar ele na sua requisição que você receberá até 100 usuários na resposta.
// Retorna 100 seguidores.
client.get(`/${loginValue}/followers`, { params: { per_page: 100 } })

Caso você queira continuar recebendo 30 usuários por página, mas das outras páginas, basta passar o parâmetro page.
// Retorna os próximos 30 seguidores.
client.get(`/${loginValue}/followers`, { params: { page: 1 } })

Link da documentação: https://docs.github.com/pt/rest/users/followers


What is an example of a map not satisfying this rank condition?

Question: Definition:
Consider a Lie Group $G$ and a set of right invariant vector fields on $G$, denoted $\Gamma$.
A point $y \in G$ is called normally accessible from a point $x \in G$ by $\Gamma$ if there exist elements $A_1, \ldots, A_k$ in $\Gamma$ and $\hat{t} \in \mathbb{R}^k$ with positive coordinates $\hat{t_1},\ldots,\hat{t_k}$ such that the mapping $F(t_1,\ldots t_k) = e^{t_kA_k}\ldots e^{t_1A_1}x$ as a mapping from $\mathbb{R}^k$ into $G$ satisfies the following conditions:

$F(\hat{t}) = y$
The rank of the differential $dF$ at $\hat{t}$ is equal to the dimension of $G$.

Source:
This definition is taken from 'Controllability of Invariant Systems on Lie Groups and Homogeneous Spaces' by Yu Sachkov.
My aim: I am trying to gain an intuitive understanding of the second condition.
Questions:

What is an example of a map of this form that does not satisfy condition 2?
Is there an example of condition 2 being violated for $k = 1$?
Answer: Rank
First note that the rank of the differential map $dF$ is the dimension of its image. It is an induced map between the tangent spaces of the domain and range of its associated map, $F$.
See: https://en.wikipedia.org/wiki/Pushforward_%28differential%29
What is an example of a map of this form that does not satisfy condition 2?
Consider the case where $x$ lives in an $n$-dimensional manifold such that $n \neq 0$, and where we trivially pick $\Gamma$ such that $A_1,\ldots, A_k = \mathbf{0}$. We ask if, in this case, $x$ is normally accessible from $x$.

$F$ maps all time values in its domain to $x$, so we can find some positive times such that condition $1$ is satisfied.
The equivalence classes of curves in $\mathbb{R}^k$ are mapped to the single point $x$. Hence the  rank of the differential map is $0$. We already set $n \neq 0$ therefore condition $2$ is not satisfied.

$x$ is not normally accessible from $x$ by $\Gamma$ in this case.
Is there an example of condition 2 being violated for k=1?
Let $k=1$ and therefore consider the equation:
\begin{equation}
 F(t) = e^{tA}x
\end{equation}
where $t \in \mathbb{R}$; $A \in \Gamma$; $x \in \mathcal{M}$ and $\operatorname{dim}(\mathcal{M}) = n$. Rephrasing condition $2$ we have the question: Is the differential map $dF(t)$ surjective?
First define curves in $\mathbb{R}$:
\begin{equation}
\begin{aligned}
 \sigma_t &: (-\epsilon,\epsilon) \to \mathbb{R} \\
 \sigma_t &: a \mapsto \sigma_t(a)
\end{aligned}
\end{equation}
where $\epsilon > 0$ and $\sigma_t(a)$ are curves such that $\sigma_t(0) = t$.
The tangent map on an equivalence class of curves in $\mathbb{R}$ acts like
\begin{equation}
 dF[\sigma_t(a)] = [e^{tA}x \circ \sigma_t(a)] \quad \text{for any } [\sigma_t(a)] \in T_t\mathbb{R}^k.
\end{equation}
The composition of these two maps is $e^{\sigma_t(a)A}x$, i.e. a curve in $\mathcal{M}$. With one generator the equivalence class of curves will form a one dimensional subvector space in the target tangent space. Hence the differential map will not be surjective for $n > 1$.


Rodar o comando shell_exec com UTF-8 em PHP

Question: Estou desenvolvendo um sistema em linguagem PHP e utilizo o comando shell_exec, porém quando retorno alguma mensagem com acentuação, ele não mostra o caractere.
Exemplo:
Comando: <?=shell_exec('tasklist /fi "pid eq '.getmypid().'" ')?>
Resultado:

Como printar a mensagem acima com UTF-8 ?
Answer: Você pode usar o setlocale para fazer isso. Desta forma:
$locale = 'pt_BR.UTF-8';
setlocale(LC_ALL, $locale); // LC_ALL informa que tudo abaixo deste código será configurado para pt_BR.UTF-8
putenv('LC_ALL='.$locale);
shell_exec('tasklist /fi "pid eq '.getmypid().'" ');

Edit
Estive dando uma pesquisada e descobri que o setlocale depende da configuração do servidor.
Se por acaso não funcionar com 'pt_BR', tente usar o 'en_US' que é o padrão de muitos servidores.
Você também pode usar variações, assim:
setlocale(LC_ALL, 'en_US.UTF-8', 'en_US.UTF8', 'en.UTF-8', 'en.UTF8');

Edit 2
Uma outra opção é usar o utf8_encode:
$saida = shell_exec('tasklist /fi "pid eq '.getmypid().'" ');
$saida = utf8_encode($saida);
echo $saida;

Tente desta forma também:
$saida = shell_exec('tasklist /fi "pid eq '.getmypid().'" ');
$saida = utf8_encode($saida);

foreach(mb_list_encodings() as $chr){
       $saida = mb_convert_encoding($saida, 'UTF-8', $chr);
}

Referencias:
Stackoverflow
Problemas com setlocale
Comment: Tem que mudar o locale do shell, não do PHP. Ou então, simplesmente pegar o resultado do shell e converter na exibição, que é muito mais simples (que é praticamente o final da resposta). Agora, antes de mais nada está faltando na pergunta alguma coisa confirmando o locale atual do shell.
Comment: Fiz essas alterações que você comentou e não funcionou, não me  retornou em UTF-8 a mensagem. Continua sendo exibido do mesmo jeito
Comment: @Piupz tem uma outra opção.
Comment: @Piupz tente com edit 2
Comment: Ele me retornou [assim](https://i.imgur.com/ClzwfxH.png), ainda não está em UTF-8 =/
Comment: @Piupz ok! O problema é que o servidor não está configurado para utf8. Vou ver se consigo fazer algo quanto a isso.
Comment: @Piupz da uma olhada na edição e veja se resolve agora.
Comment: @Bacco tem rasão. Acho que um `echo setlocale(LC_ALL, 0);` mostra qual é a locali.


Medir o uso de um código Python na CPU e Memoria

Question: Tenho um código e quero saber quanto que ele ta pegando do processador e da memoria.
Comment: Ctrl+Shift+Esc no Windows 10 e analise o processo python.exe
Comment: Este comando abre o Gerenciador de Tarefas
Comment: Mas lá ira mostrar os dados em tempo de execução?
Answer: Se não for utilizar gerenciador de tarefas, podes usar a biblioteca psutils
<code>import psutil

print(psutil.cpu_percent())                    # Em porcentagem, uso da CPU
print(psutil.virtual_memory()._asdict())       # Em dicionário informações de memória física
</code>
retorna, por exemplo:

14.2
OrderedDict([('total', 8272900096), ('available', 3767132160),
  ('percent', 54.5), ('used', 4505767936), ('free', 3767132160)])

Edit: Há uma abordagem por id de processo também, "um pouco' mais complexa caso essa não lhe agrade.


Python open() vs. .close()

Question: Regarding syntax in Python
Why do we use open("file") to open but not "file".close() to close it?
Why isn't it "file".open() or inversely close("file")?
Comment: `"file".open()` *seems wrong* to me - not all strings are valid files to open, so having `str.open()` just seems like poor design, whereas all strings can be `split()` etc.
Comment: It's a style thing. Functions that work with an object generally are methods of that object, but you need a way of generating the object in the first place...
Comment: It's not `"file".close()`, so `"file".open()` wouldn't match. I suppose it easily could have been `close(file_object)`.
Comment: I've added one word to your question that I think you left out by accident - feel free to roll back my change if that's not what you intended.
Comment: To close voters: this is not "primarily opinion based." There are sound technical reasons for syntax being the way it is.
Comment: Thanks for asking this, as I was about to myself
Answer: It's because open() is a function, and .close() is an object method. "file".open() doesn't make sense, because you're implying that the open() function is actually a class or instance method of the string "file". Not all strings are valid files or devices to be opened, so how the interpreter is supposed to handle "not a file-like device".open() would be ambiguous. We don't use "file".close() for the same reason.
close("file") would require a lookup of the file name, then another lookup to see if there are file handles, owned by the current process, attached to that file. That would be very inefficient and probably has hidden pitfalls that would make it unreliable (for example, what if it's not a file, but a TTY device instead?). It's much faster and simpler to just keep a reference to the opened file or device and close the file through that reference (also called a handle).
Many languages take this approach:
f = open("file") # open a file and return a file object or handle
# stuff...
close(f)         # close the file, using the file handle or object as a reference

This looks similar to your close("file") construct, but don't be fooled: it's closing the file through a direct reference to it, not the file name as stored in a string.
The Python developers have chosen to do the same thing, but it looks different because they have implemented it with an object-oriented approach instead. Part of the reason for this is that Python file objects have a lot of methods available to them, such as read(), flush(), seek(), etc. If we used close(f), then we would have to either change all of the rest of the file object methods to functions, or let it be one random function that behaves differently from the rest for no good reason.
TL;DR
The design of open() and file.close() is consistent with OOP principals and good file reference practices. open() is a factory-like function that creates objects that reference files or other devices. Once the object is created, then all other operations on that object are done through class or instance methods.
Answer: Only slightly less new than you but I'll give this one a go, basically opening and closing are pretty different actions in a language like python.  When you are opening the file what you are really doing is creating an object to be worked within your application that represents the file, so you create it with a function that informs the OS that the file has been opened and creates an object that python can use to read and write to the file.  When it comes time to close the file what basically needs to be done is for your app to tell the OS that it is done with the file and dispose of the object that represented the file fro memory, and the easiest way to do that is with a method on the object itself.  Also note that a syntax like "file".open would require the string type to include methods for opening files, which would be a very strange design and require a lot of extensions on the string type for anything else you wanted to implement with that syntax.  close(file) would make a bit more sense but would still be a clunky way of releasing that object/letting the OS know the file was no longer open, and you would be passing a variable file representing the object created when you opened the file rather than a string pointing to the file's path.
Comment: I have a couple of corrections I'd like to make to your explanation: The `open` function doesn't read your file into memory. `read` and `readlines` do that. Also, There isn't necessarily a "lock" on any files you open. It depends on how the operating system handles open file references. I understand what you meant, but I would avoid using the word "lock".
Comment: Thank you!  My MS background was showing through there and I forgot about the differences in how some OS's handle open file handles.  really appreciate the clarification and I've updated my answer.
Answer: Normally you shouldn't use "file".close() explicitly but use open(file) as contextmanager so the file handle is also closed if an exception happened. End of problem :-)
But to actually answer your question I assume the reason is that open supports many options and the returned class differs depending on these options (see also io module). So it would be simply much more complicated for the end-user to remember which class he wants and then use the "class".open with the right class itself. Note you can also pass "integer file descriptor of the file to be wrapped." to open, this would mean besides having a str.open() method you also get a int.open(). This would be really bad OO design but also confusing. I wouldn't care to guess what kind of questions would be asked on StackOverflow about that ("door".open(), (1).open())...
However I must admit that there is a pathlib.Path.open function. But if you have a Path it isn't ambiguous anymore.
As to a close() function: Each instance will have a close() method already and there are no differences between the different classes, so why create an additional function? There is simply no advantage.
Answer: In addition to what has been said, I quote the changelog in Python removing the built in file type. It (briefly) explains why the class constructor approach using the file type (available in Python 2) was removed in Python 3:

Removed the file type. Use open(). There are now several different kinds of streams that open can return in the io module.

Basically, while file("filename") would create an instance of file, open("filename") can return instances of different stream classes, depending on the mode.
https://docs.python.org/3.4/whatsnew/3.0.html#builtins

Python open() vs. .close()


How to prove this sequent using natural deduction?

Question: How do I prove
$$S\rightarrow \exists xP(x) \vdash \exists x(S\rightarrow P(x))$$
using natural deduction? Just an alignment of which axioms or rules that one could use would be much appreciated.
Comment: This is wrong as shown in the empty model with $S$ being false, where $S \to \exists x P(x)$ is true but $\exists x(S \to P(x))$ is false.
Comment: @KennyLau Natural deduction presumes a nonempty universe, both $(\forall x ~ \bot) \to \bot$ and $\top \to( \exists x ~ \top)$ are instances of inferences.
Comment: This seems like it isn't actually a constructively true statement.  Someone who knows kripke models can probably confirm.
Comment: @DanielV what does "constructively true" mean?
Comment: @KennyLau The short answer is "provable by constructive (intuitionistic) logic".  It is a type of proof where (among other things), statements of the form $\exists x ~ Px$ can only be proven by establishing an algorithm that constructs $x$, assuming all the assumptions are constructive as well.  So if you prove an $x$ exists, you can always demonstrate what that $x$ is.  Natural deduction without law-of-excluded-middle (or equivalent) is constructive.
Answer:
$S \to \exists x P(x)$ [P]

$S$ [A]
$S \to \exists x P(x)$ [1 R]
$\exists x P(x)$ [2.2 2.1 $\to$E]

$P(a)$ [A]

$S$ [A]
$P(a)$ [2.4.1 R]

$S \to P(a)$ [184.108.40.206 18.104.22.168 $\to$I]
$\exists x [S \to P(x)]$ [2.4.3 $\exists$I]

$\exists x [S \to P(x)]$ [2.3 2.4.1 2.4.4 $\exists$E]

$S \to \exists x [S \to P(x)]$ [2.1 2.5 $\to$I]

$\neg S$ [A]

$S$ [A]
$\neg S$ [4.1 R]
$\neg S \lor P(a)$ [4.2.2 $\lor$I]
$P(a)$ [4.2.3 4.2.1 $\lor$E]

$S \to P(a)$ [4.2.1 4.2.4 $\to$I]
$\exists x [S \to P(x)]$ [4.3 $\exists$E]

$\neg S \to \exists x [S \to P(x)]$ [4.1 4.4 $\to$I]
$S \lor \neg S$ [LEM]
$\exists x [S \to P(x)]$ [3 5 6 $\lor$E]

How to complicate everything, take #314159.
Comment: Note that 6 [LEM] is classical, and 4.4 [4.3 $\exists$E] assumes a non-empty universe
Answer: Here is a proof in the Fitch formal proof system:
Comment: @KennyLau Same answer: I'm not an expert in that particular area, but given as I saw no way to prove this without a proof by contradiction I don't think it is.
Comment: Is step 10 intuitionistic?
Comment: @KennyLau  I haven't really worked with intuitionistic logic, but from what little I gather about it, I believe step 10 would not be intuitionistic
Comment: Is this theorem intuitionistic?


Find continuous dates in PostgreSQL

Question: I am trying to solve one query which I have already solved in SQL Server.

Write a SQL query to find continuous dates appear at least three times.

SQLfiddle
Table: orders
*------------*
|   mdate    |
*------------*
|'2012-05-01'|
|'2012-05-02'|
|'2012-05-03'|
|'2012-05-06'|
|'2012-05-07'|
|'2012-05-10'|
|'2012-05-11'|
*------------*

SQL Server:
select
  mdate
from
(
   select
      mdate,
      count(gap) over (partition by gap) as total
  from
  (
    select
      mdate,
      dateadd(day, - row_number() over (order by mdate), mdate) as gap
    from orders
  ) t
) tt

where total >= 3

Result:
*------------*
|   mdate    |
*------------*
|'2012-05-01'|
|'2012-05-02'|
|'2012-05-03'|
*------------*

I cannot use dateadd() function in PostgreSQL so how can I achieve same result in it?
Answer: You can make an interval out of your ROW_NUMBER computation by CONCAT with ' day' and typecasting; then you can subtract that from mdate. Your query remains the same other than changing
dateadd(day, - row_number() over (order by mdate), mdate) as gap

to
mdate - concat(row_number() over (order by mdate), ' day')::interval as gap

Demo on SQLFiddle
Answer: In SQL Server, this would look like:
select mdate
from (select o.*,
             count(*) over (partition by dateadd(day, - seqnum, mdate)) as cnt
      from (select o.*,
                   row_number() over (order by mdate) as seqnum
            from orders o
           ) o
     ) o
where cnt >= 3;

In Postgres:
select mdate
from (select o.*,
             count(*) over (partition by mdate - seqnum * interval '1 day') as cnt
      from (select o.*,
                   row_number() over (order by mdate) as seqnum
            from orders o
           ) o
     ) o
where cnt >= 3;

The only difference is the date arithmetic.

Find continuous dates in PostgreSQL


Prove that the expression $5^{2n+1} \cdot 2^{n+2} + 3^{n+2} \cdot 2^{2n+1}$ is divisible by 19.

Question:
Prove that the expression
  $$5^{2n+1} * 2^{n+2} + 3^{n+2} * 2^{2n+1}$$
  is divisible by $19$.

I'll skip the basis step (as I have done last time) but I can conclude that it's only divisible by 19 for integers n ≥ 0 (or whole numbers).
II.
Assume that
$$5^{2k+1} * 2^{k+2} + 3^{k+2} * 2^{2k+1}$$
is divisible by 19. Then,
$$5^{2k+3} * 2^{k+3} + 3^{k+3} * 2^{2k+3}$$
is divisible by 19.
Now this is where I get lost, I try to "dismember" the expression to get
$$5^{2k}* 5^3 * 2^k * 2^3 + 3^k * 3^3 * 2^{2k} * 2^3$$
I also try to get it similar to to the assumption to make use of the said assumption yielding
$$5^{2k}* 5 * 5^2 * 2^k * 2^2 * 2 + 3^k * 3^2 * 3 * 2^{2k} * 2 * 2^2$$
$$5^{2k+1} * 5^2 * 2^{k+2} * 2 + 3^{k+2} * 3 * 2^{2k+1} * 2^2$$
$$5^{2k+1} * 25 * 2^{k+2} * 2 + 3^{k+2} * 3 * 2^{2k+1} * 2^2$$
$$50 * 5^{2k+1} * 2^{k+2} + 12 * 3^{k+2} * 2^{2k+1}$$
And this is where I get lost.. : (
Am I missing out something? Had I done it wrong? The number 19 is prime which makes it hard to handle for me. Thanks!
EDIT : After some pondering, I answered it this way :
$$50 * 5^{2k+1} * 2^{k+2} + 12 * 3^{k+2} * 2^{2k+1}$$
I realized that 50 can be written as 38 + 12 (and 38 is a multiple of 19) Hence,
$$ 38 + 12 * 5^{2k+1} * 2^{k+2} + 12 * 3^{k+2} * 2^{2k+1} $$
Factoring out 12, I get :
$$ 38 + 12(5^{2k+1} * 2^{k+2} + 3^{k+2} * 2^{2k+1}) $$
38 is divisible by 19 and the long expression is divisible by 19 (per the assumption) and qed.
Is this correct ?
Comment: Hint:  by Euler's Theorem $5^n\pmod {19}$ only depends on $n\pmod {18}$, thus in a worst case you only need to check $18$ cases.
Comment: Why you didn't solve it with congruence?
Comment: Related older question: [Prove divisibility by induction $19\mid 5^{2n+1}2^{n+2}+3^{n+2}2^{2n+1}$](https://math.stackexchange.com/q/1850992)
Comment: Hi everyone! Thanks for the answer and after putting some thought to your answers, I found a way that seemingly solves it. Is it correct ?
Answer: Without using induction
$$5^{2n+1}2^{n+2}+3^{n+2}2^{2n+1}=20\cdot50^n+18\cdot12^n$$
$$\equiv1\cdot12^n+(-1)\cdot12^n\pmod{19}$$  as $20\equiv1,18\equiv-1,50\equiv12\pmod{19}$
Comment: But this *does* use induction, e.g. the standard proof that $50\equiv 12\Rightarrow\ 50^n\equiv 12^n\,$ is by induction on $\,n,\,$ e.g. see the [Congruence Power Rule.](https://math.stackexchange.com/a/879262/242) Pushing the induction into a Lemma does not mean that you are not using induction.
Comment: @BillDubuque, Using Binomial Expansion, $$(a-b+b)^n=b^n+\sum_{r=0}^{n-1}\binom nrb^r(a-b)^{n-r}$$
Comment: The common proof of the Binomial Theorem is also by *induction* on $n.\ \ $
Answer: Because $$5^{2n+1}2^{n+2}+3^{n+2}2^{2n+1}=20\cdot50^n+18\cdot12^n=$$
$$=20(50^n-12^n)+38\cdot12^n$$ and since
$$a^n-b^n=(a-b)(a^{n-1}+...+b^{n-1}),$$
we are done!
Comment: https://math.stackexchange.com/questions/188657/why-an-bn-is-divisible-by-a-b
Answer: Hint:
$
5^{2n+1}  2^{n+2} + 3^{n+2}  2^{2n+1}
\\= 20\cdot 50^n + 18 \cdot 12^n
\\= 19(50^n + 12^n)  + 50^n - 12^n
\\= 19(50^n + 12^n)  + (2\cdot 19 +12)^n - 12^n
$
Answer: $$5^{2n+1}2^{n+2}+3^{n+2}2^{2n+1}=20(50)^n+18(12)^n\equiv-18(50)^n+18(12)^n\equiv-18(12)^n+18(12)^n\equiv0$$
Answer: $$5^{2n+1}2^{n+2}+3^{n+2}2^{2n+1}\equiv 5^{2n}2^n-3^n2^{2n}\pmod{19}\qquad (1)$$
since $5^12^2=20\equiv 1\pmod{19}$ and $3^22^1=18\equiv -1\pmod{19}$. Hence, $(1)$ yields the following
$$2^n(5^{2n}-3^n2^n)=2^n(25^n-6^n)=50^n-12^n\equiv 12^n-12^n\pmod{19}\equiv 0\pmod{19}$$
since $50\equiv 12\pmod{19}$.
Answer: Without congruences, subtraction, or factoring a difference of common powers:
Inductive assumption:
For some $n$, there is a $k$ such that
$5^{2n+1}2^{n+2}+3^{n+2}2^{2n+1} = 19k $
i.e.
$20(50^n)+18(12^n) = 19k$
For this $n$, add $980(50^n) + 198(12^n)$ to both sides.
The left-hand side will turn into the desired $(n+1)^{th}$ expression. The right-hand side is now
$19k+11[20(50^n)+18(12^n)]+38[20(50^n)]$
Here just use the inductive assumption again, and these terms will have a common factor.
Answer: First let's rewrite the expression so as to better highlight innate arithmetical structure.
$\ \ \quad\qquad\begin{align}
19\ \mid &\,\ 5^{2n+1} \cdot 2^{n+2} + 3^{n+2} \cdot 2^{2n+1}\\[.2em]
\iff\, \bmod 19\!:\, &\ \ \ \ \color{#0a0}{20}\cdot 50^n\, \equiv\, - \color{#0a0}{18}\cdot 12^n
\end{align}$
Now the induction is extremely simple if we view it arithmetically $\!\bmod 19,\,$ where it amounts to  multiplying the base congruence $\,\color{#0a0}{20}\equiv \color{#0a0}{-18}\,$ by the $\color{#c00}n$'th power of $\,50\equiv 12.\,$ In induction format
$\ \ \quad\qquad\qquad\qquad\begin{align}
\color{#0a0}{20}\, \ &\equiv\, \color{#0a0}{-18}\qquad\qquad\ {\rm i.e.}\ \ \ P(0)\\[.3em]
\color{#0a0}{20}\cdot 50^{\large\color{#c00} n} &\equiv\, 12^{\large\color{#c00} n}(\color{#0a0}{-18})\qquad\! {\rm i.e.}\ \ \ P(\color{#c00}n)\\
\times\,\qquad 50\ \ &\equiv\, 12\\[.2em]
\hline
\!\!\Longrightarrow\ \ 20\cdot 50^{\large\color{#c00}{n+1}} &\equiv\, 12^{\large\color{#c00}{n+1}}(-18)\ \ \ {\rm i.e.}\ \ \ P(\color{#c00}{n\!+\!1})^{\phantom{|^|}}\!\!\!\!\!
\end{align}$
The final congruence is the product  the two prior congruences using the Congruence Product Rule. In number theory we make such deductions by using  Congruence Product and Power Rules. The power rule encapsulates such arithmetical inductions for convenient reuse.  The inductive proofs in the other answers are in fact special cases of the proof of the Power Rule (e.g. see here where I highlight this in great detail).
We can simplify further using $\,\color{#0a0}{20\equiv 1,\ 18\equiv -1},\ 50\equiv 12\pmod{\!19}\,$ to obtain
$\qquad\qquad\qquad\qquad\qquad\begin{align}&\color{#0a0}{20}\cdot 50^n +  \color{#0a0}{18}\cdot 12^n\\[.2em]
\equiv\ &\ \ 1\cdot 12^n\  \color{#0a0}{-\ 1}\cdot  12^n\end{align}$
which effectively completely encapsulates the induction in the Congruence Power Rule.
Remark $ $ Even if you don't know congruences you can still take advantage of these arithmetical simplifications by using a version of the Product Rule in divisibility form as below
$$\qquad\qquad\begin{align} {\rm mod}\,\ m\!:\, A\equiv a,\, B\equiv b&\ \ \,\Longrightarrow\,\ \ AB\equiv ab\qquad\bf\text{Congruence Product Rule}\\[3pt]
m\mid A-a,\ B-b&\,\Rightarrow\, m\mid AB-ab\qquad\bf\,\text{Divisibility$\ $ Product Rule}\\[4pt]
{\bf Proof}\quad (A-a)B+a(B&-b)\, = AB-ab\end{align}$$


Misunderstanding of an exercise on topology?

Question: Let $\mathbb{R}$ be the set of reals with a topology $\mathcal{T}$ such, that each $x\in\mathbb{R}$ has a base of open regions
$$\mathcal{B}_x=\{\{x\}\cup\{y\in\mathbb{Q}:|x-y|<1/n\}\}_{n\in\mathbb{N}}$$

Show the space is seperable and $T_2$
Show that for each $x\in\mathbb{R}$ and $U$ open subset of $(\mathbb{R}, \mathcal{T})$ which contains $x$, there is an open set $V$ such that $x\in V\subseteq\overline{V}\subseteq U$. Then conclude that the space is $T_3$.
Show that the singleton $\{q\}$, where $q\in\mathbb{Q}$, and the set of irrationals $\mathbf{Irr}$ are closed and not separable by two disjoint open sets. Conclude that the space is not $T_4$.

My question is

How can this space be $T_3$ when, according to (3), for $q\in\mathbb{Q}$ and $\mathbf{Irr}$ (which is closed and does not contain $q$) there is no open set separating them? Isn't this exercise contradictory?
Answer: You are right, the exercise is contradictory. And the space is not $T_3$. For rational $x$, the closed neighbourhoods don't form a neighbourhood base.
If $x\in\mathbb{Q}$, take $U = (x-1,x+1) \cap \mathbb{Q}$. This is an open set, and every open set $x \in V \subset U$ contains $W_\varepsilon := (x-\varepsilon,x+\varepsilon)\cap\mathbb{Q}$ for some $\varepsilon > 0$. But $(x-\varepsilon,x+\varepsilon) \subset \overline{W}_\varepsilon$, whence $\overline{W}_\varepsilon \not\subset U$.
Comment: Exactly! This is what I was thinking, too, but I needed some confirmation to be sure.
Comment: For the record, I told this to my professor and he agreed that the exercise was wrong and the space is not $T_3$.


Hyper-V Client Network Dropouts

Question: Bit of a strange one I'm having that I can't work out.
The setup: Asus P8Z77-M Pro motherboard, 16GB RAM, Intel i7-3770 CPU, OCZ SSD, NVIDIA Quadro 2000 grpahics card (with RemoteFX on the client); running Windows Server 2012 Standard on bare metal with Hyper-V. One Windows Server 2012 Standard Domain Controller, one Windows 8 Enterprise client with 4GB of RAM allocated, and 1 virtual CPU.
Everything is running pretty well on the test client, except that every 1-5 minutes there is a network dropout on the local ethernet interface (on the client) that stops all connectivity. Typing catches up after this dropout is over.

Is this the network interface on the motherboard having a heart attack? Or am I doing something wrong? When testing flash videos on the client, the dropouts are more regular - even when playing local videos.
Any help would be greatly appreciated.
Comment: @joeqwerty - I have built a test machine to build some environments to help my learning of Server and Windows 8. I cannot afford a server class system, and am hoping to get knowledge out of the lower cost workstation class hardware...
Comment: Forgot to mention - this is on the LAN on a gigabite switch.
Comment: I'm sorry. I just can't take this question seriously if you insist on running a Server OS on workstation class hardware.
Comment: local videos wouldn't have anything to do with the nic unless they are on one of the other VMs, but it looks like you might be having one of those issues that pops up when you try to run servers on desktop hardware.  Truthfully, its likely the NIC driver on the Host OS.  It could also be that you have contention issues with CPU/RAM/HD/....  and those are causing your VMs to lock up..  if you run a constant ping, does it fail during the "outage"?  ping more than one device (Host OS/Router/Google etc) just to make sure.
Answer: Thank you to MikeAWood - it was a NIC driver. I had forgotten to update the network card drivers, as Microsoft installed the default ones and I didn't "need" to straight away.
Answer: I had an issue where my xRDP connection to the guest VM (Win10 pro host, ubuntu 20.04 guest) would dropout approximately once an hour then spontaneously recover after a minute. I switched the following setting to off: hypervmanager->[guestvm]->hardware->network->hardware acceleration -> VMQ (as recommended here: dmunified ) and my dropouts stopped.

Hyper-V Client Network Dropouts


Google Sheets Script Error - Cannot read property '1' of null (line 7)

Question: I'm using the following script to pull data from bulk json files:
function importRegex(url, regexInput) {
  var output = '';
  var fetchedUrl = UrlFetchApp.fetch(url, {muteHttpExceptions: true});
  if (fetchedUrl) {
    var html = fetchedUrl.getContentText();
    if (html.length && regexInput.length) {
      output = html.match(new RegExp(regexInput, 'i'))[1];
    }
  }
  // Grace period to not overload
  Utilities.sleep(1000);
  return output;
}

Then this formula with the desired URL in E3:
=IMPORTREGEX(E3,"(.*')")

It worked completely fine to begin with, now I'm suddenly getting the error, seemingly without making any changes, any tips?
Comment: `'` is not present in the response.
Comment: @idfurw you are right, thank you. Not sure how I accidentally added that without noticing!
Comment: Did the previous comment solve the issue? If so, please add-it as a solution or the user who mentioned to do it.
Comment: @Kessy How do I mark a comment as a solution?
Comment: You can post the answer yourself explaining the change to the code you did
Answer: This error is because of lacking a null check.
You are now using the return value of html.match() whether it is null or not.
So you should check if the return value is null and if it has enough length.
Like this:
if (html.length && regexInput.length) {
  let match = html.match(new RegExp(regexInput, 'i'));
  if ( match != null && match.length > 1 ){
    output = match[1];
  }
}


How should I report errors for aggregate data?

Question: I wish to "predict" the number of bugs my company will cause using a linear regression. For any given piece of development, the prediction is not great ($r^2 = .2$). However, my real task is to predict, company-wide, how many bugs we'll produce in a week. My errors are roughly zero-mean, so in this aggregated data set my $r^2$ is closer to .8.
How should I report this? My coworkers (and admittedly myself) are not terribly familiar with statistics, but if I say something like "20% of the variance is 'explained' by the model" that makes it sound as if there is a long way to go. If 80% is explained, that seems quite good.
Am I unfairly increasing my perceived correctness if I report the higher $r^2$ from the aggregate model?
Comment: You might appreciate reading about the [Ecological Fallacy](http://en.wikipedia.org/wiki/Ecological_fallacy).
Comment: @whuber: very cool, thanks! As seems to be the usual here, I get an answer to a question I didn't even ask!
Answer: As long as you make it clear what you are predicting (bugs in a given week rather than bugs in a given project), you should use the $R^2$ from the aggregate model.
It would be dishonest to present the model predicting the number of bugs in a given project but give the $R^2$ from the aggregate model, of course.


How can I create a programmatic Search API query which uses a date field

Question: I'm trying to create a programmatic Search API query. I've successfully created one which looks for all nodes which are published:
<code>  $index = search_api_index_load("node_index");
  $myQuery=new SearchApiQuery($index);
  $myQuery->condition('status', '1', '=');
  $data=$myQuery->execute();
  $results=$data['results'];
</code>
However the condition that I want to search for is to find all nodes with a certain date on a date field.
The problem is I can't work out how the Search API stores dates. I've tried UNIX time stamps:
<code>  $myQuery->condition('field_application_end_date', '1411084800', '=');
</code>
And the PHP date format that is stored on the nodes however neither returns any results.
<code>  $myQuery->condition('field_application_end_date', '2014-10-01T00:00:00', '=');
</code>
Can someone explain how the Search API stores dates?
I've been digging through the module to try and work out how it's done, but it's a little out of my league.
Answer: Try
<code>$myQuery->condition('field_application_end_date:value', '1411084800', '=');
</code>
Search API stores the dates as timestamps, so you're right there, but you forgot the 'value' after the field. If you want to use the 'to' date, use 'value2'.


BillingSecurity.verifyPurchase - what are is signedData and signature?

Question: I want to check in android inapp billing is a purchase has been made. I found this method...
<code>protected static void verifyPurchase(String signedData, String signature) {
    ArrayList<VerifiedPurchase> purchases = BillingSecurity.verifyPurchase(signedData, signature);
    Log.e("IN APP","purchases: " + purchases.toString());
}
</code>
Yet I can't figure out that should I put into signedData and signature? Tried itemid and base64EncodedPublicKey, doesn't work...
Thanks!
Comment: Did you figure out how to retrieve the signedData and signature?
Answer: For checking result of purchase you should use another method of class BillingPurchaseObserver:
<code>@Override
public void onRequestPurchaseResponse(RequestPurchase request,
        ResponseCode responseCode)
{
    Log.d("TAG", "onRequestPurchaseResponse");
    if (Consts.DEBUG)
    {
        Log.d("TAG", request.mProductId + ": " + responseCode);
    }
    if (responseCode == ResponseCode.RESULT_OK)
    {
        if (Consts.DEBUG)
        {
            Log.i("TAG", "purchase was successfully sent to server");
        }
    }
    else if (responseCode == ResponseCode.RESULT_USER_CANCELED)
    {
        if (Consts.DEBUG)
        {
            Log.i("TAG", "user canceled purchase");
        }
    }
    else
    {
        if (Consts.DEBUG)
        {
            Log.i("TAG", "purchase failed");
        }
    }
}
</code>
And purchaseStateChanged method in BillingService you shouldn't modify.
<code>/**
     * Verifies that the data was signed with the given signature, and calls
     * {@link ResponseHandler#purchaseResponse(Context, PurchaseState, String, String, long)}
     * for each verified purchase.
     *
     * @param startId
     *           an identifier for the invocation instance of this service
     * @param signedData
     *           the signed JSON string (signed, not encrypted)
     * @param signature
     *           the signature for the data, signed with the private key
     */
    private void purchaseStateChanged(int startId, String signedData,
            String signature)
    {
            //...
    }
</code>


Show that, for every non-empty subset A of [ n ] , there is an intersecting family F of subsets of [ n ] of size $2^{n − 1}$ with A ∈ F .

Question: Here is what I have understood this question as:
Every subset of [n] is contained in an intersecting family of size 2^n-1
This is my approach:
I took a set, X={1,2,3}
I list down all the subsets of X: {}, {1}, {2}, {3}, {1,2}, {2,3}, {1,3
}, {1,2,3}
Now, I take any one from the above, let us take {2,3}, and name it A
To build an Intersecting family containing A, I take any element from A, let us say, 3. I remove 3 from X and list down all the subsets of our new X: {}, {1}, {2}, {1,2}. I further add 3 to each of these sets, so I have now: {3}, {1,3}, {2,3}, {1,2,3}.
The above list forms an intersecting set containing A, and is of size 4(2^3-1).
In the same way, I can repeat the above steps for all subsets of X, and conclude the same solution.
I apologise for a naive question, but I would like to know if I am correct in this approach, and If I am, How should I approach for a mathematical proof?
Comment: Welcome to MSE. For some basic information about writing mathematics at this site see, *e.g.*, [basic help on mathjax notation](/help/notation), [mathjax tutorial and quick reference](//math.meta.stackexchange.com/q/5020), [main meta site math tutorial](//meta.stackexchange.com/a/70559) and [equation editing how-to](//math.meta.stackexchange.com/q/1773).
Answer: Welcome to this site. Is the following all you require or have I misunderstood your question?
Let $x$ be an element of a set $X$ which has $n$ elements.
The set $X-\{x\}$ has $n-1$ elements and therefore has $2^{n-1}$ subsets. Add $x$ back into each of these subsets to give us the required family.
Comment: Thankyou for your warm welcome. Absolutely, Once again, thank you.
Answer: Your arguing about the set $X$ is correct, albeit somewhat laborious. But $X=\{1,2,3\}$ is just a special case. Now you have to extend your argument to the general setup in the question; then erase the proof concerning $X$.
You are given a nonempty subset $A\subset[n]:=\{1,2,\ldots, n\}$. Choose a number $a\in A$ and consider the family
$${\cal F}:=\bigl\{X\subset[n]\bigm| a\in X\bigr\}\ .$$
Comment: Thankyou Christian, It solves my problem very efficiently


How is Vsus7 written in Roman numbers if 1st inversion? (any seventh chord with sus4)

Question: I'm analyzing a fugue in G-minor (BWV 105) by Bach that starts with Gmsus4 la-re-mi-so (G-C-D-F) 1st inversion (re-mi-so-la =C-D-F-G). I wonder what the R.N. assignment will be ...
The Thorough bass notation I think is i246, yes?
Is this the same for the analysis in Roman numbers? i246?
In the 2nd example we have Dm4 (Bassnote=4=G)
In the full score we have the root chord in the accompaniment. (1st example)

the 2nd example is like my question asks:
G=4, then D,A,D, and even C (Alt)
Comment: So you're asking about the first two beats of the second measure in the image?
Comment: Posting the full score changes everything. Highly recommend getting rid of the first two images, which only confuse the question.
Comment: Please add an indication of where the chord occurs in the images posted.
Comment: I don't know how to draw in there. It's the 1st tied note in the bass line. I thinks the question could be answered even without notation examples. e.g. V7sus4 in C: GCDF,   3rd inversion CDFG, oh sorry, it's the 1st inversion. CDFG!
Comment: Yes, I've edited the question. (it was so confusing to inverse the simple notation: the sus4 is in the bass voice.)
Comment: Deleted! As you can see it's the 5th-fall progression. Very nice music, btw.
Comment: See the linked question. The Roman numeral and figured bass (i.e. intervals) should be considered separately. So the Roman numeral would reflect the chord of resolution, and the figures would reflect the actual intervals present above the bass.
Comment: Again, Aaron, apologize  for wasting your time. Yes, but the link says its confusing .... http://www.sfcmtheory.com/harmony_supplements/chap_21.htm
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/119829/discussion-between-aaron-and-albrecht-hugli).
Comment: Thank you, Aaron.  (I've been out). No need to chat, everything is clear now.
Comment: Actually, I thought all the comments would get moved to chat. Anyway, I gather you saw my message there. Cheers.
Answer: In the second example (-ger ge-recht, vor dir wird) without accounting for the suspension I think it would be...
Gm: ...V V4/2 | i6 Dm: IV V4/2 | i6...
...the suspension is in the bass at Dm: i6
I thought the usual way to analyze it is with suspension figures above the Roman numerals...

    4-3
Dm: i6

If that were given without a score, I think it might take a bit of thought to understand the meaning: a i chord, first inversion, third is in the bass, but the bass is suspended at the fourth above the root prior to dropping down to the third to give a normal 6/3 chord.
Also, I thought in other posts we have seen the figured bass part of Roman numeral analysis would take the figures for the intervals above the bass, and I think that for this example it would be...
Dm: i5/2 i6/3


Iphone application store url in application

Question: My iPhone application does some processing on a server, and I save the url in a core data database so that every time the application is run I can read the url value from the database.
My issue is: if this url value changes, my application will stop working.  How can I get the url value dynamically without storing it in a database so that if url is changed, my application will continue working?
Comment: I'm sure you've got a good reason to be saving this in the Core Data, only, with the little info you've divulged about your app, I'm pretty worried you're not going about this in the right way.
Answer: You could get get it from any server, open a NSURLConnection class reference and read the response. So basically at the beginning your app would always check with the server to make sure it has the latest URL.


Large pairwise coprime sets

Question: Say that a set $S\subseteq\Bbb N$ is pairwise coprime if every two elements of $S$ are relatively prime. Denote by $f(n)$ the size of a maximal pairwise coprime subset of $\{1,...,n\}$.

What is the asymptotic behavior of $f(n)$ as $n\rightarrow\infty$?

I think I can prove that $f(n)=o(n)$, but that's about what I know.
No context for this question, just something I was thinking about today.
Thanks in advance.
Answer: For every prime $p\le n$, there is at most $1$ number in $S$ divisible by $p$.  So taking $S$ to be $1$ together with all the primes $\le n$ maximizes the size of $S$ subject to pairwise coprimality. Now the Prime Number Theorem gives us the asymptotics.
Remark: One can characterize all maximum-sized  subsets $S$ of $\{1,2,\dots,n\}$ such that any two distinct members of $S$ are coprime. Such an $S$ must consist of $1$, and for each prime $p\le n$, some power of $p$ that is $\le n$.
Comment: In particular we have $f(n)=\pi(n)+1$.
Comment: Really nice answer, I wonder how I've missed that :P

Large pairwise coprime sets


Chain rule in matrix derivation

Question: I am having trouble differentiating $\frac {\partial(tr(AX^{-1}))}{\partial X}$. If I understand, how chain rule works in matrix derivation (if it works at all), then I'm getting this result: $$\frac {\partial(tr(AX^{-1}))}{\partial X} = \frac {\partial(tr(AX^{-1}))}{\partial (X^{-1})} \frac {\partial(X^{-1})}{\partial X}$$
which, using matrix cookbook, particularly equations (101) and (59), gives me $$\frac {\partial(tr(AX^{-1}))}{\partial (X^{-1})} \frac {\partial(X^{-1})}{\partial X} = A^TX^{-2}$$
This is the answer I get, but I'm not sure at all that that is how it works.
Comment: a particular case is easier : if $ \|Y\| < 1$ (the operator norm $\|Y\| = \max_{\|v\|=1} \|Y v\|$) then the series $\sum_{k=0}^\infty Y^k$ converges and is equal to $(I-Y)^{-1}$. hence $\frac{\partial (tr(A (I-Y)^{-1}))}{\partial Y} = ?$
Comment: @user1952009 I'm sorry, but I don't think I follow, what does this give. Also, I don't have any such guarantees.
Comment: since $I$ is constant, $\frac{\partial}{\partial (I-Y)}$ and $-\frac{\partial}{\partial Y}$ is the same. hence if $X = I-Y$ with $\|Y\| < 1$ ... and what I wanted to show you is that even if you are treating matrices, you can write the Taylor expansion $((I-\epsilon Y)M)^{-1} = M^{-1} (I-\epsilon Y)^{-1} = M^{-1} \sum_{k=0}^\infty \epsilon^k Y^k =  M^{-1} + \epsilon M^{-1} Y + \mathcal{O}(\epsilon^2)$
Answer: Write the function in terms of the Frobenius (:) Inner Product and take its differential
$$\eqalign{
 f &= {\rm tr}(AX^{-1}) = A^T: X^{-1} \cr\cr
df &= A^T: dX^{-1} \cr
   &= -A^T: X^{-1}\,dX\,X^{-1} \cr
   &= -X^{-T}A^TX^{-T}:dX \cr
}$$
Since $df=\big(\frac{\partial f}{\partial X}:dX\big),\,$ the gradient must be
$$\eqalign{
\frac{\partial f}{\partial X} &= -X^{-T}A^TX^{-T} \cr
}$$
Comment: Thanks for the help. I'll be honest, I've never encountered Frobenius inner product.

Chain rule in matrix derivation


Views help from Advanced Help isn't being displayed or I can't find it

Question: It turns out that I actually hadn't installed Advanced Help on this Drupal setup and was only using regular 'Help'
I'm using Views 7.x-3.5 (API version 3) and Drupal 7.17
I installed Advanced Help (some time ago now) and cleared all caches
When I go to /admin/help I see a list of the following...
<code>Help topics

Help is available on the following items:

Administration menu
Advanced User Management
Block
CKEditor
Color
Comment
Content Access
Contextual links
Dashboard
Database logging

Date
Field
Field SQL storage
Field UI
File
Filter
Help
Image
List
Menu

Menu Block
Node
Number
Options
Path
Pathauto
RDF
Rules
Rules Forms Support
Search

System
Taxonomy
Text
ThemeKey
Token
Trigger
User
Webform
</code>
The following is constantly displayed in structure > views

If you install the advanced help module from http://drupal.org/project/advanced_help, Views will provide more and better help. Hide this message.
Comment: The module you need to install is called _Advanced Help_, not _Advanced Views_
Comment: Sorry, yes I'm getting myself confused here, must not have been using Advanced Help at all!
Answer: Install the advanced help module

When this module is installed, users with the view advanced help index
  permission can access the advanced help index by going to Administer
  -> Advanced Help (http://www.example.com/admin/advanced_help). Additional view advanced help popup and view advanced help topic
  permissions enable them to access the actual help pages and popups.
Comment: Thanks, yeh I think I'm getting myself confused here. Cheers - must not have been using Advanced Help at all!


Como posso obter acesso a objetos deletados no Django?

Question: Estou desenvolvendo um sistema de gerenciamento de estacionamento no Django que registra o objeto 'Veículo' de acordo com seu tempo de entrada, e calcula o valor à medida que sai, porém necessito desenvolver um sistema de relatórios que retorne quantos carros entraram e o valor total do dia.
Como posso obter acesso aos veículos que deixaram o estacionamento, pois após o registro de saída, o objeto é excluído no banco de dados.
<code># models.py
class Veiculo(models.Model):
    marca = models.CharField(max_length=100, null=False)
    modelo = models.CharField(max_length=100, null=False)
    cor = models.CharField(max_length=50, null=False)
    placa = models.CharField(max_length=8, null=False)
    horario = models.DateTimeField(auto_now_add=True, null=False)

    def __str__(self):
        return self.placa

class ValorEstacionamento(models.Model):
    periodoManha = MoneyField(max_digits=14, decimal_places=2,
                              default_currency='BRL', default='2')
    periodoTarde = MoneyField(max_digits=14, decimal_places=2,
                              default_currency='BRL', default='3')
    periodoFDS = MoneyField(max_digits=14, decimal_places=2,
                            default_currency='BRL', default='2.5')

    def __str__(self):
        return "Tabela de Valores"
</code>
<code># views.py
class EntradaCreateView(CreateView):
    model = Veiculo
    form_class = InsereVeiculoForm
    template_name = 'entrada.html'
    success_url = reverse_lazy('sistema:veiculos')

class VeiculosListView(ListView):
    template_name = 'veiculos.html'
    model = Veiculo
    context_object_name = 'veiculos'

def saida(request, placa):
    veiculo = get_object_or_404(Veiculo, placa=placa)
    veiculo.delete()
    return render(request, 'index.html')
</code>
<code># forms.py
class InsereVeiculoForm(forms.ModelForm):

    class Meta:
        model = Veiculo
        fields = [
            'marca',
            'modelo',
            'cor',
            'placa',
        ]
</code>
Comment: Falta dados, cadê a classe de entrada de veículos e saída de veículos
Comment: Realizei a entrada e saída dos veiculos na `views.py`
Answer: Para consultar estes dados, você precisara registra-los em algum lugar. Sugiro que, ao invés de deletar o veiculo após a saída, apenas o "desative", você pode adicionar um atributo "ativo" do tipo boolean em sua model, deste modo, você irá inativar o carro marcando o atributo como True ou False. Caso deseje fazer de um modo um pouco mais trabalhoso, porém, mais correto, você pode criar uma nova model onde você registrará as entradas e saídas do veículo, deste modo, o registro sempre estará em sua tabela de veículos, e, em outra tabela, você irá registrar apenas a data da entrada e data da saída daquele veículo vinculado o mesmo neste registro através de uma chave estrangeira.
Comment: Deixa eu ver se entendi... Para o Registro da Data, devo criar uma `class Data(models.Model):` que recebe o `data_entrada = models.ForeignKey(Veiculo, on_delete=models.CASCADE)` e `data_saida = models.DateTimeField(auto_now_add=True)`. E para o Registro de Entrada e Saida do veículo, eu não entendi muito bem como estruturar o modelo.
Comment: Você vai criar uma class Data como disse, e criara algo do tipo:

data_entrada = models.DateTimeField('Data de entrada', auto_now_add=True)
data_saida = models.DateTimeField('Data de saída', auto_now=True)
veiculo = models.ForeignKey('nomeDaApp.Veiculo', on_delete=models.PROTECT)

Assim você criará sempre um novo registro temporal de entrada e saída vinculado ao veiculo de modo que você só precisará cadastrar o veículo uma única vez, porém, poderá registrar várias entradas e saídas.


Want to create Android application project with min required sdk of API8

Question: Whenever I do this I receive the error "This template requires a build target API version of at least 14, and the current version is 8" but my Android project needs min sdk of API8, how can I manage this?
Thanks in advance.
Answer: There are some restriction in version 8 that some default android method or classes you can not use and after that updated version came and that restriction are gone.
So your error clearly say's that you have to use android:minSdkVersion="14". If you want to use android:minSdkVersion="8" then you must have to remove some method's or some part of code that is causing this issue.
It's not easy to tell you anything without your code that what actually causing the issue. But by seeing your question and by this line This template requires a build target API version of at least 14, and the current version is 8 I am pretty much sure that you must have to use android:minSdkVersion="14"
Hope this is gonna help you.  Still further if you have any doubt you can comment me.
Answer: You don't say which item was causing the error, but in general you can often get around a minimum API issue by using one of the support libraries. There are several different ones based the desired minimum API and the newer feature wanted. There's a list of libraries and the features they support here and some usage instructions here.
Answer: Open project.properties file
then set target=android-21


Local Approximation of Real Valued Functions

Question: I'm unsure where to begin. Any guidance would be greatly appretiated. Suppose that the function $f:\mathbb{R}^2\rightarrow\mathbb{R}$ has continuous second order partial derivatives, and at the origin (0,0) suppose that $\frac{\partial f}{\partial x}(0,0)=0$ and $\frac{\partial f}{\partial y}(0,0)=0$. Let $h$ be a nonzero point in the plane $\mathbb{R}^2$ and suppose that $\langle\bigtriangledown^2f(0,0)h,h\rangle>0.$ Use single-variable theory to prove that there is some positive number $r$ such that $f(th)>f(0,0)$ if $0<|t|<r.$
Answer: Hint: Calculate the second derivative of $g(t)=f(th)$, and recall the criteria for local extremal points in one variable.


How to return the parent on a one-to-many association?

Question: Rails 3.0.4
Given the following relationship
class Child < ActiveRecord::Base
  belongs_to   :parent
end

class Parent < ActiveRecord::Base
   has_many  :children
end

Using
@parents = Parent.find(:all, :include => :children)

Will return every parent with its children.
How can each child also include a reference to its parent so that can be used during serialisation?
E.g. in a JSON format that would look like:
[
    {
        "parent": {
            "created_at": "2012-05-05T11:29:19Z",
            "id": 1,
            "updated_at": "2012-05-05T11:29:19Z",
            "children": [
                {
                    "created_at": "2012-05-05T11:35:05Z",
                    "id": 1,
                    "updated_at": "2012-05-05T11:35:05Z",
                    "parent": {
                        "created_at": "2012-05-05T11:29:19Z",
                        "id": 1,
                        "updated_at": "2012-05-05T11:29:19Z"
                    }
                }
            ]
        }
    }
]

Answer: You should override to_json method on Child model:
class Child
  belongs_to :parent

  def to_json
    attributes.merge(parent: parent.attributes).to_json
  end
end

Answer: @parents = Parent.find(:all, :include => {:children => :parent})


How to remove scrollbar in popup form

Question: This is my code:
<!DOCTYPE html>

        <link rel="stylesheet" href="http://www.jacklmoore.com/colorbox/example4/colorbox.css" type="text/css" media="screen"/>
        <link rel="stylesheet" href="CSS/bootstrap.css" type="text/css" media="screen"/>
        <link rel="stylesheet" href="CSS/bootstrap-theme.css" type="text/css" media="screen"/>

External Form

            Please fill out my form.

                        <object type="text/html" data="https://ss88.wufoo.com/forms/rmndx1a0zzpe4m/" style="width:640px;height:730px;">
                        </object>

when run this code in localhost, it works fine. When applying my site it will show scrollbar, I adjust width for corresponding CSS style, still stays scrollbar, May I know how to fix this?
Comment: you can use overflow : hidden property of css
Comment: may i know where is exact palce to add?
Comment: ok, it removed, but  content is not visible on the end.
Comment: If you have done overflow : hidden content will be hidden
Comment: ok, then to display the whole content, either you have to increase the height of your container or you have to show scroll for showing all the content
Comment: @SandeepPal: I i have added overflow-hidden in custom.css in container, so now look like this http://imgur.com/mSAcIEE
Comment: read docs for how overflow property works. if u have set fixed height of element and set overflow hidden, then if content have bigger height that u provide, part of content will be hidden.
Comment: not set, height:fixed
Answer: Problem with overflow:hidden would be that it would hide the details from your form and depending on the screen size, different users will see different counts of columns in the form as teh overflowing content has been hidden.
What i would suggest is that you use  Media Queries  on you pop up page and reduce the size (read height) of item in you form
Something like this would be my suggestion :
@media only screen and (min-device-width : 320px) and (max-device-width : 480px) {
  .form-textbox, .form-textarea {
       width: 250px;height:20px /* dummy size, use you own */
   }

}

@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) {
  .form-textbox, .form-textarea {
     width: 250px;height:20px  /* dummy size, use you own */
  }

}

Good Read on Media Q :  Smashing Magazine
Answer: Try this

            <object type="text/html" data="https://ss88.wufoo.com/forms/rmndx1a0zzpe4m/" style="width:640px;height:730px;">
            </object>

Comment: Its working fine in localhost, but in my site shows scrollbar. I have added overflow hidden in custom.css, it removed, but content will be cut on the right side, look like this imgur.com/mSAcIEE
Comment: `overflow:hidden` always hides the mess, miss...not cleans it!! :)
Comment: @NoobEditor I know that and i have already said that in comment
Answer: Set overflow as hidden

Answer:

Demo
Comment: `overflow:hidden` always hides the mess, mate...not cleans it!! :)

How to remove scrollbar in popup form


Existe alguma vantagem em evitar redundância de especificação de tipos?

Question: Dado o seguinte código:
public override Entidades.ControleAcesso.Perfil PreencherEntidade(IDataReader dr)
        {
             return  new Entidades.ControleAcesso.Perfil()
                        {
                            Codigo = FieldSafer.Safe<int>(dr["someCol"], 0),
                            Nome = FieldSafer.Safe<string>(dr["someCol"], "nothing"),
                            PerfilFuncionalidade = new List<PerfilFuncionalidade>(),
                            StatusRegistro = FieldSafer.Safe<StatusRegistroEnum>(dr["someCol"], StatusRegistroEnum.Ativo),
                        };
        }

Onde FieldSafer =
public class FieldSafer : MinhaClasseBase
    {
        private T ObjectSafe<T>(object field, T defaultValue)
        {
            return GetSafeField<T>(field, defaultValue);
        }

        public static T Safe<T>(object field, T defaultValue)
        {
            return new FieldSafer().ObjectSafe<T>(field, defaultValue);
        }
    }

sofro no caso de uma redundância aqui:   Codigo = FieldSafer.Safe<int>(dr["someCol"], 0),
onde deixo explicito o meu Safe<int>, onde poderia ser automaticamente suprimido por Safe(dr... sendo que o retorno (defaulValue) é um inteiro.
é Correto suprimir redundância de tipos? ou para facilitar o entendimento é melhor deixa-los explícitos?
Comment: esses metodos fazem o que? pega um DataReader e tranformar em um Tipo de classe ? se puder responder ?
Comment: Desculpe a demora, Sim, esses métodos recebem o retorno do Banco de Dados e transformam em um objeto
Comment: Eu tenho uma rotina que tranformar dados que vem do Banco lidos por um datareader é uma lista, se quiser trazer um item também funciona ... se você achar legal te passo como resposta! @okevinlira
Comment: Poste como Reposta @FCCDias é bom ter outra opiniao para avaliar também. Particularmente existem outras maneiras de se fazer isso, mas nao posso alterar essa estrutura a pedido de meu cliente ;)
Answer: Nos casos apresentados, como o valor sendo passado é um literal, é muito fácil perceber qual tipo será inferido pelo C#... então nesse caso, eu com certeza removeria a especificação do tipo da chamada genérica.
Em outros casos em que há maior complexidade do valor sendo passado, dependendo da situação, talvez seja melhor deixar os tipos explícitos.
Particularmente, eu nunca deixo os tipos especificados quando eles podem ser inferidos pelo compilador, pois o Visual Studio permite saber qual é o tipo, simplesmente passando o mouse sobre o método.
Em termos de performance, não existe diferença, pois quando o compilador infere o tipo, é como se você tivesse especificado o tipo... o resultado compilado será o mesmo. Ou seja, a diferença é apenas visual.
Comment: Cara.. se tu soubesse como vc foi ninja agora, editando exatamente o que eu iria perguntar :P
Comment: Hehe... esqueci de responder a parte principal da pergunta: o título! Mas agora acho que tá tudo certo e coerente. =)


Change an Applications and Services Logs log path using GPO

Question: I am wanting to change the AppLocker Log path by a GPO.  The specific log is found at Event Viewer \ Applications and Services Logs \ Microsoft \ Windows \ AppLocker \ EXE and DLL.
I know you can change Application, Security, Setup, and System by setting Computer Configuration \ Administrative Templates \ Windows Components \ Event Log Service, but I can find one for the below section.
Manually changing isn't an option since we are using Citrix Provisioning Services and don't want to save it into the image.
Answer: According to this link it is not actually possible to change the path of the AppLocker log file.
The suggested answer from the Microsoft moderator seems to be to utilize Event Forwarding and Collecting. At least one achieves a degree of flexibility in the adding of a new location for the same log events.


How to properly specify context for Drupal behaviours

Question: I have this code that does not work. I know why it does not work - first time page is loaded 'context' is all page and jquery easely finds '.view-SPECIFICVIEW .view-content'. After AJAX 'context' has changed and it is now just '.view-SPECIFICVIEW' and inside that there is no class '.view-SPECIFICVIEW' and therefore nothing happens. Script works if I remove '.view-SPECIFICVIEW' from find(), but then all views are selected.
(function ($, Drupal, window, document, undefined) {
    Drupal.behaviors.MYMODULE = {
      attach: function(context, settings) {
        $(context).find('.view-SPECIFICVIEW .view-content').masonry({
          columnWidth : 300,
          gutterWidth : 20
        });
      }
    }
})(jQuery, Drupal, this, this.document);

I would like to have this code to work with '.view-SPECIFICVIEW' and also I would like to know how code changes if multiple, different specific views should be targeted.
Answer: Just stop using context in this case.  I've been playing around with jQuery Masonry and I've not needed to use it.
(function ($){
  Drupal.behaviors.myModule ={
    attach: function(context, settings) {
      $('.view-SPECIFICVIEW .view-content').masonry({
        columnWidth : 300,
        gutterWidth : 20
      })
    }
  }
})(jQuery);

FYI, I'd also take a look at the Masonry recommendation to use the imagesLoaded plugin if there are images in your view.  It takes a LOT of future frustration out.
Comment: You mean I should use attach as `attach: function()` without context and settings? Masonry is absolutely not important in this case.
Comment: You can pass context and settings through, but if you're not using them there seems little point.  I'm just saying, rather than use `$(context).find` just use  `$('.view-SPECIFICVIEW .view-content')`
Comment: `.find()` is also an extra function call, so I'd imagine it's slightly slower.  It's probably negligible though.
Comment: Ok, tested. Thanks. "Just stop using context" appears to be correct answer.
Answer: Give this a try, Context acts as "live" so doing it this way will attach it to each instance of view-SPECIFICVIEW (this is if I understand what your asking)
(function ($, Drupal, window, document, undefined) {
    Drupal.behaviors.MYMODULE = {
      attach: function(context, settings) {
        $('.view-content',context).each(function(){
         /* ADD CODE HERE */
        });
      }
    }
})(jQuery, Drupal, this, this.document);

Comment: Main problem is that there is no `.view-SPECIFICVIEW` in context after AJAX. context IS `.view-SPECIFICVIEW`. Im still waiting for a chance of real world test, any hour now.


SciKit Learn get feature importance for multiclass classification using Decision Tree

Question: I am using Scikit-learn for a multiclass classification task and would like to find out what are the most important features for each class. I have three classes (say class_a, class_b and class_c), and achieved Cross Validation scores of around 70% using Decision Tree classifier.
There is a feature_importances_ attribute in DecisionTree which allows me to find out the feature importance of each feature. However, how can I tell which feature is important for which class? I know that the feature importance is computed by the Gini score, but how do I know if a certain feature with a high score is important to distinguish say class_a from class_b and class_c? or is my understanding of feature importance completely wrong?
I would appreciate it very much if someone could shed some light on this. I have been poring over Scikit learn documentation and other sources but couldn't seem to find an answer to this, which makes me suspect there are some flaws in my understanding.
Thank you!
Answer: You could modify your problem by using multiple one-vs-rest classifiers.
For example train a classifier to distinguish between (1) class_a and (2) rest.
Then you can access the feature importance. Nonetheless, the feature importance is not the importance of a feature for a certain class, but a measure for the usability of a single feature to distinguish two classes (here one-vs-rest).
Therefore your the feature importance attribute does not answer the question "Which feature is important for a class?" but rather answers the question "Which feature helps best at distinguishing class_a from other classes present".
Comment: that makes a lot of sense. I will try that and comment if I have any further questions. Thank you very much!


Putting guitar and song together

Question: So, I'm still working on this.
I started singing with my playing using hey ya as my first song.  (In fact that was the first song I ever played)
Ironically I always lose it at the verse that goes

you think you've got it, oh you think you've got it
but got it just don't get it
till there's nothing at aaaaaaalllll-

The hardest part to get was the words and the strums together.  In particular the words of hey ya seemed off-beat (the words of each verse start AFTER the first downstroke).
Any tips for putting song and words together, particularly easy songs to sing and play?
Answer: I think there is only one answer: you must get the strumming down so solid, that your brain would have no need to focus on it. Then you can be free to focus on singing. You cannot focus on two things at one time.
Practice you strumming until it becomes fully automatic - then it will become possible to sing over it.
edit:
About easy songs: try Nothing else matters by Metallica using easy strumming, as explained at the beginning of this video: http://www.youtube.com/watch?v=d4ajO43l2sw
Comment: @bobobobo, yes, sorry, added one :)
Comment: How about easy songs to sing and play?
Answer: I've had some pretty intense lines to run whilst singing. Personally I've found that it is best to have the lines (strumming, picking, slapping) down as solid as possible.
What works when that bit is in the muscle memory, is to practice sections of the song, start bits and pieces, or lines, and layer them over piece by piece.
If this doesn't work for you. Record yourself playing the piece, then get the vocal time right over your playing and possibly repeat the previous step.
With regards to strumming specifically, see if you can get a songbook of oldies that you love. Work through them.
Metronomes help! When practicing I consider that law. :)
A good alternative to a metronome - if you don't like the consistency or repetitive tone of it - get the Hydrogen drum machine software. It's free. Very easy to setup loops or even songs (loop collections). There is a linux and Windows version available.

I find this ideal. Enjoy!
Answer: I've found that playing and singing along with a recording helps, especially if you can slow down the recording.  Start by just playing along, and then add simple singing (humming, or singing just the first word of each phrase, for example).
Answer: In my experience you just have to get comfortable enough that you can do other things while you play: talking to your friend, watch tv w/o missing a beat etc. It's a bit of a stretch when you first start but once you really get your muscle memory in place and master playing a song you should notice that you can carry conversations, sing etc while playing.
One practice technique i've used is to take advantage of my time in the car. While driving i'll turn on some music and either slap my my knew or steering wheel with the strumming pattern of the guitar and sing along while trying to keep in band with the guitar's strumming pattern.
Things like that go a long way - you can practice certain things w/o your guitar; Keeping a strumming pattern and vocal pattern separate in your head is one of those things... well, for me.

Putting guitar and song together


How to fix "django.core.exceptions.FieldError:" when querying with "_startswith" filter in django views?

Question: I am trying to get a queryset where the username starts with some name.
I have implemented the following code :
def searchUsers(request):
    if request.is_ajax():
        uname = request.GET['name']
        print(uname)
        user = User_Master.objects.filter(username_startswith = uname.title())
        usr_jsn = json.loads(serializers.serialize('json', user))
        return JsonResponse(usr_jsn)

Ajax call is succesfully running and I'm getting the searchkeyword printed in terminal.
But the error I'm getting is because of "_startswith" filter. This is the part from traceback.
django.core.exceptions.FieldError: Cannot resolve keyword 'username_startswith' into field. Choices are: contact_no, created_at, created_by, department, email, id, industry_segment, password, status, updated_at, updated_by, username

I have searched for my problem but none of the solutions worked.
Comment: You need two underscores: `username__startswith`.
Answer: it should be dundee(__) double underscore for lookups
user = User_Master.objects.filter(username__startswith = uname.title())

Comment: Oh man, thankyou so much .... I guess working continuosly exhausts your mind :p .... How can i be so stupid. I even checked the documentation and still couldn't figure it out. Much appreciated


"Decade" variable ranging over 130 years - Can I treat this as continuous? I've seen it done with 8pt scales...but it doesn't past the smell test

Question: My dataset includes "decade founded" but not "year founded" for organizations. I need to include some "maturity" variable in the model. Decade is the best I have. The span is 130 years, so over a dozen categories.
How do I treat decade?
I've enjoyed trying to find an answer. I now know a lot more about year variables and their treatments. But I can't find a good answer for decade. A colleague said I should just treat decade as continuous, because it has "enough" categories. I need a better rationale behind any approach I take. I'm a stickler for knowing "why" ;)
Comment: The number of categories (meaning, distinct possible values) is not a sufficient criterion for being continuous (or more important in your likely context -- interval scale). The number of countries is about 200 or more, but that doesn't make country even numeric. The number of children in a family is rarely more than 10 but it's fine as a quantitative variable with an interval scale. Decade is manifestly not continuous, as it's an integer (with an arbitrary origin too), but it is quantitative and interval scale.
Comment: Suppose the date founded was given to the nearest microsecond -- but you have data for just 13 organizations.  How would that affect your considerations?  And if it does, what exactly is it about the difference between a decade and a microsecond that influences how you model these data?
Comment: Thanks for an interesting question! Just to clarify - are you going to do some type of regression/general linear model and decade would be one of the predictors/covariates? How many observations do you have?
Comment: Seems a fair question to me.
Comment: This will generally depend on what exactly you will do with the variable. What does "treating as continuous" exactly amount to for you, and what would be your alternative, in what kind of analysis? (I'm surprised that this has already attracted four answers without this question being asked...)
Answer: As alluded to in the comments, the word "continuous" is a a bit misleading here, and what you really care about is whether you can treat the decade variable as an interval scale (e.g. is the difference between 1960s and 1980s the same as the difference between 1990s and 2010s?). In most situations, I would say that's a reasonable assumption to make. You could also consider recoding as decades_ago (e.g. 2010s = -1 decade, 2000s = -2), in which case it could also be treated as a ratio scale, since, e.g. the 1980s were twice as long ago as the 2000s.
As for continuous, no date-times are ever continuous, since they're always rounded to the decade, year, month, day, or hour, etc. The question is whether this loss of information is large enough to worry about.
Comment: I deal with ages in months frequently and it cracks me up when they're stored out to the 10th decimal place
Comment: Thanks! @AzorAhai-him-
Answer: As the answer by Eoin points out, the question is not whether you have "enough categories", but whether a) time is an interval scale for your model and b) the loss of information from rounding to decade is likely to be inconsequential (i.e. if you expect only very small differences in outcome on the scale of single years or smaller). Both of those assumptions can be relaxed, if you are OK with more complex models.
The assumption of interval scale can be relaxed by fitting the effect of maturity as a smooth function (e.g. a spline , a Gaussian process or a random walk). This means that you assume there is some continuity over time (e.g. companies founded in 1920s will be more similar to those founded in 1930s than to those founded in 1980s). This model is more flexible and allows non-linear change over decades, but less flexible than assuming decades are completely independent (which would arise if you treated decade as a categorical predictor). There are many ready-made packages supporting spline/Gaussian process/random walk predictors.
If you assume that rounding may loose important information, you can treat the decade as interval censored, i.e. you assume there is some true continuous time for each observation and the decade information serves to bound the true time from both below and above.  You then can treat that "true" time as another unknown parameter and have the outcome depend on that parameter, forming a special type of a measurement error model. I know of no package that would have a model like that readily available (let alone one where you could combine it with spline/Gaussian process), so such a model would probably need to be implemented from scratch in some probabilistic programming language like Stan. In fact, there is a chapter in the Stan manual on treating rounded values as interval-censored data.
Comment: Thanks! I didn't know a lot of this before. This is an excellent. I learn best when I'm learning to get a project done well.
Answer: This is a great question, similar ones arise all the time when modeling data. For example, user ratings on a scale of 1-5 and economic data binned by quintiles. They're certainly numbers. But they're not continuous so it's not obvious.
I'll cut to the chase and suggest the following:

if your model is susceptible to overfitting you'll most likely benefit from treating it as a single numeric feature
if you have a lot of data and overfitting is less of a concern, I suggest starting with modeling as one feature with the decades, and 13 additional one-hot features, 1 for each decade. Then use feature selection to determine which representation is best. You may find that a few of the one-hot/indicator variables for are particularly important because of the unique (dare I say, categorical) social, political, and economic circumstances of those decades.

Here's why: all common models, from OLS to deep neural nets, apply continuous domain mathematical operations to your input data. All they see are floating-point numbers. Even random forests, which pick a pivot and recursively partition your data. It's the same operation regardless of whether every value is unique or 90% are 0s and 10% are 1s.
So the real question isn't whether to model your data as numeric, it's what feature vectors you should give to the model, and what their numeric values should be.
Setting aside transformations and PCA and other pre-processing steps, there are ultimately two choices:

one feature with the decades as numbers, as your colleague suggests. This generally makes sense when math operations on your values make sense. For example, adding 10 to the 1970s is arguably the 1980s. The 1980s are arguably halfway between the 1970s and 1990s. This representation allows the model to more easily learn long-term temporal trends in your data if they exist. "Easily" meaning less model complexity and fewer FLOPs.
considering the feature to be categorical and making a separate 1-hot feature for each category. This is done when math operations don't make sense on your data. Arguably it does not make sense to average the roaring 20's with the WW2 economy of the 1940's to get the Great Depression of the 1930's. The average of the 1970s music with 1990s music isn't 1980s hair metal. So in this case you instead want to make 1-hot vectors to indicate which decade each organization was founded in. This representation makes it easier for models to learn decade-specific behavior. A nonlinear model with enough flexibility can learn to isolate decades from each other from a single numeric decades feature, it will just require a more complex model and that complexity will expose you more to overfitting.

Without knowing more about your dataset and what you aim to model, there's no way to tell which is best for sure. My instinct is that treating it as a continuous numeric feature is probably the best single-feature way to use it, but it's a false choice - your model can probably accommodate an arbitrary number of features. So I encourage you to try both numeric and categorical, use some feature and model selection techniques, and find out for sure which one is best (or a combination of both).
Comment: Thanks! This is a great explanation.
Answer: Regression on continuous variables is more difficult than classification.  However, threshold classification captures most of the information, as the above answer states.
Comment: Welcome to CV, Gregory.  An answer is not the place for comments.  If you intended to provide an answer, then please edit your post to show clearly how it does answer the question.