JavaScript - Dados do Usuário duvida

Question: if (usuario[1] >= 18 && usuario[2] >= 170) {
Essa linha de codigo abaixo fiquei com duvida alguem me explica por favor, pra mim nao faz muito sentido pegar o usuario 1 e o usuario 2 para verificar se e true ou false, posso estar enganado mas nao teria que ser usado um usuario para todos ?
Em uma academia está acontecendo um cadastro de vários usuários contendo as seguintes informações: nome, idade e altura. E para realizar um determinado treino, existe alguns requisitos: Ter 18 anos ou mais e ter uma altura igual ou maior a 1,70.
Crie uma função chamada maiorAlto que retorne verdadeiro (true) caso ele atenda os requisitos, e falso (false) para o contrário. Nessa função você irá receber um parâmetro que será um array, contendo na primeira posição o nome, segunda posição a idade do aluno e na terceira contendo a altura em Centímetros.
Exemplo
maiorAlto(["Aluno incrível", 18, 170]) // retorna true
maiortAlto(["Aluno baixo", 17, 150]) // retorna false
Dicas:Lembre-se que para criar uma função usamos a palavra function No array de informações, a idade do usuário vem primeiro, segundo a altura (que está em centímetros) Para acessar a posição de um array bata colocar o nome seguido de colchetes: array[1]
function maiorAlto(usuario) {
*if (usuario[1] >= 18 && usuario[2] >= 170)* {
    return true;

}
else {
    return false;
}

}
var usuario1 = ['Et da Estônia', 17, 170];
var usuario2 = ['Pessoa do Pântano', 39, 198];
var usuario3 = ['Homem da Lua Virada', 21, 149];
var usuario4 = ['Pequena Paulistana', 18, 171];
var usuario5 = ['Menino da Porteira', 13, 142];
//var resultado = maiorAlto(usuario1);
console.log("usuario1 = " +maiorAlto(usuario1));
console.log("usuario2 = " +maiorAlto(usuario2));
console.log("usuario3 = " +maiorAlto(usuario3));
console.log("usuario4 = " +maiorAlto(usuario4));
console.log("usuario5 = " +maiorAlto(usuario5));
Comment: Isto responde à sua pergunta? [Solução de problema em JavaScript](https://pt.stackoverflow.com/questions/461100/solu%c3%a7%c3%a3o-de-problema-em-javascript)
Answer: Está correto.
Isso é a utilização de array (vetor ou matriz) de variáveis.
Observe que:
var usuario1 = ['Et da Estônia', 17, 170];
É o mesmo que:
usuario1[0]  = 'Et da Estônia'; usuario1[1] = 17; usuario1[2] = 170;
São dados do mesmo usuário. Respectivamente nome, idade e altura.
Então a sua função ficaria assim:
function maiorAlto(usuario){
return (usuario[1] >= 18 && usuario[2] >= 170);

}
Note que o retorno da função já é booleano, então você pode escrever a expressão condicional já no return, não sendo necessário verificar com if() para utilizar return true.
Exemplo de chamada para essa função:
var usuario1 = ['Eduardo', 17, 175];
console.log(maiorAlto(usuario1));

No caso de trabalhar com Array Multidimensional como:
var usuarios = [ { nome: 'Pessoa do Pântano', idade: 39, altura: 198 }, { nome: 'Homem da Lua Virada', idade: 21, altura: 149 }, { nome: 'Pequena Paulistana', idade: 18, altura: 171 }, { nome: 'Menino da Porteira', idade: 13, altura: 142 } ];

Você terá que fazer um loop para acessar cada objeto dentro do array. Há duas formas de fazer, loop for com um contador ou loop foreach.
Loop for:
    function maiorAlto(usuario){
for(i = 0; i < usuario.length; i ++)
    console.log(usuario[i].idade >= 18 && usuario[i].altura >= 170);

}
maiorAlto(usuarios);
Ou,utilizando forEach:
function maiorAlto(usuario){
console.log(usuario.idade >= 18 && usuario.altura >= 170);

}
Utilizando a chamada para a função dessa forma:
usuarios.forEach(maiorAlto);

Recomendo leitura desses artigos para maior esclarecimento:
https://www.geeksforgeeks.org/multidimensional-array-in-javascript/
https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
Comment: Olha to com duvida de como fazer meu IF se fizesse uma unica variavel para os usuarios assim :
 var usuarios = [
    { nome: 'Pessoa do Pântano', idade: 39, altura: 198 },
    { nome: 'Homem da Lua Virada', idade: 21, altura: 149 },
    { nome: 'Pequena Paulistana', idade: 18, altura: 171 },
    { nome: 'Menino da Porteira', idade: 13, altura: 142 }
];  E nao uma variavel para cada usuario
Answer: O If já retorna true ou false, não precisa especificar isso no corpo dele. basta dar um return usuario;
Comment: Entendi, so que o if nao ficaria aplicado somente na variavel 1 e 2 ? Devido eu ter escolhido somente essas duas variaveis dentro do if. Nao teria que ser um if que conte-se todos os usuarios ?
Comment: Aí no caso você tem que fazer um for, pra poder comparar todos os usuários. O ideal é você criar uma variável usuários do tipo array, pra armazenar todos os usuários e fazer um for percorrendo todas as posições do array. Dentro do for for você cria uma variável pra guardar o maior e aí você usaria um if pra verificar se o novo usuário é maior que o último. Aí no final você retorna o maior.

JavaScript - Dados do Usuário duvida


how do robots find node urls

Question: I appear to be getting quite heavily crawled by robots that are seeing urls like
?q=node/668
1) how are robot's able to find these urls?
The robots are referring too are not google or popular search engines. Are there anyway apart from robots.txt to defend against these. The amount of traffic i'm getting is quite intense.
I'm using drupal 7
Comment: It's almost impossible to say without being able to inspect the site...run a link scanner on your site and see which pages refer to those paths, that's the easiest solution. If there aren't any, then essentially you've got bots that are 'guessing' based on some criteria or other, and there's not much you can do about it short of banning their IPs
Answer: Robots can find urls by following links either on-site or offsite.
You could use a link scanner as suggested by Clive, or look in google analytics to see where referrals are coming from to see if you have a lot of inbound links.
Alternatively, if a robot has figured out (or guessed) that your site is Drupal based then it's a pretty simple matter to start trying ?q=node/1, ?q=node/2, etc... and see what you don't get a 404 from.
I'd say a likely reason that the robot is using "?q=blah" instead of just "blah" is because the former will always work whereas the latter requires you to have clean URLs configured.
As well as robots.txt there are free services like Cloud Flare http://www.cloudflare.com/ that attempt to filter known-malicious bots for you before they can access your server.
You could also add rel="nofollow" to links on you're site that you're suspicious might be generating the traffic, which tells crawlers to not follow that link. Be careful with this as it also stops search engines, meaning it can harm your SEO if used unwisely.

how do robots find node urls


Using Facebook Session to login my website?

Question: I am using facebook to login and register into my website. But I want to know that how can I use facebook session to create session on my website and as soon as user logs out of facebook the user will be automatically logged out of the website too.
Plz help.
Answer: Check the Facebook's Real Time API (See https://developers.facebook.com/docs/reference/api/realtime/).  Maybe you can subscribe to their log out event.


Does $\int_{1}^{\infty} g(x)\ dx$ imply $\lim\limits_{x\to \infty}g(x)=0$?

Question: Let $g:[1, \infty)\rightarrow \mathbb R$ a continuous non-negative function, such that $\int_{1}^{\infty} g(x)\ dx$ converges.
Is it true that $\lim\limits_{x\to \infty}g(x)=0$ ?
I tried to find a counter-example but I can't figure a trivial one.
I also tried to prove it by the definition of the convergence of $g(x)$ but couldn't show that limit is really $0$.
Comment: It's true if you also force $g$ to be monotonic.
Comment: You mean $ x \rightarrow +\infty $?
Comment: @FreeSalad Yes, I meant that. Sorry.
Comment: $\int_0^\infty \sin(x^2)\,dx$ is known to converge.
Comment: @YvesDaoust $\sin(x^2)$ is not non-negative however.
Comment: @Zubzub: quite right, I missed that.
Comment: I remember this one. And I remember I didn't really find an expression but got it right anyway. Hope it's really identical :D
Answer: Take a function made up of triangles (i.e. it starts at $0$, it goes to $1$, then comes back at $0$). Make it so that the area of each triangle is $1/n^2$ (i.e. the base of each triangle is $2/n^2$).
This means that $$\int_1^\infty g(x) = \sum_{n=1}^\infty \frac{1}{n^2}$$ converges.
But the limit of $g(x)$ as $x \to \infty$ is not $0$ as $g(x)$ alternates between $0$ and $1$
Comment: @Dror It clearly is. All the triangles are "connected".
Comment: Is this continous?
Comment: Whoops my bad..
Comment: So is it true to say that if $\lim\limits_{x\to \infty}g(x)$ exists, then it must be zero?
Comment: @z00x Yes; if the limit is $l > 0$ then you can bound the integral with something like $\int_1^R g(x)dx \ge l/2\cdot R$, which diverges as $R \to \infty$, which implies that the integral $\int_1^\infty g(x)dx$ does not converge. So if the limit exists then it must be $0$


Resolver erro SVN: "must be ancestrally related to..."

Question: Com o TortoiseSVN criei uma branch para produção a partir do meu trunk, só que depois de um tempo quando tento fazer o merge do trunk na producao dá o seguinte erro:

'http://hostname/repositorio/trunk@50' must be ancestrally related to 'http://hostname/repositorio/branches/producao@43'

Por que isso acontece e como resolver?
Answer: O branch foi criado manualmente ou usando a opção "TortoiseSVN -> Branch/tag"? Uma possível solução imediata pode ser usar svn merge --ignore-ancestry.
Perguntas relacionadas no stackoverflow em inglês:

https://stackoverflow.com/q/490164/1814415
https://stackoverflow.com/q/22204268/1814415
Comment: Criei manualmente usando a opção que você descreveu e também marquei a opção **ignore-ancestry** mas dá outro erro: "Cannot merge automatically while ignoring mergeinfo"
Comment: Isso parece ocorrer por causa de informações expúrias no svn:mergeinfo, essa resposta no stackoverflow em inglês pode ajudar: http://stackoverflow.com/a/2648969/1814415
Comment: Seu problema foi resolvido ?


Bayesian linear regression KL divergence

Question: $$y_i \sim N(w_0 + w_1x_i, \sigma^2_j)$$
$$\mathbf{w} \sim N(0,\alpha^2 I) $$
Data is $D$, posterior distribution $p(\mathbf{w}|D)$ is approximated according to mean-field approximation
$$p(\mathbf{w}|D) \approx \prod_{d=0}^1 q(w_d)= \prod_{d=0}^1 N(w_d | \mu_d, \sigma^2_d)$$
How to calculate the KL divergence of:
$$ \text{KL} \left[q_{\lambda}(\mathbf{w}) | p(\mathbf{w})\right]$$
I know that analytical solution of KL for two univariate gaussians would be:
$$-\frac{1}{2} + \log(\frac{\sigma_1^2}{\sigma_2^2}) + \frac{\sigma_2^2 + (\mu_1-\mu_2)^2}{2\sigma_1^2}$$
But not sure what to do here since $p(\mathbf{w}|D)$ itself has two components.
Answer: You can use the formula for KL divergence between two multivariate normal distributions:
$$D_{KL}(\mathcal N_0\vert\vert N_1)=\frac{1}{2}\left(\text{tr}(\Sigma_1^{-1}\Sigma_0)+(\mu_1-\mu_0)^T\Sigma_1^{-1}(\mu_1-\mu_0)-k+\ln\left(\frac{\det\Sigma_1}{\det\Sigma_0}\right)\right)$$
In your case, $\mathcal N_0=\mathcal N \left(\mathbf{\mu_0}=\begin{bmatrix}\mu_0\\\mu_1\end{bmatrix}, \mathbf{\Sigma_0}=\begin{bmatrix}\sigma_0^2&0\\0&\sigma_1^2\end{bmatrix}\right)$, and $\mathcal N_1=\mathcal N( \mathbf{\mu_1}\mathbf = 0, \mathbf{\Sigma_1}=\alpha^2\mathbf I)$, and $k=2$. Note the differences between the bold and normal fonts, i.e. $\mathbf{\mu_0}\neq\mu_0$.


Removing string out of string rowwise in data.frame using another column in R

Question: I am trying to cut/remove a string out of a larger string based on another column in a data.frame in a rowwise manner.
For example, in this data.frame col2 should be removed from col1
kat1 <- data.frame(col1 = c("A123Testz45", "66Test255"), col2 = c("Testz", "Test2"))

with the results being
          col1     col2
1     A123 45     Testz
2       66 55     Test2

I have tried variations of sub with
kat1$col1 <- sub(kat1$col2, " ", kat1$col1)

but this results in
Warning message: In sub(kat1$col2, " ", kat1$col1) : argument 'pattern' has length > 1 and only the first element will be used

Thus, I am thinking of ways to use columns in REGEX to replace these elements in a row-wise manner.
Answer: sub and gsub can't vectorize pattern (see ?gsub). If you are looking for both simplicity and efficiency, try stringi (or stringr which is a stringi wrapper)
with(kat1, stringi::stri_replace_all_fixed(col1, col2, " "))
# [1] "A123 45" "66 55"

Using base R, you could do it (inefficiently) using apply, something like
apply(kat1, 1, function(x) sub(x[["col2"]], " ", x[["col1"]], fixed = TRUE))
# [1] "A123 45" "66 55"

A better base R suggestion by @docendo would be to use mapply on vectors in order to avoid matrix conversions
transform(kat1, col1 = mapply(sub, col2, " ", col1, fixed = TRUE))
#      col1  col2
# 1 A123 45 Testz
# 2   66 55 Test2

Comment: @DavidArenburg, interesting! Another (not so efficient) base alternative would be `transform(kat1, col1 = mapply(sub, col2, " ", col1))`
Comment: I used to think `stringr` was a wrapper for base functions. Is that not the case?
Comment: @docendodiscimus, No. Just type `str_replace_all` in console and check out the source code. By "wrapper" I mean that it's just the same code under disguise. Compared to `stringi` which is written in C/C++.
Comment: `stringr` used to be a wrapper for base functions until `stringi` came along and strutted its awesomeness about.
Comment: @docendodiscimus Nice alternative. Probably better than `apply`


How prove the finite induction

Question: Theorem (Finite induction)
Let be P$(x)$ a property. So we suppose that

P$(0)$,
P$(n)\rightarrow$P$\big(S(n)\big)$, for all $n<k$

So P(n) is true for all $n<k$.
Unfortunately I can't formally prove the theorem. So could someone help me, please?
Comment: Consider $\{n\in\Bbb N:\mathbf{P}(n)\text{ or }k\le n\}$.
Answer: Let $\pi:=\{h\in k:\mathbf{P}(h)\}$. So if it was $k\setminus \pi\neq\varnothing$ then there exist $m:=\min{k\setminus \pi}$ so we analise the case where $m=0$ and the case where $m\neq 0$. So for the hypothesis 1 it is impossible that $m=0$. Finally if $m\neq 0$ then $m=S(l)$ for some $l\in k$ and then $l\in\pi$ so that $\mathbf{P}(l)$ is true and so $\mathbf{P}(m)$ is true and this would be impossible.
Comment: Almost: either $m=S(\ell)$ for some $\ell\in k$ (and you do need to mention that $\ell$ is in $k$, not just in $\Bbb N$, or $m=0$. The $m=0$ case is trivial but does have to be mentioned.
Comment: But you have to **say** so. All you know about $m$ is that it is $\min k\setminus\pi$. That means that $m\in k$, but it does **not** immediately imply that $m\ne 0$; it says only that **either** $m=0$, **or** $m=S(\ell)$ for some $\ell\in k$. The first of these is impossible by clause (1) of the theorem, and the second is impossible by clause (2) — and both cases have to be ruled out.
Comment: @BrianM.Scott I edited the answer. Now is it correct?
Comment: You still haven't dealt with the possibility that $m=0$. It's not true that $m=S(\ell)$ for some $\ell\in k$: what's true is that **either** $m=S(\ell)$ for some $\ell\in k$, **or** $m=0$. (Of course both turn out to be impossible, but for different reasons.)
Comment: @BrianM.Scott If for hypothesis $\mathbf{P}(0)$ is true then it seems to me that it is impossible that $m=0$, is this uncorrect?
Comment: @BrianM.Scott Okay, I edited the ansewer. Now is it correct?
Comment: Yep, much better; upvoted.
Comment: @BrianM.Scott Okay, thanks too much for your assistance!
Comment: You're welcome!
Comment: @BrianM.Scott Hi professor Scott, could I ask your assistance [here](https://math.stackexchange.com/questions/3734631/how-prove-the-general-recursion-theorem)? Excuse me for the bother.
Answer: Hint:
Consider the set $S=\lbrace n\in \bigl[\mkern-4mu\bigl|0,k\bigr|\mkern-4.25mu\bigr]\mid \ P(n)\text{ false }\rbrace$ and suppose  $S\ne\varnothing$. As any nonempty subset of $\mathbf N$, it has a least element. Can you deduce a contradiction?
Comment: Let $\pi:=\{n\in\Bbb{N}:\mathbf{P}(n)\}$. So if it was $n\setminus \pi\neq\varnothing$ then there exist $m:=\min{n\setminus \pi}$ and so if $l\in\Bbb{N}$ is such that $m=S(l)$ then $l\in\pi$ and so $\mathbf{P}(l)$ is true and so $\mathbf{P}(m)$ is true and this would be impossible. Do you what say this?
Comment: It's fine (I'd prefer a Π rather than a π). Τ To be quite complete, you have to mention that $m>0$.
Comment: @AntonioMariaDiMauro: No, this doesn't work: $\mathbf{P}(\ell)$ does not imply $\mathbf{P}(m)$ if $\ell\ge k$. Replace $\mathbf{P}(n)$ with the property $\mathbf{Q}(n)$ that is '$\mathbf{P}(n)$ or $k\le n$ and prove that $\mathbf{Q}(n)\to\mathbf{Q}(S(n))$ for all $n\in\Bbb N$.
Comment: @BrianM.Scott Excuse me. I had do a terrible mistake: I wanted write $\pi:=\{n\in k:\mathbf{P}(n)\}$.
Comment: Oh! yes. That's how I interpreted  your way of writing.

How prove the finite induction


Is $p \equiv q\pmod{15}$ the same as $p\equiv q\pmod{5}$?

Question: Let $p$ and $q$ be prime. If $p\equiv q \pmod{15}$, then is it true to say they are congruent mod $5$?
I figure I could say $p - q \equiv 0 \pmod{15}$, so $p\equiv q \pmod{5}$, but what throws me off is when we let $p = 37$ and $q = 7$.
So $37\equiv 7 \pmod{15}$, but $37\equiv 2 \pmod{5}$ which disproves this, doesn't it? Or is it legal to just say $37\equiv 7 \pmod{5}$ is the same as $37\equiv 2 \pmod{5}$ since $7\equiv 2 \pmod{5}$.
Comment: The question in your title and the question in your question are subtly different: your title asks if being equivalent mod 15 is _the same_ as being equivalent mod 5, whereas the text of the question only asks if one implies the other.  The latter is true, but the former is not.
Comment: So basically, if p = q mod 15, then they are congruent mod 5. But being congruent mod 5 does not imply they are congruent mod 15.
Comment: $7\equiv 2\pmod {5}$, but $7\not\equiv 2\pmod {15}$.
Comment: Yes, it is "legal" to say it, from the basic definition of congruence.
Comment: $p\equiv q\pmod {15}\,\Leftrightarrow\, 15\mid p-q\,\Rightarrow\,5\mid p-q\,\Leftrightarrow\, p\equiv q\pmod {5}$. So $p\equiv q\pmod {15}\,\Rightarrow\, p\equiv q\pmod {5}$, but it's not true the other way around, so they're not the same.
Comment: @user2327195 yes.
Comment: $p=q+15n$ is the same as $p=q+5(3n)$. If $p=q+5m$ then $m=3r+s$  with $s\in \{0,1,2\}$ then $p=q+15r+5s$ where $5s=0,5,10$.
Comment: Rephrase your question as asking if the following statement is true: "A number is divisible by $15$ if and only if it is divisible by $5$". I think the solution should be most obvious, now :)
Comment: Definition: $a\equiv b\pmod {n}\,\Leftrightarrow\, n\mid a-b$. Or i.e. $a,b$ leave the same remainders when divided by $n$.

So in your case indeed $37\equiv 7\pmod {5}$, since $5\mid 30=37-7$. Both $37,7$ leave the same remainders, namely $2$, when divided by $5$. Both $37,7$ belong to the same equivalence classes modulo $5$ ($a\equiv b\pmod {n}$ is an equivalence relation (since $a\equiv a$ and $a\equiv b\,\Leftrightarrow\, b\equiv a$ and $a\equiv b,\:b\equiv a\,\Rightarrow\, a\equiv c$), so we can divide the values $a\bmod{n}$ into equivalence classes).
Answer: You may be confusing the notion of modular equivalence in mathematics with the mod operator in computer programming; while the two are closely related, they're not quite the same thing.  The mod operator is actually a function, one that takes two numbers (a value and a modulus) and returns the remainder from dividing the value by the modulus; for instance, we say that 22 mod 5 = 2.  Here (ignoring negative numbers), a mod n = b means that c is a number between $0$ and $n-1$ and that $a-b$ is a multiple of $n$.
Mathematically, though, mod is generally used for what's known as an equivalence relation; we say that $a\equiv b\pmod n$ if and only if $a-b$ is a multiple of $n$.  There's no requirement that $b$ be less than $n$; it's true that $22\equiv 2\pmod 5$, but it's also true that $22\equiv 37\pmod 5$ (since $22-37=-15$ is a multiple of $5$, or even that $22\equiv -13\pmod 5$ (since $22-(-13)=35$ is a multiple of $5$).  The two can be related back and forth: in one direction we have $a\equiv b\pmod n$ if and only if $a$ mod $n = b$ mod $n$, and going the other way the value of $a$ mod $n$ is the unique number $b$ (can you see why it's unique?) such that $a\equiv b\pmod n$ and $0\leq b\leq n-1$.
Answer: I find it helpful to take questions like these out of a congruence relation to understand them sometimes.
$p\equiv q\pmod{15}$ just means $p=q+15n$ for some integer $n$. This can now be rewritten as $p=q+5(3n)$. Since $3n$ is clearly also an integer, we can now put this back into a congruence relation $p\equiv q\pmod{5}$. Therefore it is true that $p\equiv q\pmod{15}$ implies $p\equiv q\pmod{5}$.
Also, you mentioned using the form $p-q\equiv0\pmod{15}$. I find this form is always preferable because it removes any confusion over the residue classes. Using your example where $p=37$ and $q=7$, it can be seen that $37-7=30\equiv 0\pmod{15}$ and $37-7=30\equiv 0\pmod{5}$.
Answer: $p \equiv q \bmod{15} \iff 15 \mid (p-q) \iff 5 \mid (p-q)$ and $3 \mid (p-q) \iff p \equiv q \bmod{3}$ and $p \equiv q \bmod{5}$.


Pip installing to wrong virtual environment

Question: I have two Django projects each with a virtual environment called myvenv. I am trying to use pip to install a package called psycopg2. It is installing to the wrong virtual environment even though the which pip command confirms that pip is being run within the correct virtual environment.
I rebooted my mac so as to start without any virtual environments running. My terminal log looks like this when I try to use pip:
BillMacBookPro:~ billnoble$ cd ~/documents/yhistory-server
BillMacBookPro:yhistory-server billnoble$ source ~/documents/yhistory-    server/myvenv/bin/activate
(myvenv) BillMacBookPro:yhistory-server billnoble$ which pip
/Users/billnoble/Documents/YHistory-Server/myvenv/bin/pip
(myvenv) BillMacBookPro:yhistory-server billnoble$ brew install postgresql
Warning: postgresql-9.4.4 already installed
Warning: You are using OS X 10.11.
We do not provide support for this pre-release version.
You may encounter build failures or other breakage.
(myvenv) BillMacBookPro:yhistory-server billnoble$ pip install psycopg2
Requirement already satisfied (use --upgrade to upgrade): psycopg2 in /Users/billnoble/Documents/VeeUServer/myvenv/lib/python3.4/site-packages
You are using pip version 8.1.1, however version 8.1.2 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.

I am successfully starting my virtual environment in the YHistory-Server directory and which pip confirms that it is running from this virtual server. However when I run pip it complains that the package is installed in another virtual environment on my computer. Why is it using the wrong path name? How can I make it install in the correct virtual environment?
Comment: share output for `echo $PYTHONPATH` before and after activating the virtualenv
Comment: Nothing happens when I run echo $PYTHONPATH
Answer: I think when you created your second virtualenv you did so with the first already activated, and possibly chained them together. Try to recreate your virtual environments, and when you create the second one make sure you deactivate the first one you created first.
Comment: Yes it is very probably that my original virtualenv was active when I created the second one. How do I go about recreating the virtual environments?


Referenciar uma table através de uma string em Lua

Question: Preciso utilizar uma table em Lua, mas só posso referenciá-la através de uma string, exemplo:
tabelaA = { "qualquer coisa" }
variavelA = "tabelaA"

print(variavelA)
resultado: "qualquer coisa"

Tendo em mente que não tenho como referenciar esta tabela diretamente, eu vou obter o nome em string.
Answer: Existe a tabela _G, chamado de o ambiente global, que representa as variáveis existentes:
> print(tabelaA[1])
qualquer coisa
> print(_G["tabelaA"][1])
qualquer coisa

Também, sempre pode construir outra tabela:
tabelaVariaveis = {}
tabelaVariaveis["tabelaA"] = tabelaA

-- e pode acrescentar mais
tabelaB = { "outra coisa" }
tabelaVariaveis["tabelaB"] = tabelaB

e utilizá-la:
> print(tabelaVariaveis["tabelaA"][1])
qualquer coisa

Comment: Muito Obrigado, Dan Getz
Consegui utilizar exemplo, ajudou muito!
Comment: @arthurgps2 tentei a sua sugestão, mas `print(shared["tabelaA"][1])` não funcionou aqui (Lua 5.1.5). Favor, pode explicar mais?
Comment: Também existe [`_ENV`](https://www.lua.org/manual/5.2/manual.html#2.2). `_ENV` e `_G` são por padrão uma mesma tabela, só que `_ENV` é o mais principalmente usado pelo Lua, por exemplo, quando você tenta acessar um nome/identificador não local, o Lua pega o valor atual de `_ENV` e pega o campo com esse nome. Apenas Lua 5.2+ suporta `_ENV` (LuaJIT).


Three Days Grace guitar distortion tone

Question: How do I get Three Days Grace guitar distortion sound in Garageband or Logic. What are the other ways to reproduce the exact sound used in their riffs?
Comment: @jadarnel27 Here's the song's link: [Three Days Grace - Break](http://www.youtube.com/watch?v=_4VCpTZye10)
Answer: You should find the best sound setting on your own.
To me their sound is closer to overdrive than distortion.
And Barry Stock uses Triaxis preamp, maybe this'll help you

Three Days Grace guitar distortion tone


How to simplify using conjugates in Maple

Question: I think it is fairly easy to see that
$$\frac{1}{\sqrt 2 -1} = \sqrt{2} + 1$$
Now given the fraction on the left in Maple, how can we get to the equivalent expression on the right? I apologize in advance, if this is rather obvious. But after trying a few things, I have not been able to make it work.
I have used simplify(1/(sqrt(2)-1) and simplify(1/(sqrt(2)-1) * ((sqrt(2)+1)/(sqrt(2)+1)). In both cases, Maple simply returns the first expression on the left $\frac{1}{\sqrt 2 -1}$.
Comment: I'm voting to close this question because this is about a particular software system.... not math per se.
Comment: Don't know Maple, but this process is usually called "rationalizing the denominator."
Comment: "rationalizing the denominator" is a general term. Using conjugates is one way to rationalize the denominator. I am not sure if conjugates is a term that is being used often, but that is the one I have been taught.
Comment: In *Mathematica*:  `Simplify[1/(Sqrt[2]-1)]` gives the answer.  By the way, this question has little to do with math but explicitly refers to a symbol-manipulation program, and hence should be closed or migrated.
Answer: Thanks to Thomas, upon looking up rationalizing the denominator, I learnt Maple has a built-in function for this purpose:
rationalize(1/(sqrt(2)-1))
gives what I want. For interested reader, have a look at the documentation page here.


Combinatorics: How many ways can an $m \times n$ board be traversed from the top left to the bottom right by moving only to the right and down?

Question: I have a $m \times n$ board, and I can only move right and down. Say you start from the top left, how many ways can you go to the bottom right?
This is a classical dynamic programming question, with dp [i][j] = dp[i-1][j] + dp[i][j-1]. And you initialize the top row and the left-most column to be 1.
I am wondering what would be the mathematical approach in solving this problem?
Comment: Can you try doing an argument by induction? try extending the row/column by one and see how the answer changes. For base cases, consider only one row or column.
Comment: Do you mean $m$ rows and $n$ columns or $m$ horizontal and $n$ vertical line segments?
Answer: One approach would be to classify moves down and right as $\mathsf D$ and $\mathsf R$ respectively. Then, given a $m\times n$ grid, to get from the top left to the bottom right, you would have to move downwards $m-1$ times, and move right $n-1$ times, in some kind of order.
For example, consider a $5\times 3$ grid. One possible route would be:
![1]][1]
[1]: https://i.stack.imgur.com/NlTHc.png
Or, written like this: $\mathsf{DDDDRR}$
Now, the problem becomes a simple matter of sequence permutation, which is a very elementary concept.
The number of ways the sequence $\mathsf{DDDDRR}$ can be ordered (which is just another way of saying the number of different ways you can get from the top left corner to the bottom right corner) is:
$$\frac{7!}{4!\times 2!} = 105$$
To generalize, for a $(m+1)\times (n+1)$ grid, the number of ways to get from the top left corner to the bottom right corner is given by:
$$\frac{(m+n)!}{m!\times n!}$$
A more comprehensive explanation is given here:
https://betterexplained.com/articles/navigate-a-grid-using-combinations-and-permutations/


Xml parser em Swift

Question: Baixei um projeto pronto de rss Reader, ele vem titulo descrição e imagem.
Porem estou tentando editar o mesmo para o meu xml.
vejam os códigos:
//
//  FeedTableViewController.swift
//  RSSReader
//
//  Created by Training on 23/12/14.
//  Copyright (c) 2014 Training. All rights reserved.
//

import UIKit

class FeedTableViewController: UITableViewController, MWFeedParserDelegate, SideBarDelegate {

var feedItems = [MWFeedItem]()
var sidebar = SideBar()
var savedFeeds = [Feed]()
var feedNames = [String]()

func request(urlString:String?){

    if urlString == nil{

        let url = NSURL(string: "http://feeds.nytimes.com/nyt/rss/Technology")
        let feedParser = MWFeedParser(feedURL: url)
        feedParser.delegate = self
        feedParser.parse()
    }else{

        let url = NSURL(string: urlString!)
        let feedParser = MWFeedParser(feedURL: url)
        feedParser.delegate = self
        feedParser.parse()
    }

}

func loadSavedFeeds (){
    savedFeeds = [Feed]()
    feedNames = [String]()

    feedNames.append("Add Feed")

    let moc = SwiftCoreDataHelper.managedObjectContext()

    let results = SwiftCoreDataHelper.fetchEntities(NSStringFromClass(Feed), withPredicate: nil, managedObjectContext: moc)

    if results.count > 0 {
        for feed in results{
            let f = feed as Feed
            savedFeeds.append(f)
            feedNames.append(f.name)
        }
    }

    sidebar = SideBar(sourceView: self.navigationController!.view, menuItems: feedNames)
    sidebar.delegate = self

}

// MARK: - FEED PARSER DELEGATE

func feedParserDidStart(parser: MWFeedParser!) {
    feedItems = [MWFeedItem]()
}

func feedParserDidFinish(parser: MWFeedParser!) {
    self.tableView.reloadData()
}

func feedParser(parser: MWFeedParser!, didParseFeedInfo info: MWFeedInfo!) {
    println(info)
    self.title = info.title
}

func feedParser(parser: MWFeedParser!, didParseFeedItem item: MWFeedItem!) {
    feedItems.append(item)
}

// MARK: - SIDEBAR DELEGATE

func sideBarDidSelectMenuButtonAtIndex(index: Int) {
    if index == 0{ // ADD FEED BUTTON
        let alert = UIAlertController(title: "Add new feed", message: "Enter feed name and URL", preferredStyle: UIAlertControllerStyle.Alert)
        alert.addTextFieldWithConfigurationHandler({ (textField:UITextField!) -> Void in
            textField.placeholder = "Feed name"
        })

        alert.addTextFieldWithConfigurationHandler({ (textField:UITextField!) -> Void in
            textField.placeholder = "Feed URL"
        })

        alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))
        alert.addAction(UIAlertAction(title: "Save", style: UIAlertActionStyle.Default, handler: { (alertAction:UIAlertAction!) -> Void in
            let textFields = alert.textFields

            let feedNameTextField = textFields?.first as UITextField
            let feedURLTextField = textFields?.last as UITextField

            if feedNameTextField.text != "" && feedURLTextField.text != "" {
                let moc = SwiftCoreDataHelper.managedObjectContext()

                let feed = SwiftCoreDataHelper.insertManagedObject(NSStringFromClass(Feed), managedObjectConect: moc) as Feed

                feed.name = feedNameTextField.text
                feed.url = feedURLTextField.text

                SwiftCoreDataHelper.saveManagedObjectContext(moc)

                self.loadSavedFeeds()
            }
        }))

        self.presentViewController(alert, animated: true, completion: nil)

    }else{
        let moc = SwiftCoreDataHelper.managedObjectContext()

        let selectedFeed = moc.existingObjectWithID(savedFeeds[index - 1].objectID, error: nil) as Feed

        request(selectedFeed.url)

    }
}

override func viewDidLoad() {
    super.viewDidLoad()
    loadSavedFeeds()

}

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

    request(nil)

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// MARK: - Table view data source

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return 100
}

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // Return the number of sections.
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // Return the number of rows in the section.
    return feedItems.count
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as FeedTableViewCell

    cell.itemImageView.image = UIImage(named: "placeholder")

    let item = feedItems[indexPath.row] as MWFeedItem?
    cell.itemAuthorLabel.text = item?.author
    cell.itemTitleLabel.text = item?.title

    if item?.content != nil {

        let htmlContent = item!.content as NSString
        var imageSource = ""

        let rangeOfString = NSMakeRange(0, htmlContent.length)
        let regex = NSRegularExpression(pattern: "()", options: nil, error: nil)

        if htmlContent.length > 0 {
            let match = regex?.firstMatchInString(htmlContent, options: nil, range: rangeOfString)

            if match != nil {
                let imageURL = htmlContent.substringWithRange(match!.rangeAtIndex(2)) as NSString
                println(imageURL)

                if NSString(string: imageURL.lowercaseString).rangeOfString("feedburner").location == NSNotFound {
                    imageSource = imageURL
                }

            }
        }

        if imageSource != "" {
            cell.itemImageView.setImageWithURL(NSURL(string: imageSource), placeholderImage: UIImage(named: "placeholder"))
        }else{
            cell.itemImageView.image = UIImage(named: "placeholder")
        }

    }

    return cell
}

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    let item = feedItems[indexPath.row] as MWFeedItem

    let webBrowser = KINWebBrowserViewController()
    let url = NSURL(string: item.link)

    webBrowser.loadURL(url)

    self.navigationController?.pushViewController(webBrowser, animated: true)

}
}

FeedTableViewCell.swift
//
//  FeedTableViewCell.swift
//  RSSReader
//
//  Created by Training on 25/12/14.
//  Copyright (c) 2014 Training. All rights reserved.
//

import UIKit

class FeedTableViewCell: UITableViewCell {
@IBOutlet weak var itemTitleLabel: UILabel!
@IBOutlet weak var itemAuthorLabel: UILabel!
@IBOutlet weak var itemImageView: UIImageView!
override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
}

override func setSelected(selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}
}

Feed.h
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>

@interface Feed : NSManagedObject

@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSString * url;

@end

Eu quero apenas colocar meu xml: http://multpesquisa.com.br/busca/a
Como ficaria?
Answer: O link que você postou apesar de também ser um XML não é um Feed RSS.
Para mostrar ele você deve:

Baixar o XML
Parsear o XML e Criar seu Modelo
Mostrar os dados na tela

Pude perceber que você está usando o MWFeedParser. Não será necessário usar ele.
Há diversas formas de fazer esses passos porém as mais simples são:
Baixar o XML
let url = NSURL(string: "http://multpesquisa.com.br/busca/a")

let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in

    if (error == nil) {
        self.xml = data
    }
    else {
        println("Error: \(error)")
    }

}
task.resume()

Parsear o XML Criar seu Modelo
Usando XMLDictionary isso é tão simples quanto
let dictionary = NSDictionary(XMLData: self.xml)
//Estou criando meu modelo aqui ....

Mostrar dados na tela
Agora que você tem os dados no seu modelo é muito fácil! Basta mostrar :D
Mas.. como baixo as imagens?
Da mesma forma que você baixou o XML!
E como eu mostro, então?
let image = UIImage(data: data)
self.imageView.image(image)

Comment: e como eu manipulo item por iem?  pq no xml tem Empresa, e abaixo de empresa tem varios itens, nome, subtitulo, icone, link, etc. esse exemplo que vc postou eh para me criar outro projeto do zero? ou usar o mesmo?
Comment: Esse exemplo é para criar o projeto do zero
Vamos supor que você queira acessar o `subtitulo` do terceiro: `self.dictionary["empresa"]?[(3-1)]["subtitulo"]`
Comment: self.xml = data  esse xml vem de onde? da erro nessa linha
Comment: é um property que você cria `var xml : NSData?` por exemplo
Comment: e se eu quiser mostrar todos ? os nomes e subtitulos
Comment: te enviei o projeto por email

Xml parser em Swift


form numpy array from possible numpy array

Question: EDIT
I realized that I did not check my mwe very well and as such asked something of the wrong question.  The main problem is when the numpy array is passed in as a 2d array instead of 1d (or even when a python list is passed in as 1d instead of 2d).  So if we have
x = np.array([[1], [2], [3]])

then obviously if you try to index this then you will get arrays out (if you use item you do not).  this same thing also applies to standard python lists.
Sorry about the confusion.
Original
I am trying to form a new numpy array from something that may be a numpy array or may be a standard python list.
for example
import numpy as np

x = [2, 3, 1]

y = np.array([[0, -x[2], x[1]], [x[2], 0, -x[0]], [-x[1], x[0], 0]])

Now I would like to form a function such that I can make y easily.
def skew(vector):
    """
    this function returns a numpy array with the skew symmetric cross product matrix for vector.
    the skew symmetric cross product matrix is defined such that
    np.cross(a, b) = np.dot(skew(a), b)

    :param vector: An array like vector to create the skew symmetric cross product matrix for
    :return: A numpy array of the skew symmetric cross product vector
    """

    return np.array([[0, -vector[2], vector[1]],
                     [vector[2], 0, -vector[0]],
                     [-vector[1], vector[0], 0]])

This works great and I can now write (assuming the above function is included)
import numpy as np

x=[2, 3, 1]

y = skew(x)

However, I would also like to be able to call skew on existing 1d or 2d numpy arrays.  For instance
import numpy as np

x = np.array([2, 3, 1])

y = skew(x)

Unfortunately, doing this returns a numpy array where the elements are also numpy arrays, not python floats as I would like them to be.
Is there an easy way to form a new numpy array like I have done from something that is either a python list or a numpy array and have the result be just a standard numpy array with floats in each element?
Now obviously one solution is to check to see if the input is a numpy array or not:
def skew(vector):
    """
    this function returns a numpy array with the skew symmetric cross product matrix for vector.
    the skew symmetric cross product matrix is defined such that
    np.cross(a, b) = np.dot(skew(a), b)

    :param vector: An array like vector to create the skew symmetric cross product matrix for
    :return: A numpy array of the skew symmetric cross product vector
    """
    if isinstance(vector, np.ndarray):
        return np.array([[0, -vector.item(2), vector.item(1)],
                         [vector.item(2), 0, -vector.item(0)],
                         [-vector.item(1), vector.item(0), 0]])
    else:
        return np.array([[0, -vector[2], vector[1]],
                         [vector[2], 0, -vector[0]],
                         [-vector[1], vector[0], 0]])

however, it gets very tedious having to write these instance checks all over the place.
Another solution would be to cast everything to an array first and then just use the array call
def skew(vector):
    """
    this function returns a numpy array with the skew symmetric cross product matrix for vector.
    the skew symmetric cross product matrix is defined such that
    np.cross(a, b) = np.dot(skew(a), b)

    :param vector: An array like vector to create the skew symmetric cross product matrix for
    :return: A numpy array of the skew symmetric cross product vector
    """

    vector = np.array(vector)

    return np.array([[0, -vector.item(2), vector.item(1)],
                     [vector.item(2), 0, -vector.item(0)],
                     [-vector.item(1), vector.item(0), 0]])

but I feel like this is inefficient as it requires creating a new copy of vector (in this case not a big deal since vector is small but this is just a simple example).
My question is, is there a different way to do this outside of what I've discussed or am I stuck using one of these methods?
Comment: Which numpy version are you using? For numpy 1.10.4 getting a single element from an array returns a scalar not a numpy array so your initial function works like you wanted.
Comment: I am using 1.10.4 @MSeifert, however I made a mistake in my question.  the main problem is that I am using 2d arrays to emulate column vectors.  I will fix this.
Answer: You can implement the last idea efficiently using numpy.asarray():
vector = np.asarray(vector)

Then, if vector is already a NumPy array, no copying occurs.
Answer: You can keep the first version of your function and convert the numpy array to list:
def skew(vector):

    if isinstance(vector, np.ndarray):
        vector = vector.tolist()

    return np.array([[0, -vector[2], vector[1]],
                     [vector[2], 0, -vector[0]],
                     [-vector[1], vector[0], 0]])

In [58]: skew([2, 3, 1])
Out[58]:
array([[ 0, -1,  3],
       [ 1,  0, -2],
       [-3,  2,  0]])

In [59]: skew(np.array([2, 3, 1]))
Out[59]:
array([[ 0, -1,  3],
       [ 1,  0, -2],
       [-3,  2,  0]])

Answer: This is not an optimal solution but is a very easy one.
You can just convert the vector into list by default.
def skew(vector):
    vector = list(vector)
    return np.array([[0, -vector[2], vector[1]],
                     [vector[2], 0, -vector[0]],
                     [-vector[1], vector[0], 0]])

Comment: do you know if list creates a copy if vector is already a list?  @John Zwinck below seemed to imply that asarray does not copy if the inside is already an array which would seem to be at least a little more efficient.
Comment: can you explain the added value of your question considering I gave this answer minutes before?
Comment: Are you referring to me @ColonelBeauvel?
Comment: Sorry, I haven't seen your answer I was already writing mine. However, mine is way less wordy and I am not sure that calling isinstance() would add anithing more...
Comment: `.tolist()` is better if the array may be 2d.
Answer: Arrays are iterable. You can write in your skew function:
def skew(x):
    return np.array([[0, -x[2], x[1]],
                     [x[2], 0, -x[0]],
                     [-x[1], x[0], 0]])
x = [1,2,3]
y = np.array([1,2,3])
>>> skew(y)
array([[ 0, -3,  2],
       [ 3,  0, -1],
       [-2,  1,  0]])
>>> skew(x)
array([[ 0, -3,  2],
       [ 3,  0, -1],
       [-2,  1,  0]])

In any case your methods ended with 1st dimension elements being numpy arrays containing floats. You'll need in any case a call on the 2nd dimension to get the floats inside.
Regarding what you told me in the comments, you may add an if condition for 2d arrays:
def skew(x):
     if (isinstance(x,ndarray) and len(x.shape)>=2):
         return np.array([[0, -x[2][0], x[1][0]],
                          [x[2][0], 0, -x[0][0]],
                          [-x[1][0], x[0][0], 0]])
     else:
         return np.array([[0, -x[2], x[1]],
                          [x[2], 0, -x[0]],
                          [-x[1], x[0], 0]])

Comment: 1d arrays are easily iterable yes, however, 2d arrays are more complicated.  for instance, if `x=np.array([[1], [2], [3]])` then the above will not work (I generally keep my arrays as 2d to emulate column vectors).  sorry I was not clear in my question.  I will fix this
Comment: so I realize now that the best option is to use `x[1][0]` to index as this will always work for up to 2d arrays or lists without making a copy.  Can you update your answer to reflect this and I will then accept?
Comment: For numpy arrays you can check the lenght of 'vector.shape' method (2 for 2d arrays). For nested lists it may get a bit more tricky.
Comment: Thanks for making the update.  I would argue that you don't even need to go that far.  One could very easily write `np.array([[0, x[2][0], x[1][0]],...` regardless of whether `x` is 1d or 2d.
Answer: In fewer lines
def skew(vector):
    return np.cross(np.eye(vector.size), vector.reshape(-1))

Comment: This is definitely a nice use of the theory, though its going to be relatively inefficient (of course, in all likelihood the efficiency difference is going to be negligible unless you are repeatedly using this function within some critical portion of the code, in which case the overhead of python is probably going to dominate anyway)
Comment: Indeed, I measure a 10x penalty over the direct construction method.
Answer: Just to add another option that removes conditionals to this old question.  This uses ravel (which does not make a copy) to "flatten" the array so its only 1D.
def skew(vector):
    """
    this function returns a numpy array with the skew symmetric cross product matrix for vector.
    the skew symmetric cross product matrix is defined such that
    np.cross(a, b) = np.dot(skew(a), b)

    :param vector: An array like vector to create the skew symmetric cross product matrix for
    :return: A numpy array of the skew symmetric cross product vector
    """

    vector = np.asarray(vector).ravel()

    return np.array([[0, -vector[2], vector[1]],
                     [vector[2], 0, -vector[0]],
                     [-vector[1], vector[0], 0]])

Additionally, for those interested, there is a form that handles multiple vectors at once (using multi-dimensional arrays) at https://github.com/nasa/giant/blob/main/giant/rotations.py#L1164


How to prove that a sequence is null?

Question: How to prove that ${2\over n^2}$ is a null sequence?
Comment: Do you know how to prove $\frac{2}{n} \rightarrow 0, n \rightarrow \infty$? Or that $\left\{\frac{2}{n^2}\right\}$ is descending and bounded?
Answer: You wish to show that for each $\epsilon > 0$ there exists a number $N=N(\epsilon) \in \mathbb{N}$ such that for all $n > N$,
$$\left|\dfrac{2}{n^2}-0\right| = \left|\dfrac{2}{n^2}\right| < \epsilon$$
Working backwards, we obtain
$$n^2>\dfrac{2}{\epsilon}\implies \sqrt{n^2}=|n|=n>\sqrt{\dfrac{2}{\epsilon}}$$
So, take $N$ to be
$$N = \left\lceil\sqrt{\dfrac{2}{\epsilon}}\ \right\rceil$$
where the ceiling function $\lceil \cdot \rceil$ is used.

Proof. Let $\epsilon > 0$ be given. Choose $N = \left\lceil\sqrt{\dfrac{2}{\epsilon}}\ \right\rceil$. Then for all $n > N$,
  $$\left|\dfrac{2}{n^2}-0\right|=\left|\dfrac{2}{n^2}\right|<\left|\dfrac{2}{N^2}\right|=\left|\dfrac{2}{2/\epsilon}\right|=\epsilon\text{.}$$
Comment: @Shashi Thank you, that was bothering me!
Comment: I hope the edits are as fine as your answer :)

How to prove that a sequence is null?


query_posts , pegar a categoria e subcategoria

Question: Bom dia a todos.
Pela primeira vez venho pedir ajuda, depois de muitas tentativas (sou iniciante).
Eu estou querendo listar vários posts (poste_type chamado=familia_peixe ) pela categoria e subcategoria.
(Eu estou tentando aproveitar um loop que está funcionando em outra página, que mostra todos os post.)
<?php query_posts('familia_peixe_familia=familia_ordem_peixe & showposts= -1 & orderby=title');?>
                            <?php if (have_posts()): while(have_posts()) : the_post();?>

<?php if (get_post_meta($post->ID, 'classificacao_peixe_ordem', true)):?><a href="<?php  $key="classificacao_peixe_ordem";echo get_post_meta($post->ID, $key, true);?>" title="<?php echo get_post_meta( $post->ID, 'familia_peixe_ordem', true ); ?>" >Lista ordem dos :  <?php if (get_post_meta($post->ID, 'classificacao_peixe_ordem', true)){echo get_post_meta( $post->ID, 'classificacao_peixe_ordem', true );} ?><?php endif?>

<?php the_title();?>

  <?php echo excerpt(80); ?>

                            <?php endwhile; else:?>
                            <?php endif;?>

Este é o que eu pretendia
Answer: Você não disse qual erro está tendo, mas eu suponho que deve estar sem receber resultados, certo? Seu código atual está especificando a taxonomia familia_peixe_familia e o termo familia_ordem_peixe mas não especifica o post_type, então query_posts() está procurando no tipo Post.
Reescrevendo sem usar query_posts() porque usar query_posts nunca é uma boa ideia:
<?php
$consulta = new WP_Query( array (
    'post_type' => 'familia_peixe',
    'posts_per_page' => 100, // use 100 ao invés de -1 para evitar problemas futuros
    'tax_query' => array( array(
        'taxonomy' => 'familia_peixe_familia', // taxonomia
        'term' => 'familia_ordem_peixe', // termo
        'field' => 'slug',
    ) ),
    'orderby' => 'title',
) );

if ( $consulta->have_posts()): while( $consulta->have_posts()) : $consulta->the_post(); ?>

Comment: Obrigada Ricardo. O problema que tinha, mas que nao era 100% um problema era que estava querendo fazer com que em baixo de cada categoria mae estivesse as sub categorias. O código como estava escrito funcionava bem, mas nao pela hierarquia certa. Nao deu para eu fazer como eu queria 100%, mas deu para resolver de uma outra forma. Mais uma vez obrigada pela ajuda


Issue with matplotlib where subplots are overwritten

Question: I am having trouble with formatting my matplotlib figure, I am trying to take in several subfigures and then graph them to a single figure. What I get instead is the figures overlap and graph on the the same axis rather than being plotted to a different axis. I have attached an image of the corresponding figure as well as the code snippets below. I had based my code off this example by matplotlib for creating subfigures
This is what I have in my main file
fig = plt.figure(constrained_layout=True, figsize=(14, 5))
subfigs = fig.subfigures(1, 2, wspace=0.07)

axsLeft = subfigs[0].subplots(3, 1)
for ax in enumerate(axsLeft):
    pc = plot_acceleration(recording_df, recording_id)

axsRight = subfigs[1].subplots(3, 1)
for ax in enumerate(axsRight):
    pc = plot_gyroscope(recording_df, recording_id)

fig.suptitle("Figures for Times", fontsize="xx-large")

plt.show()

And then in a separate python file I have the following functions that are being called from the code snippet above:
def plot_acceleration(data_df: pd.DataFrame, recording_id: str):
    skipping a lot of other code...

    fig = plt.figure(1)

    plt.subplot(3, 1, 1)
    plt.title(recording_id + "\nAcceleration versus time")

    plt.subplot(3, 1, 2)
    plt.plot(time, y_accel, ".-")

    plt.subplot(3, 1, 3)
    plt.plot(time, z_accel, ".-")

    return fig

def plot_gyroscope(data_df: pd.DataFrame, recording_id: str):
    skipping a lot of other code...

    fig = plt.figure(1)

    plt.subplot(3, 1, 1)
    plt.plot(time, x_gyro, ".-")

    plt.subplot(3, 1, 2)
    plt.plot(time, y_gyro, ".-")

    plt.subplot(3, 1, 3)
    plt.plot(time, z_gryo, ".-")

    return fig

From what I understand it must be an issue with the fig = plt.figure(1) lines in both functions but I can't figure out what to do resolve it, I don't think I can try to return subplots because that might not be correct.
Answer: You handle the plot related objects both in the main code and in the functions and there is no communication, so your plotting functions just recreate new figures.
You should reorganize your code to have the plotting function not handle any figure related level but rather get sub-elements on which to plot passed as parameters.
Below is dummy code to illustrate my point:
def plot_acceleration(data, subfig):
    # do something with subfig directly, not recreating new figure

fig = plt.figure(...)
subfigs = fig.subfigures(...)

for subfig in subfigs:
    plot_acceleration(data, subfig)

Comment: Hi! I tried your recommendation but it still doesn't work! I created a function that would pass in the subfigures in but it still does not graph them properly.


Categorical exponentiation distributes over categorical products, naturally.

Question: We are to show that in a Cartesian closed category (ccc) $\mathcal{C}$, that for any objects $X, Y, Z$, there exists a natural isomorphism $(Y \times Z)^X \cong Y^X \times Z^X$.
Disclaimer: all of this is in preparation of, so 'not using' the Yoneda Lemma (or adjunctions). It should be doable by the the definition of the exponential itself (and of course the relevant universal property of the product).
First off, I don't think (nor hope) the use of 'natural' here is the one that is defined earlier in the notes (being a natural transformation that is an isomorphism in, in this case, the endofunctor category $[\mathcal{C}, \mathcal{C}]$, i.e., an isomorphism at each component. This would require the objects to be lifted to functors and things will quickly get messy and tedious..
So I will suppose the use of 'natural' here is colloquial. In my text, being an exponential of $Y\times Z$ and $X$ means that there is a pair of an object and a morphism $((Y \times Z)^X, \text{ev} : (Y \times Z)^X \times X \to Y \times Z)$, having a certain universal property that can be expressed as a diagram but also as the fact that for each object $A$,
\begin{align*}
\text{Hom}_{\mathcal{C}}(A, (Y \times Z)^X) &\to \text{Hom}_{\mathcal{C}}(A \times X, Y \times Z) \\
H &\mapsto \text{ev} \circ (H \times \text{id}_{Y \times Z})
\end{align*}
is a bijection.
Is the idea to use the map given by the universal property of th product $Y^X \times Z^X$, or is there some other trick of matching/gluing the diagrams for products and exponentials together, or is it easier to just work with Hom-sets here? Or something else entirely?
EDIT
I actually do prefer to proceed with the Hom-sets. Namely (I write $\leftrightarrow$ for bijection), by the product properties and exponential properties, respectively, we have, for all objects $A$, bijections
\begin{align*}
\text{Hom}_{\mathcal{C}}(A, Y^X \times Z^X) &\leftrightarrow \text{Hom}_{\mathcal{C}}(A, Y^X) \times \text{Hom}_{\mathcal{C}}(A, Z^X) \\
&\leftrightarrow \text{Hom}_{\mathcal{C}}(A \times X, Y) \times \text{Hom}_{\mathcal{C}}(A \times X, Z).
\end{align*}
But then, using the universal property of the exponential again, we obtain
\begin{align*}
\text{Hom}_{\mathcal{C}}(A, (Y \times Z)^X) &\leftrightarrow \text{Hom}_{\mathcal{C}}(A \times X, Y \times Z) \\
&\leftrightarrow \text{Hom}_{\mathcal{C}}(A \times X, Y) \times \text{Hom}_{\mathcal{C}}(A \times X, Z) \\
&\leftrightarrow \text{Hom}_{\mathcal{C}}(A, Y^X \times Z^X).
\end{align*}
Now I am beginning to see how powerful Yoneda is, I think. (I do know the theorem, and therefore I strongly believe that this is it, as we have now derived $\text{Hom}_{\mathcal{C}}(A, Y^X \times Z^X) \leftrightarrow \text{Hom}_{\mathcal{C}}(A, (Y\times Z)^X)$. Since this holds for all $A$, I would presume that this translates to the functor isomorphism $\text{Hom}_{\mathcal{C}}(-, Y^X \times Z^X) \cong \text{Hom}_{\mathcal{C}}(-, (Y\times Z)^X)$.
I think I am therefore there, but if anyone could close the loop on this would be even better :)
Comment: First of all, your universal property is wrong. That aside, try writing down morphisms in both directions using the universal properties and the canonical morphisms that you already have. There will essentially only be one thing in each direction you can reasonably come up with. Then, another application of the respective universal properties will show these morphisms are actually inverse. This isomorphism is natural (in the sense of functors) in all three variables, even, meaning if you consider both sides as functors $C\times C\times C\rightarrow C$.
Comment: Ah, thanks for spotting the mistake, I got confused with the notation, and corrected it. And thanks for the tip, I'll get right to it!
Answer: Think I've closed the loop myself: since the bijections $\phi_A : \text{Hom}_{\mathcal{C}}(A, (Y\times Z)^X) \leftrightarrow \text{Hom}_{\mathcal{C}}(A, Y^X \times Z^X)$ exists for all objects $A$ (in particular for $A := Y^X \times Z^X$), and since $\text{id}_{Y^X \times Z^X} \in \text{Hom}_{\mathcal{C}}(Y^X \times Z^X, Y^X \times Z^X)$, surjectivity of the corresponding $\phi_{Y^X \times Z^X}$ now ensures that this identity is reached. Thus, for some morphism $f : (Y\times Z)^X \to Y^X \times Z^X$, we have
$$\text{id}_{Y^X \times Z^X} = f\circ \phi_{Y^X \times Z^X}(f),$$
obtaining a right-inverse of $f$.
By the injectivity of the $\phi_A$, this morhpism is unique with this property.
Now we can choose $A:= (Y \times Z)^X$ and apply the argument in reverse (using $\phi_{(Y \times Z)^X}^{-1}$) to find a (unique) left-inverse of $f$, thereby obtaining a unique isomorphism $(Y \times Z)^X \to Y^X \times Z^X$.
Being unique, this isomorphism should be pretty natural, I would presume ^^
Comment: be careful! the isomorphism is not at all unique (e.g. look at the situation in Set), it is only the unique one compatible with the structure maps of the products and exponentials.
Comment: Thanks! I'll look to see if I can show that (mainly: what explicitly that means) later!


Identifying a number of significance from a histogram

Question: I'm creating a program that identifies trending music artists that uses Twitter metrics. I have data in a histogram format that represents the frequency of twitter @mentions of an artist for the last 30 days. I need my program to recognize a "significant" change (number that is quite greater than the rest in the sample) in the frequency of @mentions. Here is a data sample:
histogram:
      [ 43,
        17,
        70,
        137,
        198,
        113,
        126,
        96,
        100,
        130,
        107,
        112,
        438,
        215,
        76,
        30,
        119,
        78,
        38,
        27,
        27,
        35,
        29,
        38,
        59,
        35,
        164,
        113,
        29,
        111 ],
In this scenario, 438 is the number of significance. It's fairly obvious in this data set b/c it is 2x greater than any other value.
I need to build an equation that recognizes this number of significance across various data sets. In my first attempt at writing this equation, I will calculate the average of the 30 values and compare the average to the highest value in the data set. After doing some sampling, I will come up with a percentage difference that justifies significance.
This is a simple approach, but I'm worried its too subjective. Are there any other ways of doing this?
Comment: So you're looking to do outlier detection?
Comment: Yes. Is there an equation I can refer to for this? The only statistics I know is from a 101 course in college :)
Comment: I'd follow up on @Dason's comment and look up the various ways to test for the statistical significance of outliers in a distribution.
Answer: There is no universal definition of an outlier. One criterion amongst others is what I call the "boxplot criterion". It is in fact the criterion that is frequently used to compute the length of the whiskers in a boxplot. This criterion has been put forward in Tukey's book on Exploratory Data Analysis.
Anything outside the following interval could be considered as an outlier:
$$ [Q_1 - 1.5*(Q_3 - Q_1), Q_3 + 1.5*(Q_3 - Q_1)] $$
where $Q_1$ is the first quartile and $Q_3$ is the third quartile of the variable of interest. If you apply this rule to the data above, you will see that the value 428 will come out as an outlier.
For what it's worth, the hardest part is not the detection of an outlier (once you have agreed on a definition), but what you should do about it. You can have a look at the questions under the outlier tag.


Is there a more intuitive term for a "Linear model"?

Question: A model is linear if it is linear in the parameters. Therefore, a linear model can describe a curve, if a function (such as raising to a power, but not necessarily) is performed on one of the variables.
The name "linear model" is very unintuitive; intuitively the term conjures a line, not a curve.

Is there a term that would fit the definition of a linear model, but be more intuitive to understand?

Is there a way to make the term "Linear model" more intuitive to myself?
( This part of the question is a one on studying skills).
Comment: What does "intuitive" mean any way? I translate it as "familiar to me and should be easy for you too". It is sometimes advertising, as in "this software has an intuitive interface" (so, the more you use it, the easier it gets), and sometimes an implied put-down if you don't work on the same level as the writer ("the result is intuitive given Fubini's theorem" or the Cauchy-Schwarz inequality, or whatever). It's a subtlety that has to be learned that "linear in parameters" is deeper and wider than "linear in variables" and thinking up different language for that won't make it easier.
Comment: "linearly parameterized models"?
Comment: I don't have another / better term. For your own understanding, here are two threads that may help:  [Why is polynomial regression considered a special case of multiple linear regression?](https://stats.stackexchange.com/q/92065/7290); & [How to tell the difference between linear and non-linear regression models?](https://stats.stackexchange.com/q/148638/)
Comment: I don't see a problem with the term *linear model*. It's as intuitive as anything else. As Underminer noted, *regression* is a possible substitute with the obvious caveat that its use would be limited to a nontechnical audience. Anyone with even a moderate degree of statistical sophistication would demand more specificity. That said, my suggestion is to use the words *classic regression*. This phrase can be tracked back to how OLS or linear regression is taught in Stats 101 and, therefore, should be recognizable to all.
Comment: If you are familiary with linear algebra, then 'linear model' is very intuitive :)
A way to make the term 'linear model' more intuitive to you could be Bapat, _Linear Algebra and Linear Models_, Springer, 2012.
Answer:
For an alternative name, I think referring to the model as a Regression Model or simply as a Regression may be more intuitive to others.  Regression models are most commonly linear models (but also include non-parametric and non-linear models).  Since you are looking for something more intuitive, I think this would be easy to understand by others since most people intuit regression as a type of "line-fitting" and don't care if it's a straight line or a curved line.

Since you already understand that a linear model is linear in the parameters, I don't think there is a more intuitive way to think of it by yourself.  You understand the technical reason why linear models are named the way they are, and now have the responsibility to explain that reason to others, or you can dumb-it-down to layman's terms.


Adding predictor variables to hurdle model

Question: I am trying to build GAMs to understand the detectability of two cetacean species using acoustic and visual data. For now, I am running three separate models (All detections (encounters), Acoustic detections (acoustic), and Visual detections (visual)). My response variable is count data (detections along a line segment). And predictor variables are sea swell, bft scale, swell in meters, depth of water, distance from shore for the detection, time of day, month, and area. I have an effortkm offset as each survey line is of slightly different lengths. My aim is to understand which of these factors (if any) influence the detectability of the species.
Many of the lines, don't have any encounters, so I have a lot of zeros, especially for the visual detection model (example dataframe in image link)

I ran zero inflation GAM in mgcv and it works okay for encounters and acoustic but for the visual model I get an error:
Warning: Fitting terminated with step failure - check results carefully.
In my case, would a hurdle model work better? I tried the hurdle model in mgcv but I am having trouble adding my categorical variables. I am able to add them to only one part of the model:
<code>fp_hurdle_enc <- gam(list(encounters ~
      s(swell, k = 5) +
      s(dist, k = 5) +
      s(depth, k = 5) +
      s(time, k = 5),
    ~ s(swell, k = 5) +
      s(dist, k = 5) +
      s(depth, k = 5) +
      s(time, k=5) +
      bft2 + area + month + offset(effortkm)),
  data = porpoise, method = "REML",
  family= ziplss(link=list("identity","identity")))
</code>
Does this mean that it is using the categorical variables in one part of the model and not the other? Also when I try to fit the same to the visual detections, it gives the following error:
<code>*Error in gam.fit5(x, y, sp, Sl = Sl, weights = weights, offset = offset, :
indefinite penalized likelihood in gam.fit5*
</code>
Its a smallish data set, I have about 331 data points, with 136 encounters, out of which 132 are acoustic and 37 are visual.
I'm very new to GAM, and would really appreciate help in navigating these errors. Any alternate method suggestions are welcome!
Comment: I am not an expert on GAMs but fitting a model with so many covariates to a dataset (visual encounters) with so few events strikes me as very ambitious.
Answer: As @mdewey says, this would be very ambitious indeed with 331 data points, let alone a smaller data set (if that is what is implied by 37 visual encounters?).
Anyway, it looks like you have the linear predictors back to front. The first formula is for the Poisson part of the model so I would expect the offset to be in that count model and not in the binomial part, which comes second in the list of linear predictors.
Currently the categorical variables are only in the binomial part of the model.
It wouldn't surprise me if you are able to perfectly (or nearly perfectly) predict the 0s and 1s with a data set this small and all those terms in the binomial part of the model, which can lead to errors like this. Even if it is not this specific problem, this error often arises when the model is not identifiable or you are trying to fit too many terms to the data at hand.
Finally, lots of 0s doesn't imply zero-inflation; it could well be that the 0s arises from a low expected count. Zero-inflation can only be assessed with respect to the mean model; does your data have more zeroes than can be generated by your model?
I would suggest starting off simply and model the counts with a Poisson of Negative Binomial model and compare the expected number of 0s with the observed number (using say a rootogram).


How to hook to content profile edit form validation

Question: I try the following code, but it doesn't seem to work.
function mymod_profile_node_form_validate($node,&$form) {
  firep($form, 'form');
}

Could anybody help?
Answer: If you would like to add a custom validation to a form 1st you're going to have to modified the form and inject your validation.
So 1st lets infect our validation into a form.
/**
 * Implements hook_form_alter()
 */
function hook_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'name_of_the_form_we_want_to_alter') {
    // Notice that we're appending to the array, we not replacing, this is to keep the regular validation function.
    $form['#validate'][] = 'name_of_our_custom_validation_function';
  }
}

Now we need to add out validation function:
function name_of_our_custom_validation_function($form, &$form_state) {
 //We do all our processing in here.
}

This should cover most use cases in Drupal 6 and 7.
Answer: It will not work as it is not a hook.
Try hook_form_alter() to edit form so that $form['#validate'] can be defined.
$form['#validate'] = !empty($form['#validate']) ? $form['#validate'] + array('mycustom_validate_handler') : array('mycustom_validate_handler');

Then define your function
function mycustom_validate_handler($form, $form_state){
     // Do your validation.
}


jQuery AJAX, GET, POST JSON issue, getting no response it seems

Question: $.ajax({
type: 'POST',
dataType: 'json',
url: "http://domainsvault.com/test.json",
error: function(){alert('An unexpected Error occured while processing the resquest, reload the page to try again');},
timeout: 7200,
success: function()
{
    document.write('

');
    $.each(data.items, function(i, item)
    {
        //document.write('
');
        document.write(' ');
    });
}

});
the JSON http://domainsvault.com/test.json
{"items":[{"name":"hamburger","description":"A two-patty cheeseburger","image_url":"http://www.rw-designer.com/icon-view/5734.png"},{"name":"hot dog","description":"A hot dog with mustard","image_url":"http://www.rw-designer.com/icon-view/5735.png"},{"name":"pizza","description":"Pepperoni pizza","image_url":"http://www.rw-designer.com/icon-view/5743.png"},{"name":"ice cream","description":"Soft-serve ice cream","image_url":"http://www.rw-designer.com/icon-view/5739.png"},{"name":"fountain drink","description":"Ice cold drink","image_url":"http://www.rw-designer.com/icon-view/5741.png"}]}

Far as I can tell the JSON is valid. The code is working if I hardcode the string it works fine for the $.each(). However attempting to get the JSON from the URI via post or get my response in Firebug is "200 OK" and shows it in red as if the File wasn't found.
Comment: Is your page running on that domain?
Comment: are you requesting from same domain, also from server response headers contain 'application/json'
Comment: That you're using `document.write` at all is worrisome. Avoid it at all costs, unless you ***really*** know what you're doing. You've got jQuery, so why wouldn't you just use [`.append()`](http://api.jquery.com/append)?
Comment: Ajax requests to third party websites are normally not possible because of security restrictions.
Comment: this should be the umpteenth cross domain policy request using $.ajax
Answer: Look at the response you are getting.

http://jsfiddle.net/praveen_prasad/tnaWd/
Answer: try using jQuery.getJSON() http://api.jquery.com/jQuery.getJSON/
it can run cross domain


Libraries in custom module

Question: I have the following 2 files in 2 different directoties in a custom module directory.
modules/custom/calculator
This is my info.yml file (calculator.info.yml)
name: calculator
type: module
description: Calculator
core: 8.x
package: Custom

My css is in  the directory modules/custom/calculator/css and js in the modules/custom/calculator/js directory
My libaries file is this: (calculator.libraries.yml)
base-style:
  version: VERSION
  css:
    component:
      css/wunderpage.css: {}
  js:
    js/wunderpage.js: {}
    js/jquery.matchHeight-min.js: {}

I also have a calculator.module file :
<?php

/**
 * @file
 * Contains calculator.module..
 */

use Drupal\Core\Routing\RouteMatchInterface;

/**
 * Implements hook_help().
 */
function calculator_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    // Main module help for the calculator module.
    case 'help.page.calculator':
      $output = '';
      $output .= '
' . t('About') . '
';
      $output .= '
' . t('Calculator') . '
';
      return $output;

    default:
  }

  function calculator_preprocess_page(&$variables) {
    $variables['#attached']['library'][] = 'calculator/base-style';
  }
}

Still my css and js etc is not being loaded.
Somebody knows why my libraries are not being loaded?
Comment: hook_page_attachments
Answer: Either you made a mistake when copying and pasting that PHP code, or you defined calculator_preprocess_page() as being inside calculator_help(). Also, as Ivan Jaros also pointed out, Drupal 8 requires you to use hook_page_attachments() to attach page-level assets.
I do recommend you add these assets elsewhere in the code, preferably in the render array you build that actually needs the library.

Libraries in custom module


read float from SQLite

Question: I used the codes below to load data(float) and store in an array.
My oject has one float field 'value' (setValue,getValue to read or write value)
rowData=(char*)sqlite3_colum_text(statement,0);
float v=[[NSString  initWithUTF8String:rowData] floatValue];
[myObject setValue:v];
[myArray addObject:myObject];

If I read the value from the array using
    float tem=[[myArray objectAtIndex:i] getValue];
I found all values are not correct, everyone is 0.00000000000000
Welcome any comment
Thanks
interdev
Answer: If your values are stored as float numbers in database you should get them using sqlite3_column_double function, not sqlite3_column_text
Comment: Can you please give me any example?

read float from SQLite


Is there a standard way to conduct 5/4 and 7/4, amongst other irregular time signatures?

Question: We expect the downbeat to be signified with exactly that from a conductor - a downstroke of the baton. With 3/4 and 4/4, and often 6/8, that's pretty straightforward to achieve, with a maximum of 4 distinct movements from the conductor.
But what about more complex time signatures. It's been a long, long time since I watched Mars, in 5/4 for example, so am asking how would that be conducted? Is there an 'industry standard'?
Comment: I don't think there's one answer. Sometimes there are multiple downbeats conducted per measure. Other times the macro structure will be conducted only. Also of course different ensemble types have different standard conducting styles.
Answer: There'll be a downbeat on 'One' and (more importantly) an upbeat preceding it on 'Five'.  In-between, whatever, though there's generally an 'out, up' on '4,5', increasingly pronounced as the music gets 'bigger'.
Here's a couple of random YouTube hits.   What I found  interesting was different conductors' choice of preparatory beats at the very start.  'Mars'  pretty clearly sets off in a 3+2 grouping, so Andrew Lytton's two-beat preparation seems logical.

Susanna Mälkki gives three.  Well, OK...  Either way, it's quite clear where the music starts.
Answer: It depends on how fast it is.  If it's fast, you can't conduct all five or seven beats.  A little slower, where it's possible to conduct them, you still might not want to.  In these cases, you typically conduct 5 in a 2 pattern, with one beat being 50% longer than the other.  In 7, you similarly use a 3 pattern with one beat being 50% longer than the other two.
For slower speeds where you do want to indicate five or seven beats in each measure, you typically conduct a subdivided 2 or 3 pattern, just as 6/4 can be thought of as a two pattern with each beat subdivided in three, or 3/2, when conducted "in 6" typically uses a 3 pattern with each beat subdivided in two.
Thus the 5 pattern becomes down-in-out-out-up for 2+3 and down-in-in-out-up for 3+2.  Similarly, the 7 pattern is down-in-in-out-out-(more)out-up, down-in-out-out-out-(more)out-up, or down-in-out-out-(more)out-out-up.
Thanks to Chris Strickland for some visual aids:

https://www.classicfm.com/artists/marin-alsop/guides/masterclass-beating-time/

And

The "subdivided upbeat" patterns (b and c in the image) are standard, but I did not mention them because I find them awkward and misleading.  They result in a large upward motion that doesn't serve as the preparation for a downbeat, and they leave the baton in too high a position to be able to give an appropriate preparation for the downbeat.
Comment: @ChrisStrickland I know.  I just wanted to connect the "cumbersome" observation back to the beginning of this answer and to try to clarify what I meant about patterns -- or rather certain details of the patterns -- being less significant to players than many people seem to think.
Comment: I had conducting class, and that's about it.  I have "conducted" a few groups of varying complexity since then but I've always had my hands full of guitar or bass or trombone.  We had a book of patterns, which seem similar to what you describe and they were similar to these (5/4 is at the bottom): _[https://www.classicfm.com/artists/marin-alsop/guides/masterclass-beating-time/]_.  The 7s were similar to these, although there are clearly more options: _[https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRxqQ-ZEWItPQ1xQB0gcOOFmYsDOsNusyiLgcNLsgUV0Q&s]_
Comment: @ChrisStrickland "more options" indeed.  I find that patterns are more important for the conductor than the ensemble, most of whom don't pay much attention to anything more than the downbeat.  Thanks for those links; I don't remember whether I ever even had a conducting textbook, and I didn't find any decent resources from a quick search.  The square brackets broke the links, though; I'll fix them and add them to the answer.  I don't use the "subdivided upbeat" patterns because they lack the desirable (critical?) property that the preparation for the downbeat is the largest upward motion.
Comment: Didn't realize about the links. I think you're right about the ensemble, but sometimes the pattern can be helpful in initial rehearsal to communicate expectation. Yes, patterns can quickly get cumbersome at fast tempi, and in my experience the more beats per measure the more likely that it's going to be a compound meter and the individual beats too quick to conduct. Also a no to the subdivided upbeats. We were taught big downbeat in the middle, and big upbeat directly to the right of the middle and all strokes should touch (or approach) the horizontal plane, regardless of how you group.
Comment: @ChrisStrickland "cumbersome at fast tempi": this is why you conduct fast 5 or 7 as 2 or 3 with one beat being 50% longer (or again there are other possibilities for unequal beats as seen in https://music.stackexchange.com/q/125340/2257).  My main point about details of specific patterns though is that 99% won't notice (and those on either side can't even see) whether a given beat is left, right, center, or what have you. For the most part the pattern helps the conductor keep track; the players are more helped by relative sizes of beats than their location.
Comment: I'm agreeing with you.


Formatting sandbox — please test stuff here

Question: This post is provided so that people can, in the answers and comments below, test formatting features of Expats Stack Exchange.
Answer: Testing YouTube URL Embedding
Regular https://www.youtube.com/watch?v=gocwRvLhDf8
https://www.youtube.com/watch?v=gocwRvLhDf8

Timestamped https://www.youtube.com/watch?v=gocwRvLhDf8&t=22
https://www.youtube.com/watch?v=gocwRvLhDf8&t=22

Shortened https://youtu.be/gocwRvLhDf8
https://youtu.be/gocwRvLhDf8

/Embed https://www.youtube.com/embed/gocwRvLhDf8
https://www.youtube.com/embed/gocwRvLhDf8

Embedded HTML

Mobile https://m.youtube.com/watch?v=gocwRvLhDf8
https://m.youtube.com/watch?v=gocwRvLhDf8

Flash Player https://www.youtube.com/v/gocwRvLhDf8
https://www.youtube.com/v/gocwRvLhDf8

YouTube TV https://www.youtube.com/tv#/watch/video/idle?v=gocwRvLhDf8
https://www.youtube.com/tv#/watch/video/idle?v=gocwRvLhDf8

See Which sites have YouTube embedding on?


How to write specific CSS statements for mozilla, chrome and IE

Question: can you please let me know how to write single statement to with specific for IE, Mozilla, Chrome.
Comment: I got [this](http://stackoverflow.com/questions/4332117/how-to-write-specific-css-for-mozilla-chrome-and-ie?rq=1) from the right hand side column and am sure you would've got that while typing the question...
Comment: The better practice is never use single statements for each browser ... maybe the only one are for IE <= 8.
Answer: Whether using this approach to target browsers specifically is a good idea or not is a seperate question in itself. However, assuming you have a legitimate reason to target browsers as you asked, there are couple of ways you can achieve your goal
CSS Browser Specific Selector Hacks
browserhacks.com has an exhaustive list of browser specific selector based hacks that will apply to only specific browsers. Also, as Mr. Alien suggests, this question details browser hacks well too.
CSS Browser Selector JS Library
This library will add classes to the root html tag that indicate browsers and more other potentially useful info: https://github.com/ridjohansen/css_browser_selector/
Once you've included the library, it . You can use those classes to target specific browsers in css similar to this:
.chrome .some-class { } /* Will only apply in chrome (all versions) */
.ie .some-class { } /* Will only apply in IE (all versions) */
.ie7 .some-class { } /* Will only apply in IE7 */
.opera .some-class { } /* Will only apply in Opera (all versions) */

The library will add a bunch of classes that can be used to target based on browser, browser version, platform, platform version, device, device version etc. Check the documentation in the github link for full details.
Comment: answer for this question is "@-moz-document url-prefix(){}"


Can I format currency when sending email using google app Script?

Question: I create a page with google Script for orders . When the order is finished, it will automatically save to Google sheet and email a copy to the customer (in normal email format/text). The money display for email I want to format is 1,000,000 (with commas).
The part I want to format is .
This is my code

function doGet(e) {
var htmlOutput =  HtmlService.createTemplateFromFile('index');
htmlOutput.message = '';
return htmlOutput.evaluate();
}

function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename)
.getContent();
}
/* @Include JavaScript and CSS Files */
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename)
.getContent();
}

/* @Process Form */
function processForm(formObject) {
var url = "https://docs.google.com/spreadsheets/d/10s7pV1Rv1jy--EQxVg-86ikNfj5KGmyfLdYwVO-Qpzs/edit#gid=0";
var ss = SpreadsheetApp.openByUrl(url);
var ws = ss.getSheetByName("注文リスト");

ws.appendRow(["H Guard社 インフル&コロナ ダブル検査キット",
formObject.numberProductHGuard,
formObject.priceProductHGuard,

"DIAsia社 口腔内粘膜(唾液)コロナ検査キット",
formObject.numberProductDIAsia,
formObject.priceProductDIAsia,
formObject.sumprice,

formObject.YourCompany,
formObject.manager,
formObject.Email,
formObject.postnumber,
formObject.location,
formObject.telephonenumber,
formObject.Faxnumber,

"お届け先情報",
formObject.option2,
formObject.Companypart2,
formObject.managerpart2,
formObject.department2,
formObject.postnumberPart2,
formObject.locationpart2,
formObject.telephonenumberPart2,
formObject.Faxnumberpart2,

"ご請求先情報",
formObject.option3,
formObject.Companypart3,
formObject.managerpart3,
formObject.department3,
formObject.postnumberPart3,
formObject.locationpart3,
formObject.telephonenumberPart3,
formObject.Faxnumberpart3

]);
var html_body =   formObject.YourCompany+   "
"
+formObject.manager +     "様

"
+"この度は新型コロナ関連抗原検査キットのご注文をいただき、誠にありがとうございます。"+"
"
+"ご注文をいただき、誠にありがとうございます。
"
+"2営業日以内に、折り返し弊社担当よりご注文の受付確認のご連絡を差し上げますので、しばらくお待ちください。
"
+"なお、2営業日経過後も弊社より連絡がない場合は、弊社にご注文内容が届いていない可能性がございます。
"

+"お手数をおかけしまして恐れ入りますが、お電話にてご注文の確認をお問い合わせください。
"
+"
********************ご注文内容*********************

"
+"商品名:H Guard社 インフル&コロナ ダブル検査キット
"
+"商品数量:"+formObject.numberProductHGuard+"ケース
"
+"金額:"+formObject.priceProductHGuard+"円

"

+"商品名:DIAsia社 口腔内粘膜(唾液)コロナ検査キット
"
+"商品数量:"+formObject.numberProductDIAsia+"ケース
"
+"金額:"+formObject.priceProductDIAsia+"円
"
+"合計金額:"+formObject.sumprice+"円

"

+"貴社名:"+formObject.YourCompany+"
"
+"ご担当者名:"+formObject.manager+"
"
+"郵便番号:"+formObject.postnumber+"
"
+"所在地:"+formObject.location+"
"
+"メールアドレス:"+formObject.Email+"
"
+"お電話番号:"+formObject.telephonenumber+"
"
+"FAX番号:"+formObject.Faxnumber+"

"
+"━━━━━━━━━━━━━━━━━━━━━━━"

+"
お届け先情報

"
+"お届け先の指定:"+formObject.option2+"
"
+"企業名:" +formObject.Companypart2+"
"
+"ご担当者名:"+formObject.managerpart2+"
"
+"部署・役職:"+formObject.department2+"
"
+"郵便番号:"+formObject.postnumberPart2+"
"
+"所在地:"+formObject.locationpart2+"
"
+"お電話番号:"+formObject.telephonenumberPart2+"
"
+"FAX番号:"+formObject.Faxnumberpart2+"
"
+"━━━━━━━━━━━━━━━━━━━━━━━"

+"
<ご請求先情報>

"
+"ご請求先の指定:"+formObject.option3+"
"
+"企業名:"+formObject.Companypart3+"
"
+"ご担当者名:"+formObject.managerpart3+"
"
+"部署・役職:"+formObject.department3+"
"
+"郵便番号:"+formObject.postnumberPart3+"
"
+"所在地:"+formObject.locationpart3+"
"
+"お電話番号:"+formObject.telephonenumberPart3+"
"
+"FAX番号:"+formObject.Faxnumberpart3+"

"
+"*****************************************************

"
+"このメールに心当たりの無い場合は、お手数ですが
"
+"下記連絡先までお問い合わせください。
"
+"この度はお問い合わせ重ねてお礼申し上げます。

"

MailApp.sendEmail({
to: formObject.Email,
subject: "新型コロナ関連抗原検査キットのご注文ありがとうございます/株式会社ミヤゲン",
body: "",
htmlBody: html_body
});

}
Comment: I thought that in your question when you provide the sample value of `formObject` and the sample output value, it will help users think of the solution.
Comment: Can you clarify the source value and format? Is the source value a [number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number)?
Answer: Although I'm not sure about your sample value of formObject, when you want to convert 123456789 to 123,456,789, how about modifying as follows?
From:
+"金額:"+formObject.priceProductHGuard+"円

"

To:
+"金額:"+formObject.priceProductHGuard.toLocaleString()+"円

"

And,
From:
+"金額:"+formObject.priceProductDIAsia+"円
"
+"合計金額:"+formObject.sumprice+"円

"

To:
+"金額:"+formObject.priceProductDIAsia.toLocaleString()+"円
"
+"合計金額:"+formObject.sumprice.toLocaleString()+"円

"

Note:

I thought that in your situation, locales of toLocaleString(locales) might be required to be used. But if it is required to use it, please set it.
If this was not the result you expect, can you provide the sample value of formObject and the sample output values? By this, I would like to confirm it.

Reference:

Number.prototype.toLocaleString()


PHP - Unexpected Behavior in Nested foreach Loop

Question: Some Background
I have 2 arrays with the following information:
$x = [
    ['name' => 'Fred', 'ykey' => 'A', 'rank' => '1', 'VIP' => '1'],
    ['name' => 'Fred', 'ykey' => 'B', 'rank' => '2', 'VIP' => '1'],
    ['name' => 'Joe', 'ykey' => 'A', 'rank' => '1', 'VIP' => '1'],
    ['name' => 'Joe', 'ykey' => 'B', 'rank' => '2', 'VIP' => '1'],
    ['name' => 'Frank', 'ykey' => 'A', 'rank' => '1', 'VIP' => '0'],
    ['name' => 'Frank', 'ykey' => 'B', 'rank' => '2', 'VIP' => '0']
]

and
$y = [
    'A' => [
        'hasVIPmember' => false,
        'slots' = [] //X elements will be placed here
    ]
    'B' => [
        'hasVIPmember' => false,
        'slots' = [] //X elements will be placed here
    ]

The goal is to place each of the elements in $x into $y with only one VIP member. I have a method to place the VIP members and then one to place everyone else. The information in $x is obtained from a database. The '1' in VIP means true.
The Problem
The problem I am having is outlined in the comments in the code below.
for($i = 1; $i <= 2; $i++){
    foreach($x as $z){
        //all Xs are seen here (after all iterations complete)
        if($z['VIP'] == 1 && $z['rank'] == $i){
            //Only Fred and Joe elements of X are shown here. (after all iterations complete)
            if(!($y[$z['ykey']]['hasVIPmember'])){
                //Only 'Fred' elements are shown here. Why?(after all iterations complete)
                $y[$z['ykey']]['slots'][]= $z;
                $y[$z['ykey']]['hasVIPmember'] = true;
            }
        }
    }
}

So the problem is, as you can see from the comments, when I perform if(!($y[$z['ykey']]['hasVIPmember'])){...} I only see the elements with the name "Fred" and, consequently, Fred is placed in both A and B.
The Question
Why is the list of items that are iterated through narrowed further in the final if statement? Is there any way to correct this behavior?
Comment: well, you never change `hasVIPmember` inside the loop, so even after you add a vipmember, you'll just keep adding more vip members,b ecause you never reset the flag to say one was added previously.
Comment: @MarcB Thanks for pointing that out. I actually do have that in my original code. I just missed it when I moved it here.
Answer: When you run the iteration Fred is first for both ranks 1 and 2. As it runs, it adds Fred to $y and then skips over the rest because at that point $y[hasVIPmember] is true. You would need to find a way to invalidate Fred from the running after he is added to any $y by using some kind of counter or key, or change your data set.
$used = NULL;
for($i = 1; $i <= 2; $i++){
    foreach($x as $z){
        //all Xs are seen here (after all iterations complete)
        if($z['VIP'] == 1 && $z['rank'] == $i){
            //Only Fred and Joe elements of X are shown here. (after all iterations complete)
            if(!($y[$z['ykey']]['hasVIPmember'])){
                // looks for used
                if (!($z['name'] == $used)) {
                    $y[$z['ykey']]['slots'][]= $z;
                    $y[$z['ykey']]['hasVIPmember'] = true;
                    $used = $z['name']; //add Fred to the used name list
                }

            }
        }
    }
}

Comment: Thanks for the fast answer! `if( ... $z['rank'] == $i){...}` prevents that from happening. I am seeing the following at the second comment (after the first if statement): When `$i = 1` I see the first entry for Fred and then the first entry for Joe. When `$i = 2` I see the second entry for Fred and then the second entry for Joe.
Comment: After rereading your answer, I found that you were correct. Thanks so much for your help!
Answer: Reason for the unexpected behavior is that you are using
$y[$z['ykey']]['hasVIPmember'] = true;

This lead to set hasVIPmember = true for all names in $x that has ykey='A' in the first iteration.Therefore after fred has been entered joe is skipped.
Similarly it sets  hasVIPmember = true for all names in $x that has ykey='B' in the second iteration.
Even if you had more names in $x they all would have been excluded.
This code gives the desirable output ,
<?php

$x = [
['name' => 'Fred', 'ykey' => 'A', 'rank' => '1', 'VIP' => '1'],
['name' => 'Joe', 'ykey' => 'A', 'rank' => '1', 'VIP' => '1'],
['name' => 'Fred', 'ykey' => 'B', 'rank' => '2', 'VIP' => '1'],
['name' => 'Joe', 'ykey' => 'B', 'rank' => '2', 'VIP' => '1'],
['name' => 'Frank', 'ykey' => 'A', 'rank' => '1', 'VIP' => '0'],
['name' => 'Frank', 'ykey' => 'B', 'rank' => '2', 'VIP' => '0']
];

$y = [
'A' => [ 'hasVIPmember' => false , 'slots' => []  ],
'B' => [ 'hasVIPmember' => false , 'slots' => []  ]

 ];

for($i = 1; $i <= 2; $i++){
foreach($x as $z){
    //all Xs are seen here (after all iterations complete)
    if($z['VIP'] == 1 && $z['rank'] == $i){
       //Only Fred and Joe elements of X are shown here. (after all iterations complete)
        if(!($y[$z['ykey']]['hasVIPmember']))
          {
          echo $z['name']; // printing to check the name
          echo $z['ykey']; // printing to check the ykey
          echo "
";
          $y[$z['ykey']]['slots'][]= $z;

    }

}

}
}

?>

Comment: I need to have only 1 VIP member in A and 1 VIP member in B. That is why I have that flag there, otherwise I will get multiples in each.
Comment: That's correct. I failed to say that order was important in my question. Sorry about that.


Showing that $f(x) = \dfrac{x}{(\ln x)^2}$ is an increasing function for $x \ge 10$

Question: I am trying to show that $f(x) = \dfrac{x}{(\ln x)^2}$ is an increasing function for $x \ge 10$
Please let me know if any of these steps are wrong:
(1)  Using the quotient rule with $g(x) = x$ and $h(x) = (\ln x)^2$:
$$f'(x) = \frac{g'(x)h(x) - g(x)h'(x)}{(h(x))^2}$$
(2) Using the exponent rule for derivatives with $s(x) = \ln x$:
$$h'(x) = (s(x)^2)' = s(x)^2\left(s'(x)\dfrac{2}{s(x)}\right) = 2s(x)s'(x)$$
(3) $s'(x) = \dfrac{1}{x}$ so that:
$$h'(x) = \dfrac{2\ln(x)}{x}$$
(4) With $g'(x) = 1$, it follows that:
$$f'(x) = \dfrac{(\ln x)^2 - \frac{2x\ln(x)}{x}}{(\ln x)^4} = \dfrac{(\ln x)^2 - 2\ln(x)}{(\ln x)^4}$$
(5)  It is increasing at $x=10$ since:
$$\dfrac{(\ln 10)^2 - 2\ln(10)}{(\ln(10))^4} > 0.24 > 0$$
Are these steps correct?  Did I make any mistakes?  Am I missing any details?
Comment: You're not wrong, but the conclusion can be strengthened. $\ln(x)-2>0$ for $x>e^2\approx 7.3$.
Comment: the derivative has a common factor that can be taken out, becomes $$  \dfrac{\ln x - 2}{(\ln x)^3}$$
Comment: Great point.  Thanks.
Comment: Thanks, Will.  I missed that!  :-)
Comment: $f(x)$ is strictly increasing at $x=10,$ which means there exists $r>0$ such that $f(y)0. $ But you did not show that $f'(x)>0$ for $all$ $x\ge 10.$
Answer: Easier approach: Introduce substitution $x=e^t$. Notice that $x(t)$ is monotoniously increasing. Now you have to prove that the following function is increasing:
$$f(t)=\frac{e^t}{t^2}$$
This is obvious from:
$$f'(t)=\frac{t^2e^t-2te^t}{t^4}=te^t\frac{t-2}{t^4}$$
The first derivative is positive for $t>2$ i.e. for $x>e^2\approx 7.39$.


System of equations can be interpreted as intersection of $3$ planes in $3$-dimensional space

Question: I'm struggling with this question.

I have worked out that attempting to solve for the $x_i$ leads to a contradiction, and that
$$\begin{vmatrix}1&4&6\\1&-2&1\\2&14&17\end{vmatrix}=0$$
So there is no solution for $x$. But what are the planes?

Three parallel planes
two parallel planes and one intersecting plane
three planes that intersect the other two but not at the same location Link

So I have narrowed down the answer to 3, 4, 5. Which one is it and how do we know?
Answer: Labelling the coefficient matrix's rows as $R_1,R_2,R_3$, we have $R_3=3R_1-R_2$ but $R_1$ and $R_2$ independent, but $3\cdot18-(-6)\ne-6$ so the third equation is not a linear combination of the first two. This means that

the planes corresponding to $R_1$ and $R_2$ intersect in a line
$R_3$'s plane is parallel to that line of intersection, but not parallel to the first two planes

Therefore the fifth answer is correct: there is no solution for $x$ even though none of the planes are parallel.
Comment: @Sam He is referring to the _**lines** of intersection between every two planes_, not the **planes** themselves. For answer 5, those three lines of intersection are all parallel.
Comment: @Sam How is that a solution? The question only asks for the planes configuration!
Comment: i. x+4y+6z=18 ii. x-2y+z=-6  iii. 2x+4y+17z=-6  Because no two of those planes are parrallel then each pair have a line of intersection.  i. have normal $N_1$=<1.4.6>, likewise $N_2$=<1,-2,1> and $N_3$=<2,14,17>. Then N1xN2= <16,-5,-6> is the direction of the vector of the intersection of planes i and ii. Likewise N1XN3=<-16,5,6> is the direction of for the intesection of planes i and iii. therefore 2 lines are parallel and there is no common point of intersection to all three planes
Comment: @Sam Which means that, since there is no solution for $x$, the answer I gave is correct.
Comment: He is saying 2 lines are parallel though. Answer 5,states no line are parrellel
Comment: Oh, I see. Thank you for the clarification


Android Layer_Drawable as a button

Question: I have a button.
The button is constructed from the StateListDrawable (made of 3 9-patch images).
I need to add an extra drawable that will reside on the button's right side, and i need it to be aligned with the button's right side.
I tried to use the following:
<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/blue_back_button_drawable" />
    <item>
      <bitmap android:src="@drawable/filter_by_button_v_mark" android:gravity="right"/>
    </item>
</layer-list>
</code>
it didn't work and the V image is indeed aligned right but it has a diff from the button's right side. here's a snapshot:
I want the image to be aligned with the button's left, the only way right now i think i can do it is:

inherit button, in onLayout AFTER the width has been set get the right edge.
get the background drawable (layerDrawable)
calc the button's width minus the v image width and set it as left margin in the drawable.

I should not mention this sounds horrid :-) i hoped there's a better way. Oh the reason it's not part of the image is that i need to know it's width so i can calc the text padding so it wont be hidden by the button's text and because it's not so nice looking as a 9-patch.
Comment: the snap shot doesn't show for some reason :-(
Answer: Seems like there was no proper solution to this. layer is for static and not 9-patch images apparently, or so it seems.
So i extended Button, changed it's on Draw, i have to use Canvas.restore() to break out of the margins that pushed my edges down and put my image in the upper right corner...
here's the code:
<code> @Override
public void setPadding(int left, int top, int right, int bottom) {
    right += mImageWidth;
    super.setPadding(left, top, right, bottom);
}

private void setVImageDrawable(Drawable d) {
    mVImageDrawable = d;
    mImageWidth = mVImageDrawable.getIntrinsicWidth();
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    if( mVImageDrawable != null && mIsMarked){
        //for some reason the clip binds us to position with margins, which is not so good for us.
        //we need to save the clip, restore the canvas to pre clipping mode, do what we need then
        //put the canvas back to it's previous clipping state.
        Rect bounds = canvas.getClipBounds();
        canvas.restore();
        int right = getRight();
        int left = right - mImageWidth;
        int top = getTop();
        int bottom = top + mVImageDrawable.getIntrinsicHeight();
        mVImageDrawable.setBounds(left, top, right, bottom);
        mVImageDrawable.draw(canvas);
        canvas.save();
        canvas.clipRect(bounds);
    }
}
</code>
If i don't break out the original canvas iget 'pushed down' by any margins i add, it may also be fixed i think using xml property that specifies if children should be clipped on the layout containing this button, but i find that lame solution as it makes my button dependent on our conditions.
The image itself i get from XML using new attributes and style and theme i declare.
Hope it'll help some ppl out there.
Comment: can you tell me exatly what you need ?

Android Layer_Drawable as a button