Dúvida sobre tamanho da array

Question: Tenho uma dúvida referente a array, por exemplo, se eu tiver 2 arrays de tamanho 9 e for imprimir os valores de ambas é normal a entrada 9 pegar o valor 0 da próxima array ?, isso é mais um teste, sei que o máximo é 8 ?
Exemplo de código:
struct stType {
  type[9];
}select;

strcut vrType {
  type[9];
}variable;

void st_type(int type, int value) {
    int i;
    uint32 type_select = select_type(type);

    ST_TYPE(i, type_select) {
        select->type[i] += value;
    }
}

void vr_type(int type, int value) {
    int i;
    uint32 type_select = variable_type(type);

    VR_TYPE(i, type_select) {
        variable->type[i] += value;
    }
}

int main() {
    st_type(0, 50); // define valor 50 para array select->type[0]
    vr_type(0, 60); // define valor 60 para array variable->type[0]

    for (i = 0; i < 10; i++)
        printf("[ST Debug %d] Value: %d\n", i, select->type[i]);

        printf("\n");

    for (i = 0; i < 10; i++)
        printf("[VR Debug %d] Value: %d\n", i, variable->type[i]);
}

Saída:
[ST Debug 0] Value: 50
[ST Debug 1] Value: 0
[ST Debug 2] Value: 0
[ST Debug 3] Value: 0
[ST Debug 4] Value: 0
[ST Debug 5] Value: 0
[ST Debug 6] Value: 0
[ST Debug 7] Value: 0
[ST Debug 8] Value: 0
[ST Debug 9] Value: 60 // posição 9 puxa o 0 de vr

[VR Debug 0] Value: 60
[VR Debug 1] Value: 0
[VR Debug 2] Value: 0
[VR Debug 3] Value: 0
[VR Debug 4] Value: 0
[VR Debug 5] Value: 0
[VR Debug 6] Value: 0
[VR Debug 7] Value: 0
[VR Debug 8] Value: 0
[VR Debug 9] Value: 0

Answer: Na verdade ter um zero é uma coincidência, poderia ter qualquer valor aí. Está pegando um valor que está em uma posição de memória fora da área reservada para este array. Você sabe que vai do 0 ao 8, então o 9 é algo que vem logo a seguir na memória.
C permite acessar toda a memória da aplicação sem restrições, é problema do programador garantir que não está acessando algo indevidamente.
Comment: Entendo, mais isso prejudica algo no código ?
Comment: Muito, você está acessando uma área que não deveria, o que tem lá é considerado lixo, e consumira isto. Pior, se mexer lá alterará algo que faz parte de outro objeto danificando-o.
Answer: Sim é perfeitamente normal. Isto acontece devido a forma como as variáveis são alocadas em c, mas também depende do compilador. Observe as seguintes situações:
int a = 5, b = 10;

int main() {
  int *p = &a;
  printf("%d\n", *p);
  p++;
  printf("%d\n", *p);
}

Se você compilar este código usando o gcc ou mesmo o vc++, o programa ira produzir a seguinte saída:
5 - 10

Nesse caso temos duas variáveis globais e a memória foi alocada na ordem em que as variáveis foram declaradas, uma após a outra. O mesmo se passa no teu exemplo, primeiramente alocou-se a memória o primeiro vetor, e logo a seguir para o segundo, fazendo com que o último elemento do primeiro vetor fique mesmo ao lado do primeiro elemento do segundo vetor.
Mas nem sempre as coisas acontecem desse jeito. Observe o segundo exemplo:
int func(int a, int b){
   int *p = &a;
   printf("%d - ", *p);
   p++;
   printf("%d", *p);
}

int main() {
   func(5, 10);
}

Este código possui uma saída quando compilado com o vc++ e outra com gcc.
Saída VC++: 5 - 10
Saída GCC:  5 - 0
Como se pode ver neste exemplo, em c não há uma regra que determine a ordem como as variáveis são alocadas. No teu exemplo  select->type[9] é igual a 60, mas talvez num outro compilador ou numa outra plataforma as coisas não seriam assim.
Comment: Entendo, eu estava achando que era problema no meu código por isso me surgiu essa dúvida, seu exemplo foi bem esclarecedor, obrigado.
Comment: @Carol na verdade é problema no seu código e esta resposta está induzindo a erro, por mais que haja boa intenção. Não é como C aloca variáveis e não depende do compilador. Note que os exemplo sequer tratam do seu problema. Ela até está correta no problema que está falando, mas não é o mesmo que o seu. A resposta dá a entender que seu código está certo. É o que eu falei, você está acessando uma área de memória que não foi designada para aquela variável, se você tem posições de 0 a 8, tentar acessar a 9 é possível, mas semanticamente errado produzindo um resultado certamente errado...
Comment: ...ainda que funcione por coincidência https://i.stack.imgur.com/g0Toi.png
Comment: @Maniero, em momento algum falei que o cógigo está certo, só quis mostrar porquê que as funcionaram desse jeito. O primeiro exemplo é sim o mesmo caso que o dela. O segundo foi só pra mostrar o quão imprevisível (e consequentemente perigoso) c pode se tornar quando se trata deste assunto. E você tem razão quando diz que é errado tentar acessar a memória que não foi designada para uma variável.

Dúvida sobre tamanho da array


an analysis problem on manifold

Question: Let $M$ be a $n-$dimensional close connected manifold or manifold without boundary and $S$ be a connected close subset homeomorphism to of a $n$-dimensional closed ball $D^n$ (since a manifold is locally compact, $S$ always exists). Let $int(S)$ be the interior of $S$. Is $M-int(S)$ a connected manifold?
I am interested it because I want to simulate the connected sum in my Opengl project,in the case $n=2$ and $M$ can be embedded into $R^3$. I am interested in it.Moreover how can we deduce some topology properties on $M-int(S)$ such as its homology.For example if $M$ is a convex close subset in $R^n$, and we dig out the interior of a small ball $D^n$ in $M$, then $M-int(D^n)$ should take $S^{(n-1)}$ as its retract kernel so homology group $H_k(M-int(D^n)) = \mathbb{Z}$ iff $k=n-1$. (Is my calculation right?)
Comment: You forgot to assume that $M$ is connected.
Comment: Really sorry uh.
Answer: 1) Assuming $M$ is connected, the answer is yes. Indeed, any path joining $x$ and $y$ passing throuhg $S$ can be deformed to a path passing only on the boundary $\partial S$.
2) Your computation is indeed correct.
Comment: The topologist's curve is not a manifold. A manifold is always locally connected.
Comment: Thank you and give you a upvote!I forget to assume $M$ is connected.However a connected manifold is not always path-connected since topologist's sine curve is a typical counterexample.How to explain this?
Comment: @Muse_China: for a standard manifold, we have always connected $\Leftrightarrow$ path connected, because a manifold is locally path-connected.
Comment: Yeah.I make a mistake.Thank you for pointing out.And a further question,is topology structure $M-int(S)$ depends on the choice of $S$?
Comment: @Muse_China : I would say that it does not depend on the choice of $S$. Here is a sketch of the proof : take a path between the center of $S$ and the center of $S'$. There is a diffeomorphism $f : M \to M$ with $f(S) = S'$, obtained as integration of a suitable vector field.

an analysis problem on manifold


How find this $I=\iint_{\Sigma}(x^2+y^2+z^2)^{-\frac{3}{2}}(\frac{x^2}{a^4}+\frac{y^2}{b^4}+\frac{z^2}{c^4})^{-\frac{1}{2}}dS$

Question: Find this Surface integral
$$I=\iint_{\Sigma}(x^2+y^2+z^2)^{-\frac{3}{2}}\left(\dfrac{x^2}{a^4}+\dfrac{y^2}{b^4}+\dfrac{z^2}{c^4}\right)^{-\frac{1}{2}}dS$$
where
$$\Sigma:\dfrac{x^2}{a^2}+\dfrac{y^2}{b^2}+\dfrac{z^2}{c^2}=1,a>0,b>0,c>0$$
My try: let
$$x=a\sin{\alpha}\cos{\beta},y=b\sin{\alpha}\sin{\beta},z=c\cos{\alpha},\alpha\in[0,\pi],\beta\in[0,2\pi]$$
$$E=x''_{\alpha}+y''_{\alpha}+z''_{\alpha}=a^2\cos^2{\alpha}\cos^2{\beta}+b^2\cos^2{\alpha}\sin^2{\beta}+c^2\sin^2{\alpha}$$
$$G=x''_{\beta}+y''_{\beta}+z''_{\beta}=a^2\sin^2{\alpha}\sin^2{\beta}+b^2\sin^2{\alpha}\cos^2{\beta}$$
$$F=x'_{\alpha}x'_{\beta}+y'_{\alpha}y'_{\beta}+z'_{\alpha}z'_{\beta}=-a^2\sin{\alpha}\cos{\alpha}\sin{\beta}\cos{\beta}+b^2\sin{\alpha}\cos{\alpha}\sin{\beta}\cos{\beta}$$
so
$$EG-F^2=(a^2b^2\cos^2{\alpha}+a^2c^2\sin^2{\alpha}\sin^2{\theta}+b^2c^2\sin{\alpha}\cos^2{\beta})\sin^2{\alpha}$$
then
$$\int_{\Sigma}f(x,y,z)dS=\int_{\Delta}f(a\sin{\alpha}\cos{\beta},b\sin{\alpha}\sin{\beta},c\cos{\alpha})\sqrt{EG-F^2}d\alpha d\beta$$
where $\Delta:0\le\alpha\le \pi,0\le \beta\le 2\pi$
$$f(x,y,z)=(x^2+y^2+z^2)^{-\frac{3}{2}}\left(\dfrac{x^2}{a^4}+\dfrac{y^2}{b^4}+\dfrac{z^2}{c^4}\right)^{-\frac{1}{2}}$$
and follow I fell very ugly,Thank you very much
Answer: Let $\vec{r} = (x,y,z)$ and $\varphi(\vec{r}) = \frac{x^2}{a^2} + \frac{y^2}{b^2} + \frac{z^2}{c^2}$, we have
$$\vec{\nabla}\varphi(\vec{r}) = (\frac{2x}{a^2}, \frac{2y}{b^2},\frac{2z}{c^2})
\quad\implies\quad
\begin{cases}
\vec{r}\cdot \vec{\nabla}\varphi(\vec{r}) &= 2 \left(\frac{x^2}{a^2} + \frac{y^2}{b^2} + \frac{z^2}{c^2}\right) = 2\varphi(\vec{r})\\
\left|\vec{\nabla}\varphi(\vec{r})\right|^2 &= 4\left(\frac{x^2}{a^4} + \frac{y^2}{b^4} + \frac{z^2}{c^4}\right)
\end{cases}$$
On the surfaces $\Sigma$, $\varphi(\vec{r}) = 1$, we can rewrite the factor
$$\frac{1}{\sqrt{\frac{x^2}{a^4} + \frac{y^2}{b^4} + \frac{z^2}{c^4}}} d\text{S}
\quad\text{ as }\quad
\vec{r} \cdot \frac{\vec{\nabla}\varphi(\vec{r})}{\left|\vec{\nabla}\varphi(\vec{r})\right|} d\text{S}
$$
But $\;\displaystyle \frac{\vec{\nabla}\varphi(\vec{r})}{\left|\vec{\nabla}\varphi(\vec{r})\right|}$ is nothing but the normal vector $\hat{n}{(\vec{r})}\;$ for the surfaces $\Sigma$. This means
$$I = \int_{\Sigma} \frac{\vec{r}}{|\vec{r}|^3} \cdot \hat{n} d\text{S}
    = - \int_{\Sigma} \vec{\nabla}\frac{1}{|\vec{r}|} \cdot \hat{n} d\text{S}
$$
Since $\;\displaystyle \nabla^2 \frac{1}{|\vec{r}|} = 0\;$ for $\vec{r} \ne \vec{0}$,
we can use Divergence Theorem to deform the surface $\Sigma$ to the unit sphere $S^2$ centered at $\vec{0}$ without changing the value of $I$. As a result,
$$I = \int_{S^2} \frac{\vec{r}}{|\vec{r}|^3} \cdot \hat{n} d\text{S} = 4\pi$$
Comment: Oh,It's nice,Thank you+1
Answer: Lets write the integral
$$I=\iint_{\Sigma}(x^2+y^2+z^2)^{-\frac{3}{2}}\left(\dfrac{x^2}{a^4}+\dfrac{y^2}{b^4}+\dfrac{z^2}{c^4}\right)^{-\frac{1}{2}}dS$$
in the form
$$I=\iint_{\Sigma} \frac{(x, y, z)}{(x^2+y^2+z^2)^{\frac{3}{2}}} \cdot \left(\left(\frac{x}{a^2}, \frac{y}{b^2}, \frac{z}{c^2}\right)\left(\dfrac{x^2}{a^4}+\dfrac{y^2}{b^4}+\dfrac{z^2}{c^4}\right)^{-\frac{1}{2}}\right)dS$$
and notice the integral now reads
$$I=\iint_{\Sigma}(\mathbf{F\cdot n})dS$$
with
$$\mathbf{F}= \frac{(x, y, z)}{(x^2+y^2+z^2)^{\frac{3}{2}}}, \mathbf{n}=\left(\left(\frac{x}{a^2}, \frac{y}{b^2}, \frac{z}{c^2}\right)\left(\dfrac{x^2}{a^4}+\dfrac{y^2}{b^4}+\dfrac{z^2}{c^4}\right)\right)^{-\frac{1}{2}}$$
Notice how $\nabla\cdot \mathbf{F}=0$ on $\mathbb{R}\backslash\{(0, 0, 0)\}$, which means you can integrate $\mathbb{F}$ over any surface $S$ with the origin in its interior. For simplicity, take $S: \{(x,y,z)\in \mathbb{R}^3|\ x^2+y^2+z^2 = 1\}$. The integral is now simply
$$I=\iint_{S} \frac{(x, y, z)}{(x^2+y^2+z^2)^{\frac{3}{2}}} \cdot \frac{(x, y, z)}{(x^2+y^2+z^2)^{\frac{1}{2}}}dS = \iint_{S} \frac{dS}{r^{2}} $$
Therefore, $$I= \int_{0}^{1} \frac{4\pi r^2 dr}{r^2} \Rightarrow I=4\pi$$
Comment: It's nice too+1


Symbian mobile os - how to write C applications?

Question: I want to write a C application that runs on Symbian mobile OS. I don't know where to start.
Is there any library files available or any SDK or IDE available for it?
Comment: Go to http://www.google.com.

Enter "Symbian SDK" in the search box.
Comment: I "improved" spelling and grammar, but I'm not sure this question is narrow enough in focus to stand. I'll let it stew for a while before voting to close, to see if it gains some focus or has an answer more interesting than "let me google that for you".
Answer: http://wiki.forum.nokia.com/index.php/How_do_I_start_programming_for_Symbian_OS%3F
Architecture http://developer.symbian.org/wiki/images/9/95/OpenCppEnv.png:
Developer community tutorial link.
Answer: Just like to elaborate on the previous post. Symbian supports POSIX libraries via Open C. Mobile apps almost always have a UI. Depending on your objective, you might check out Qt on Symbian too.
-hth
John
Comment: When we write a program, we want to solve a problem. The original question does explicit say in C. I am simply suggesting a UI is a natural next step. C and C++ work well together. Allow the original author to access/reuse the C APIs and leverage Qt's UI and application framework.
Comment: How does Qt help with writing an application in C?
Answer: You should download the Nokia Qt SDK (http://qt.nokia.com/downloads/) . This allows you to write applications in C/C++ (without having to learn the Symbian flavor of C++).


SPF record validation - best guess only

Question: I administrate the domain [mydomain.com] which was until now only used for handling mail through Google Mail/Google Apps.
Now I added a server which should be part of the domain without changing the primary purpose. I want the server to be able to send simple administrative mail, so I installed and configured sendmail.
When I send testmails to another Google Mail address the mail gets through but I get this header information:
<code>Received-SPF: pass (google.com: best guess record for domain of
[myuser]@[myhost].[mydomain].com designates [myipv6address]
as permitted sender) client-ip=[myipv6address];
</code>
Now of course I want the validation to pass without guessing but I have probably something wrong in my DNS record.
<code>$TTL 86400
@   IN SOA [mynameserver1]. (
    2013101002   ; serial
    14400        ; refresh
    1800         ; retry
    604800       ; expire
    86400 )      ; minimum

@            IN NS      [mynameserver3].
@            IN NS      [mynameserver2].
@            IN NS      [mynameserver1].

@            IN A       [myipv4address]
[myhost]     IN A       [myipv4address]

@            IN AAAA    [myipv6address]
[myhost]     IN AAAA    [myipv6address]

@            IN MX 1    ASPMX.L.GOOGLE.COM.
@            IN MX 5    ALT1.ASPMX.L.GOOGLE.COM.
@            IN MX 5    ALT2.ASPMX.L.GOOGLE.COM.
@            IN MX 10   ASPMX2.GOOGLEMAIL.COM.
@            IN MX 10   ASPMX3.GOOGLEMAIL.COM.
@            IN TXT     "v=spf1 a:[myhost].[mydomain].com ip4:[myipv4address]
                        ip6:[myipv6address] include:_spf.google.com ~all"
</code>
I can't find the error and would appreciate any help.
Best regards,
Thomas
Comment: What is the problem you are having? Your post does not describe any problem.
Comment: The problem is that I expect the receiving mail server not only to "guess" that the sending host is valid. I think other providers may be stricter and classify the mail as spam.
Answer: You sent email from an address which contains a subdomain of your domain. Your domain has an SPF record, but the subdomain does not. Thus Google makes a "best guess" that your domain's SPF record should be used. This violates the specification, under which your subdomain would not be considered to have an SPF record, but it usually reflects what senders (whose mail systems are misconfigured) intended.
Comment: Shouldn't this be addressed by the A and AAAA entry for the hostname and the hostname in the spf line?
Comment: No, you misunderstand. Your hostname, what you call `[myhost]`, is missing an SPF record.
Comment: So I should add an additional line like: `[myhost]            IN TXT     "v=spf1 a:[myhost].[mydomain].com ip4:[myipv4address]
                        ip6:[myipv6address] include:_spf.google.com ~all"` ?
Comment: Yes, if that's the record you want.
Comment: I changed my sendmail.cf to masquerade as [mydomain].com instead of [myhost].[mydomain].com now and everything works as intended. Thanks for showing me the right direction!

SPF record validation - best guess only


Url Amigavel com Mysql

Question: estou construindo um site que puxa ids do banco de dados e faz a pagina do post, porém quando ele faz a requisição a url fica como id assim:
http://www.meusite.com.br/posts.php?id=2

Queria que em vez de mostrar o id, mostrasse o Titulo da postagem que eu pego no banco de dados, por exemplo, www.meusite.com.br/Como_Criar_URls_amigaveis sem necessidade de aparecer o posts.php?id, agradeço a ajuda.
Comment: Obrigado, realmente reconstruir o sistema da mais trabalho, mudei o caminho, utilizando Wordpress agora.
Comment: Ainda assim seria interessante votares e aceitar a resposta que melhor solucionava o problema...
Answer: Primeiramente, o que você diz que é mostrar o ID, na verdade não é bem assim, a sua url representa um arquivo no seu servidor, e o ID representa um parâmetro passado para essa página. Quando você aperta o ENTER na barra do seu navegador, ele está realizando uma requisição HTTP GET ao seu servidor, passando esse parametro ID.
Nessa página, provavelmente existe um código assim:
Select * from Posts where postID = $_GET["ID"]

Ou seja, "Traga o POST aonde o ID é igual ao Parâmetro passado na requisição"
Imagine se você trocasse o parâmetro ID por TituloPost, seu código provavelmente ficaria assim:
Select * from Posts where titPost = $_GET["TituloPost"]

Agora pense comigo, você cria um botão em uma certa parte de seu site, que redireciona para esse seu post, por exemplo, quando alguem clica em um link, é aberto o endereço;
http://www.seublog.com.br/posts.php?tituloPost=ComoCriarVariosLinkAmigavel
Mas digamos que você edite o título do post para
"ComoCriarLinkAmigavel"
Você teria um problema, pois o botão de redirecionamento está definido com o parametro tituloPost = "ComoCriarVariosLinkAmigavel".
Então a manutenibilidade do seu site fica extremamente baixa.
Outra situação seria mais de um post ter o mesmo título, o que quebraria o funcionamento do site, aonde cada página mostra um post.
Ou seja, existem diversas situações que tornam essa prática inviável.
É possível criar Links amigáveis?
Sim, é possível criar links mais amigáveis, no entanto, é totalmente recomendado o uso do ID como parâmetro, pois o ID além de ser único, representa um valor seguro de mudanças, ou seja, você pode editar o seu post, título, tags, que o ID vai continuar o mesmo.
Comment: Entendi então, o correto seria eu criar um sql que procura com base no numero da id e no nome do post, porém, depois disso, como coloco meu htacces?
Comment: **1** A 'manutenibilidade' não esta ligada ao sistema de url amigável, isso é extremamente simples de fazer. **2** `totalmente recomendado o uso do ID como parâmetro` - totalmente equivocado.
Comment: Por favor escreva sua resposta
Comment: @FernandoMedeiros, ja tenho varias sobre o tema
Answer: O que você descreve é um desejo que muita gente tem ao criar um site. A resposta do Fernando Medeiros é bastante útil e simples, basicamente falando use o ID, não se preocupe.
Eu concordo com isso, e acho que, no caso de posts, o ID no URL é prática e fácil.
Mas, como que as outras pessoas fazem? Como vários sites conseguem ter URLs bem prátcias e amgiáveis, mas também que conseguem mantê-los de forma fácil, sobrepujando os riscos que o Fernando menciunou? E, de verdade, são incomodações graves que podem custar muito!
Um desenvolvedor comum como eu usa um framework já estabelecido. No caso de posts e PHP e MySql, existe o framework de Wordpress. O Wordpress consegue manter seus URLs amigávels utilizando o banco de dados, e um algortimo de "achar" o URL mais próximo, caso não seja um url exato.
Basicamente, minha "resposta" seria, não tenta reinventar a roda†, ou seja não tenta criar tudo do zero, mas sim, usa um framework que já resolveu todos esses problemas.
† Não sei se essa expressão que temos em inglês dá o mesmo no português :P
Comment: O wordpress pode ser uma boa saída mesmo
Comment: Com certeza, fui tentar reinventar a roda pensando que era fácil, da trabalho.
Answer: Uma forma simples seria alterar seu .htaccess para algo do tipo:
RewriteEngine On
RewriteRule   ^post/([0-9]+)/(.*)?$   posts.php?id=$1   [NC,L]

// OBS: talvez precise alterar algum detalhe

Assim, a url:
http://www.meusite.com.br/post/22/titulo-do-post
http://www.meusite.com.br/post/22/titulo-do-post-editado

Seriam interpretadas como:
http://www.meusite.com.br/posts.php?id=22

Ou seja, o título seria usado para deixar o url amigável e melhorar o SEO. No fundo o que importaria para exibição correta seria o ID. Isso permite que você altere o título do post sem quebrar os links com título antigo.
Cabe a você gerar as urls na sua aplicação, lembrando de gerar esse slug do título do posts.
slug('Título do post') = titulo-do-post

Url Amigavel com Mysql


How to create a training set when I have no clue about my data?

Question: I have a dataset consisting of numbers representing the values of a KPI (Key performance indicator) collected over a period of time. I would like to implement an algorithm to classify the data as normal or anomaly (and I am planning to use logistic regression or maybe decision trees).
However, the problem is that I don't know which values are normal which values are problematic. So what should I do beforehand to create a training set for my classification algorithm ? Should I use maybe clustering algorithms ?
Answer: If you don't have labeled data (telling whether it belongs to class "normal" or "anamoly"), you will have to use a cluster analysis - for grouping the objects.
Logistic regression is a supervised learning algorithm and requires you to have data that has classes. Same goes for decision trees.
Look at this with respect to validating unsupervised machine learning algorithms.
Answer: You can check other threads tagged anomaly-detection for multiple examples. More examples can be found in this thread about finding outliers in multivariate data as this is a closely related topic. There exist specialized algorithms for dealing with such cases. One-class SVM is one of such algorithms. It is nicely described Microsoft Azure documentation:

Typically, the SVM algorithm is given a set of training examples
  labeled as belonging to one of two classes. The SVM algorithm
  represents the examples as points in space, mapped so that the
  examples of the separate categories are divided by a clear gap that is
  as wide as possible. New examples are then mapped into that same space
  and predicted to belong to one category or another, based on which
  side of the gap they fall on.
... one-class SVM, the support vector model is trained on data that
  has only one class, which is the "normal" class. It infers the
  properties of normal cases and from these properties can predict which
  examples are unlike the normal examples. This is useful for anomaly
  detection because the scarcity of training examples is what defines
  anomalies: that is, typically there are very few examples of the
  network intrusion, fraud, or other anomalous behavior.

So the basic idea is that you use your data to learn about what is "normal", or "typical" and then classify cases that are distant from what is normal as anomalous. This idea can be easily extended beyond the specialized anomaly detection algorithms.


Showing that the $r^{th}$ derivative of the moment generating function is the $r^{th}$ raw moment

Question: Is this a sound way of defining the $r^{th}$ derivative for the moment generating function  $M_{X}(t)$—in order to show that when evaluated at $0$ it gives us the $r^{th}$ raw moment $E[X^{r}]$  ?
Possible Derivative Expression
$M_{X}^{(r)}(t)=\sum_{j<r} E\left(X^{j}\right) \frac{t^{j-r}}{(j-r) !}+E\left(X^{r}\right)+\sum_{j>r} E\left(X^{j}\right) \frac{t^{j-r}}{(j-r) !}$
So that $M_{X}^{(r)}(0)= E\left(X^{r}\right)$.
I guess my question is if this is the right way of expressing the $r^{th}$ derivative of the Maclaurin series for the MGF ?
Definitions:
Moment generating function
$M_{X}(t)=E\left(e^{t X}\right)$
Maclaurin Polynomial expression for MGF
$
M_{X}(t)=1+t E(X)+\frac{t^{2}}{2 !} E\left(X^{2}\right)+\ldots+\frac{t^{r}}{r !} E\left(X^{r}\right)+\ldots=\sum_{j=0}^{\infty} \frac{E\left(X^{j}\right)}{j !} t^{j}
$
Comment: Taking successive derivatives gets rid of early terms in the expansion of $M(t).$ Setting $t=0$ makes later terms go away. You're left with just the one term you need.
Answer: Thanks @Alex and @BruceET.
To correct the original question, the $j<r$ terms disappear after taking the derivative $r$ times.
This becomes clear when computing it by hand for say $r=3$. Note that when taking the $r^{th}$  derivative, every term $E(X^{s})$—where $s \in [0,r)$—has been successively eliminated during differentiation since $\frac{d}{dt}E(X^{r-1})=0$.
So the correct formulation is then
$$M_{x}^{(r)}(t)=E\left(x^{r}\right)+\sum_{j=r+1}^{\infty} \frac{E\left(X^{j}\right) t^{j-r}}{(j-r) !}$$
or
$$
\sum_{j=r}^{\infty} \frac{E\left(X^{j}\right) t^{j-r}}{(j-r) !}
$$


Using Migrate in Drupal 6, setup and parsing XML

Question: Is there a better walkthrough to setting up Migrate than this documentation on Drupal.org? I have followed those directions, and I can't get my classes to show up in the UI. Is there anything clearer?
And how would I go about using Migrate, once it's set up, to parse a series of XML documents (one list XML that includes an additional document per node) into nodes which I can then manipulate in Views?
EDIT
Now I've gotten my XML read and fields set up (I think), but now I can't get the nodes to save. The import has the correct number of nodes, but they don't ever get imported. The wine examples in the documentation didn't say anything about using prepareRow() or anything when you are using XML. Where are my nodes? Can I pull out that data with Views even if nodes don't import? My end use for this is to arrange everything with Views.
Comment: Frankly I didn't find any documentation better than that. You have to follow carefully the instructions about files naming and classes naming. About your migration task: it can be done.
Comment: I'm wondering if there is a problem with the way I named my files. I tried to follow that tutorial exactly.
Answer: Yes, look at the Beer examples that come in the migrate module itself. If you want some example code and usage with some explanation I find the BTMash blog posts useful. While the BTMash blog is D7 based -- the hooks and usage of Migrate is widely similiar between D6 and D7.


Altering ImageField Widget with FUpload enabled

Question: I need to alter the ImageField Widget so that I can add some fields other than the Description, Alt and Title fields. I'm able to do this when I select the file field widget type as Image Uplaod, but when I select the FUpload widget type, the changes don't take effect. Here's the code I'm using:
<code>function bridge_widgets_imagefield_extended_widget($element, $extra_values) {
  // If you need the field or widget to conditionally add a FAPI field, use these.
  $field = content_fields($element['#field_name'], $element['#type_name']);
  $widget = $field['widget'];

   if( $element['#type_name'] == 'property_gallery'  ){
  global $user;
  user_load($user);
  return array(
    //This will Replace the Textfield with dropdown select for the description
    'revise' => array(
      '#type' => 'checkbox',
      '#title' => t('Revise This Description'),
       '#default_value' => isset($extra_values['revise']) ? $extra_values['revise'] : 0,
         '#attributes'=>array('class' => 'revise-check')
       ),
    'revisedby' => array(
      '#type' => 'textfield',
      '#maxlength' => 64,
      '#title' => t('Revsied By'),
     '#default_value' => ($extra_values['revise']==0) ?  NULL : $extra_values['revisedby'] ,
       ),
       'revisedon' => array(
      '#type' => 'date',
      '#title' => t('Date'),
     '#default_value' => ($extra_values['revise']==0) ?  NULL : $extra_values['revisedon'] ,

       ),

  );
  }
}
</code>
Answer: I guess it is the line
<code>$element['#type_name'] == 'property_gallery'
</code>
that makes your changes have/not have effect.
I would actually suggest writing a new widget alltogether, instead of altering the existing one(s). It isn't that difficult, but I don't know of any good tutorial for it online – there is a good chapter about it in the book "Drupal 7 Module Development" though, which helped me a lot.
If you find a good online tutorial, please post the link!


Prioridade em progressdialog

Question: É possível priorizar um progressdialog diante a uma Thread?
Em meu app, após clicar em um botão, preciso congelar um progressdialog por 2 segundos. Após isso, gerar uma consulta ao meu webservice, e assim que retornar os dados, eles são apresentados em um alertdialog,que após aberto, faz o progressdialog receber o dismiss() para fechá-lo. Porém, mesmo instanciando uma nova Thread e setando o sleep() ou wait(), o processo apenas congela a Thread por inteira e não apresenta o progressdialog. Na tela, primeiramente o alert é gerado e o progress fica em segundo plano até o alert ser fechado.
Existe uma maneira possível de gerar na sequencia primeiramente o Progress com 2 segundos de freeze e depois o alert dialog?
Segue trecho do código.
    final EditText Nome = (EditText) findViewById(R.id.cmdDigDe);
    Button btnConDeE = (Button) findViewById(R.id.btnConDe);
    btnConDeE.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {

            ProgressDialog progressDialog = new ProgressDialog(DemE.this);
            progressDialog.setTitle("Listando medicamentos");
            progressDialog.setMessage("Buscando...");
            progressDialog.show();

                String nomeProduto = Nome.getText().toString();
                String laboratorio = null;
                String aliquota = "17";

                if (android.os.Build.VERSION.SDK_INT > 9) {
                    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                    StrictMode.setThreadPolicy(policy);
                }

                if (nomeProduto == "") {
                    Toast.makeText(DemE.this, "Por favor digite o nome do medicamento", Toast.LENGTH_LONG).show();
                } else

                    try {
                        URL url = new URL("http");
                        URLConnection con = url.openConnection();
                        con.setDoOutput(true);
                        OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());

                        writer.write("nome=" + nomeProduto + "&aliquota=" + aliquota + (laboratorio != null ? "&laboratorio=" + laboratorio : ""));
                        writer.flush();

                        BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
                        String result = "";
                        String line;

                        while ((line = reader.readLine()) != null) {

                            result += line;

                            TextView tv = (TextView) findViewById(R.id.tv);
                            tv.setText(Html.fromHtml(result));

                            final String text = tv.getText().toString();

                            AlertDialog alertDialog = new AlertDialog.Builder(context).create();
                            alertDialog.setTitle("Medicamentos:");
                            alertDialog.setMessage(text);
                            alertDialog.setButton("Voltar", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    dialog.cancel();
                                }
                            });

                            progressDialog.dismiss();
                            alertDialog.show();

                        }

                        writer.close();
                        reader.close();

                    }

Comment: Sim é possível, mas eu recomendo uma outra abordagem. Exibir um `DialogFragment` (usando `cancelable` como `false`) e iniciar uma `AsyncTask` no `onViewCreated`, atualizando-a ao final do processamento no método `onPostExecute`.
Comment: Diego, não entendi onde está usando `Thread` neste código. Além disso usar `StrictMode.ThreadPolicy.Builder().permitAll()` não inicia uma nova `Thread` e é uma má prática, porque mascara alguns problemas. Esse código está executando na `MainThread` e consequentemente travando a interface, recomendo dar uma olhada nessa pergunta para resolver isso: http://pt.stackoverflow.com/questions/33509/como-usar-a-biblioteca-ksoap2/33514#33514.
Comment: Wakim, na verdade acabei postando o código antigo, desculpe, se eu instanciar uma nova thread, existe uma maneira de colocar em espera o progressdialog para executar em tela e freezar os 2 segundos? Ou colocar em espera o proprio alertdialog,  por exemplo .. o código executa o progressdialog e apresenta em tela, depois instancia uma nova thread, coloca essa thread em espera por 2 segundos, e após isso executa o alertdialog apresentando as informações retornadas pela URL. Existe uma maneira de adaptar o código para executar dessa maneira?
Comment: Vou testar aqui agora! Muito obrigado.
Comment: Você pode tentar realizar o processo de busca de dados em outra thread,por exemplo só quando a thread terminasse sua execução vc chamaria o demiss do alertDialog... embora talvez nao seja a melhor solução..
Answer: Diego, vejo algumas coisas estranhas no seu código, por exemplo, você está chamando o método AlertDialog alertDialog = new AlertDialog.Builder(context).create(); dentro do loop (while). Segundo, você está executando um processo que pode demorar dentro da Thread principal.
Você poderia usar um AsyncTask, então no método onPreExecute, você inicia seu ProgressDialog, no método doInBackground você faz sua chamada Http e no método onPostExecute, você finaliza seu ProgressDialog e exibe seu AlertDialog.
Leia mais sobre AsyncTask
Answer: O certo é fazer isso usando uma AsyncTask
-Sua activity ficaria assim:
public class DemE extends Activity implements View.OnClickListener
{
    //Suponho que seja aqui aonde você roda o metodo
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        findViewById(R.id.btnConDe).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        String nomeProduto =  findViewById(R.id.cmdDigDe).getText().toString();
        String laboratorio = null;
        String aliquota = "17";

        if (nomeProduto == "")
            Toast.makeText(DemE.this, "Por favor digite o nome do medicamento", Toast.LENGTH_LONG).show();
        else
            new BuscaMedicamentosAsync(this).execute(
                new StringBuilder("nome=")
                        .append(nomeProduto)
                        .append("&aliquota=")
                        .append(aliquota)
                        .append("&laboratorio=")
                        .append(laboratorio == null? "" : laboratorio));
    }
}

-E o processamento fica por conta da async:
public final class BuscaMedicamentosAsync extends AsyncTask<CharSequence, Integer, CharSequence>
{
    private final AlertDialog alertDialog;
    private final ProgressDialog progressDialog;

    public BuscaMedicamentosAsync(Context contexto)
    {
        this.alertDialog = new AlertDialog.Builder(contexto).create();
        alertDialog.setTitle("Medicamentos:");
        alertDialog.setButton(0, "Voltar", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
            }
        });

        progressDialog = new ProgressDialog(contexto);
        progressDialog.setTitle("Listando medicamentos");
        progressDialog.setMessage("Buscando...");
        progressDialog.show();
        progressDialog.setCancelable(false); //Impedir que o usuario feche o dialogo
    }

    @Override
    protected CharSequence doInBackground(CharSequence... parametros)
    {
        StringBuilder result = new StringBuilder();
        try {
            URL url = new URL("http");
            URLConnection con = url.openConnection();
            con.setDoOutput(true);
            OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());

            writer.write(parametros[0].toString());
            writer.flush();

            BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String line;

            while ((line = reader.readLine()) != null) {

                result.append(line);
            }

            writer.close();
            reader.close();

        } catch (Exception e) {
            //Trata a exceção
        }

        return Html.fromHtml(result.toString()).toString();
    }

    @Override
    protected void onPostExecute(CharSequence text) {
        super.onPostExecute(text);

        progressDialog.dismiss();

        alertDialog.setMessage(text);
        alertDialog.show();
    }
}

Leitura recomendada

AsyncTask

Prioridade em progressdialog


error 6 when uploading json in watson discovery service

Question: when uploading a json sample document in watson discovery service, via the tool to create, i get this response:
<code>{
    "code": 400,
    "error": "6"
}
</code>
I tried stripping my whole json, so thats there are no strange characters. e.g.
<code>[
  {
    "text": "JDE Reset JDE password",
    "FunctionName": "ERP"
  }
]
</code>
i thought error 6 was for unsupported characters, but not sure anymore..
Answer: Try just with:
<code>{
    "text": "JDE Reset JDE password",
    "FunctionName": "ERP"
  }
</code>
if dont work, test with:
<code> {
        "Content-Type: application/json"
        "text": "JDE Reset JDE password",
        "FunctionName": "ERP"
      }
</code>


What are the impications of Varnishing Drum Shells?

Question: I have baught a second hand Mapex M kit which is practically identical to a Mapex V Floor tom I acquired previously. The only problem is that the floor tom is matte or wood finish and the kit is gloss.
I was wondering if there are any implications of using clear, internal use, gloss varnish on the floor tom to make it match the other drums on my kit?
Does it effect its value?
Does it effect the sound at all?
Most importantly will the wrong type of varnish damage the drum shell?
Comment: Not a dupe, but similar to this - http://music.stackexchange.com/questions/52129/oil-in-drum-wooden-shells-to-prevent-wood-to-dry-out?rq=1 To your 4 questions I'd say... You'll never make it look as good as a machine finish; yes; yes; & not if it was just a piece of furniture.
Comment: @Tetsujin do you know how it will effect the Sound? will it dampen the resonance? and im guessing it will decrease its value?
Comment: Best guess is it will lose depth & gain mids/highs - & likely not in a good way - but it will probably depend on the hardness/density of the varnish, how thick it is & how far it soaks in... which is far too much guesswork for me. & for value, no user-mod ever increased the value of anything.
Comment: If it gets done, it needs spraying rather than brushing - much thinner coat, and better finish.
Comment: Much more interesting if, as I did, you misread this as "vanishing drum shells" :-)
Answer: Putting a new layer of varnish over the drum shell will affect the tone somewhat, depending on how thick of a finish you put on. Unless it is very thick coating (like automotive clear coat or epoxy finish) you are unlikely to notice the difference.
Putting a gloss coat on a matte finish series instrument will affect being able to resell it to someone that is replacing that piece in a kit, or who is looking for the original look of the model.
The series itself doesn't seem to be in the "collectable" market, so you should be able to sell it as an individual drum on the used market for whatever the going rate is for that type, unless you end up with a bed finish job.
Getting a good, clean, gloss coating on the drum will not be a simple job.
You will have to seal the matte wax finish with a sanding sealer, then apply multiple coats of finish, with sanding in between, before doing a final buff and polish job. This can be done by hand with hours and hours of work, but having the right tools for the job would be the best way to assure a good result.
There are many options in the types of finishes available, and different ways of approaching getting the high gloss finish.  Each method can have a different process and result in different thicknesses of final finish. You will want to do some research on woodworking and wood finishes to decide what method is best for you.  You also might bring this question to the woodworking stack exchange:  https://woodworking.stackexchange.com/
Edit: Almost forgot,  In some cases the matte finish on music products isn't a true wax finish, but a thicker coating that has the gloss removed.  I have found in some cases (guitar and ukulele) that the coating is thick enough to polish out to a gloss finish with no additional coating necessary.  I can't tell from pictures of the drum set, but this may be the case and worth looking into.
Comment: This provides me with the advice I need. I think with the amount of work that may or may not be involved and the possibility of damaging my drums sound and screwing up the finish, with my limited (non-existent) woodworking experience, I think I'm just going to leave it well alone. thanks for the in depth answer though! :)


Diferença entre span img e div img

Question: Já vi em alguns códigos-fonte:

e em outros:

Isso está errado? sempre pensei que o  fosse usado exclusivamente para a renderização de textos.
Comment: Você pode citar um código que tenha exatamente esta sintaxe?
Comment: @bigown infelizmente eu não lembro o site. Mas, não é a primeira vez que vejo isso.
Comment: Sugiro que tenhas atenção a utilização de boas práticas de HTML5
Comment: 30 Minutos depois de colocares a pergunta e teres inúmeras respostas editas a mesma e alteras todo o significado do código? Primeiro tratava-se de um atributo `img` agora trata-se da tag `` dentro de determinado elemento ? Recomendo que leias a secção de ajuda sobre [como perguntar](http://pt.stackoverflow.com/help/how-to-ask) para evitares que as pessoas que tentam ajudar percam o seu tempo em vão.
Comment: @Zuul foi um descuido meu. Comentei isso em uma postagem, pois foi lá que percebi o erro.
Answer: Depende do seu objetivo. Isso é utilizado para herdar as propriedades do elemento superior.

Usando  é como se você quisesse aplicar style="display: inline".
Usando
 é como se você quisesse aplicar style="display: block".

Ou seja, o uso depende de como você deseja encaixar a imagem no seu layout.
Answer: Apesar de ambos poderem fazer praticamente as mesmas coisas há uma diferença semântica.
Como o nome indica
 deve ser usado para determinar divisões, blocos de informações diversas, para formar uma parte do layout.
Já o  é usado para indicar um trecho de informação, muitas vezes um trecho de um texto, ou imagens e outros elementos individualmente, sem querem montar um bloco.
Não é possível usar
 dentro de conteúdo do HTML, ou seja, você não pode dizer que uma palavra do texto tenha uma característica especial dizendo que ali é um bloco de layout. Você tem que usar o .
Cada vez mais o HTML tem tags que dão melhor significado para o conteúdo e deve-se escolher o mais adequado até mesmo quando é possível usar qualquer um deles. Eles são elementos relativamente genéricos e devem ser usados em detrimento aos elementos que antes eram usados de forma equivocada, como  (agora use um ) ou
 ou  (agora use
).  de fato é considerada obsoleta e não deve ser usada nunca, as demais podem ser usadas mas apenas quando você realmente quer um parágrafo ou uma célula de uma tabela, não deve ser usado para simular blocos de layout.
Exemplo:

#blocovertical1{
  display:block;
}

#textoEspecial1{
  display:inline;
  color:red;
}

#textoEspecial2{
  display:block;
  color:blue;
}

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Duis congue vehicula purus.

Nam eget magna nec sapien fringilla euismod. Donec hendrerit.

Coloquei no GitHub para referência futura.
Olha o que acontece quando tentamos usar o  como block. O texto não flui, ele é feito para ser usado como inline, ainda que seja permitido usar de outra forma.
As duas formas apresentadas no exemplo estão corretas. A imagem é um elemento inline, portanto pode ser usado normalmente com um . Mas elementos de bloco também podem conter elementos inline sem problemas. O comportamento pode ser ligeiramente diferente mas não há nada errado no seu uso. Se a imagem deve estar dentro de um bloco, coloque ela dentro de um bloco e ponto. Não há razão para criar um span sem que ele seja necessário, sem que ele precise estar inline.
Comment: Você está certo, eu coloquei errado o exemplo, mas já arrumei. Todavia, entendi a sua explicação.
Answer: De maneira resumida,  é mais frequentemente utilizado para elementos que fogem à regra geral do elemento agrupador que o envolve (uma
 por exemplo)
De uma olhada nesse site, está bem didático: http://pt-br.html.net/tutorials/css/lesson8.php
Answer: A tag
 é um elemento de bloco usado para criar um recipiente para conter e posicionar outros elementos. Ela é normalmente usada para posicionamento absoluto do conteúdo.
A tag é um elemento embutido que é usado para renderizar o texto usando uma folha de estilos. Ela é normalmente usada para alterar o estilo de um elemento ou texto dentro de uma sentença ou bloco como

, ou <tabela>
Fonte: http://support.microsoft.com/kb/180153/pt-br
Boa prática HTML5

Comment: @ bigown - Foi alguém que editou...apenas tinha o nome Microsoft...voltei a editar e coloquei o link
Comment:  pode sim ser utilizado com imagens.
Comment: @ Cassio Milanelo - Poder pode, mas não se deve..é uma questão de boa prática. Para os casos de imagem deve ser utilizado o
Comment: A fonte foi tirada da *tag* Microsoft? Lá não tem nada escrito sobre este assunto.

Diferença entre span img e div img


I can't have my virtualhosts working properly in Apache

Question: Although I know that this topic has been already discussed in some other threads where it is explained how to configure Virtualhosts in Apache. The thing is after looking for possible answers to my problem here, researching in Google and reading Apache official documentation I cannot have my problem solved.
Firstly, I had one WordPress installation running on Apache 2.4 installed in CentOS 7 and I set up the following Virtualhost:
<VirtualHost *:80>

ServerName subdomain1.domain.com
ServerAlias www.subdomain1.domain.com
DocumentRoot /some/path/to/wordpress

<Directory "/some/path/to/wordpress">
    DirectoryIndex index.php
    Options Indexes FollowSymLinks
    AllowOverride All
    Order allow,deny
    Allow from all
    Require all granted
</Directory>

<Files ".ht*">
    Require all denied
</Files>

ErrorLog "logs/subdomain1-error.log"
CustomLog "logs/subdomain1-access.log" combined
LogLevel warn

</VirtualHost>

It worked fine but then I decided to add a Moodle installation (because the server doesn't have too much traffic) and then if I browse in Chrome subdomain1.domain.com or subdomain2.domain.com it doesn't matter, Chrome always goes to subdomain2.domain.com (Moodle website).
I tried in Chrome and Firefox with same results. The moodle Virtualhost is:
<VirtualHost *:80>

ServerName subdomain2.domain.com
ServerAlias www.subdomain2.domain.com
DocumentRoot /some/path/to/moodle

<Directory "/some/path/to/moodle">
    DirectoryIndex index.php
    Options Indexes FollowSymLinks
    AllowOverride All
    Order allow,deny
    Allow from all
    Require all granted
</Directory>

<Files ".ht*">
   Require all denied
</Files>

ErrorLog "logs/subdomain2-error.log"
CustomLog "logs/subdomain2-access.log" combined
LogLevel warn

</VirtualHost>

Also, the Apache configuration file httpd.conf includes these VirtualHosts using the directive: IncludeOptional conf.d/*.conf
The file /etc/hosts is:
127.0.0.1   localhost

18.104.22.168 subdomain1.domain.com

18.104.22.168 subdomain2.domain.com

I cannot see any obvious error in my Apache Virtualhosts configuration files so I would appreciate if someone could give me a hint about what it is wrong and any possible error.
Thanks a lot.
Answer: You are trying to setup Name-based Virtual Host and missing an important config:
NameVirtualHost *:80

So, add the above line in your httpd.conf and restart apache/httpd, and it should solve the problem.
N.B. According to apache 2.4 documentation, this directive is deprecated and no longer needed.

Prior to 2.3.11, NameVirtualHost was required to instruct the server
  that a particular IP address and port combination was usable as a
  name-based virtual host. In 2.3.11 and later, any time an IP address
  and port combination is used in multiple virtual hosts, name-based
  virtual hosting is automatically enabled for that address.

But I'm yet to find out why it works with the above directive.
Comment: Thank you for your previous answer. You are absolutely right but I should have been more specific because each one are inside blocks:   After reading your previous response, I created two different site files but unfortunately I still get same results.  Can it be because both block headers are the same and then take one of them as default? (In my case the second one)
Comment: @castle10, can you add the line `NameVirtualHost *:80` in your httpd.conf (and restart apache), if it's not already there.
Comment: Thanks @bangal  Apparently, it was the key! Honestly, I didn't add this directive because I got this message: AH00548: NameVirtualHost has no effect and will be removed in the next release  but it made it works!
Comment: @castle10, according to apache 2.4 documentation this entry is not needed and deprecated, and that's why you are getting the warning. Can you check if you have a `Listen 80` or similar directive in your httpd.conf file?
Comment: Yes, I definitively have one and if I use netstat I can see that Apache is listening on port 80.


How to join tables based on condition in codeigniter

Question: I want to write a query in such a way that,if received id matches with $id then request should join with profile table as
r.sent_id = profile_id

If sent_id matches with $id,then
 r.sent_id = profile_id

My model,
public function getRequestedDetails($id) {
$this->db->select('*');
$this->db->from('profile');
$stat =  $this->db->where('recieved_id', $id);
if($stat)
$this->db->join('requests enter code hereas r', 'r.sent_id = profile_id', 'left');
$stat =  $this->db->where('sent_id', $id);
if($stat)
$this->db->join('requests as r', 'r.recieved_id = profile_id', 'left');
$this->db->where('r.status', 1);
$query = $this->db->get();
$list = $query->result();
return $list;
}

I tried this,it shows the following error
Error Number: 1066

Not unique table/alias: 'r'
SELECT * FROM `profile` LEFT JOIN `requests` as `r` ON `r`.`sent_id` = `profile_id` LEFT JOIN `requests` as `r` ON `r`.`recieved_id` = `profile_id` WHERE `recieved_id` = '5' AND `sent_id` = '5' AND `sent_id` = '5' AND `r`.`status` = 1

Can anyone help me.Thanks.
Comment: no use of adding this `$stat =  $this->db->where('recieved_id', $id);` and `$stat =  $this->db->where('sent_id', $id);` if id isset its all set, if empty its null
Comment: as wll there is separate id too `$this->db->where('sent_id', $id);`
Answer: Try this..
public function getRequestedDetails($id) {
    $query = $this->db->select('*')
             ->from('profile')
             ->join('requests','(requests.sent_id = ' . $id . ' AND requests.sent_id = profile.profile_id)
                OR (requests.recieved_id = ' . $id . ' AND requests.recieved_id = profile.profile_id'), 'left')
             ->where('profile.status',1)
             ->get();

    $list = $query->result();
    return $list;
}

Answer: Try this
SELECT *
FROM   profile
       LEFT JOIN requests AS requests
              ON (requests.sent_id = profile.profile_id OR requests.recieved_id = profile.profile_id)
WHERE  profile.recieved_id = '5'
       AND profile.sent_id = '5'
       AND profile.sent_id = '5'
       AND requests.status = 1


Is it possible to find sum of this series?

Question: I am trying to find the sum of the following series asked by my friend.
$$n\cdot\left(\bigl\lfloor\tfrac{n}{2}\bigr\rfloor+
\bigl\lfloor\tfrac{n}{3}\bigr\rfloor+
\bigl\lfloor\tfrac{n}{4}\bigr\rfloor+
\bigl\lfloor\tfrac{n}{5}\bigr\rfloor+
\cdots\right)$$
where the sum is up to $n/2$ terms if $n$ is even, and up to $(n-1)/2$ terms if $n$ is odd.
I am not getting how to solve it. Is this form can be reduced to a formula? Thank you.
Note: $\bigl\lfloor\;\;\bigr\rfloor$ means floor function, like $\bigl\lfloor 4.78\bigr\rfloor=4$.
Comment: What does `《...》` mean?
Comment: If $n$ is odd, what do you mean by "*$n/2$ terms*"?
Comment: M realy very sorry... plz have a look on updated quedtion
Answer: There is unlikely to be a closed form.
A related function is called the divisor summatory function $$D(n)=\sum_{m\le n} d(m)=\sum_{k=1}^n \left\lfloor\frac{n}{k}\right\rfloor $$  where $d(n)$ is the divisor function, the number of positive integers which divide $n$.  Your function is $nD(n)-n = n\sum\limits_{m\le n} \big(d(m) -1\big)$.
Since $D(n) \approx n\log_e(n) + n(2\gamma-1)$, where $\gamma \approx 0.5772156649$ is the Euler–Mascheroni constant, you might say your function was about $$n^2\big(\log_e(n) + 2\gamma-2\big)$$ though the absolute errors (positive or negative) can tend to grow faster than $n$ even if the relative error can tend to reduce: as an example, when $n=10079$ your function would give $850294677$ while the approximation would be about $850545092$, while for the highly composite $n=10080$ your function would jump up to $851094720$ while the approximation would be about $850723956$.


Error while building MFP Cordova Mproject

Question: I am facing an issue integrating cordova plugin into IBM Mobilefirst 7.1 Hybrid application. We followed the IBM Knowledge and created MFP Cordova project, integrated custom cordova plugin into the project. But while building the project we are getting build error. During build it is not able to reference classes from aar files that is there in cordova plugin.
<code>  What build tool does mfp cli uses to build cordova project? Can we change it any other build tool.
</code>
Answer: Cordova applications creating using MobileFirst CLI 7.1 generate Cordova projects that are based on Cordova 3.6, which is somewhat outdated.
You cannot replace the Cordova version that is added when using the MobileFirst CLI 7.1. This in turn may limit the plugins you are able to use, so my suggestion is:

Pick the plugins that are compatible with the mentioned Cordova 3.6, or
Consider upgrading to MobileFirst Foundation 8, with which you are now no longer restricted by tools provided by IBM. You create the Cordova application using the Cordova CLI (not MobileFirst CLI). You then add the MobileFirst SDK to the application like any other Cordova plug-in.

Learn more about Cordova applications in MobileFirst Foundation 8.0: https://mobilefirstplatform.ibmcloud.com/tutorials/en/foundation/8.0/cordova-tutorials/
Comment: Thank you Idan for the response. I am currently using the second approach. I am getting the below error. {status: 404, statusText: "Not Found", responseText: "Error 404: javax.servlet.ServletException: java.io… not found: /api/adapters/ServiceAdapter/doLogin↵", responseHeaders: Object, errorMsg: "Not Found"…}errorCode: "UNEXPECTED_ERROR"errorMsg: "Not Found"responseHeaders: ObjectresponseText: "Error 404: javax.servlet.ServletException: java.io.FileNotFoundException: SRVE0190E: File not found: /api/adapters/ServiceAdapter/doLogin↵"status: 404statusText: "Not Found"__proto__: Object}.
Comment: It is not taking the runtime specified in wlclient.properties.
Comment: Your question is not clear and it has nothing to do with the original question.
Comment: Can we use cordova-plugin-mfp for creating mfp cordova project that can run on Mobilefirst 7.1?
Comment: You cannot. The SDK and security framework are incompatible.


Every affine k-scheme can be embedded into an affine space?

Question: While reading through Algebraic Geometry I by Görtz and Wedhorn (2nd version) I came across the following remark on p. 352 (between Proposition 12.66 and Corollary 12.67):
If $Y$ is an affine $k$-scheme, we can embed it into affine space $\mathbb{A}^{(I)}_k$ ($I$ some index set).
This remark is not further explained. Why is it true? For me it seems non-trivial, if $Y$ is not of finite type.
Comment: Every $k$-algebra is isomorphic to a quotient of a polynomial ring in some (possibly infinite) number of variables with coefficients in $k$. This is just because the polynomial rings with coefficients in $k$ are free $k$-algebras on the set of polynomial generators. Similarly (same proof, different category), every module is isomorphic to a quotient of a free module.
Comment: Thank you very much.
Answer: An affine $k$-scheme $X$ is given by the spectrum of a $k$-algebra $A$. We can pick generators $\{a_i\}_{i\in I}$ for $A$ as a $k$-algebra, which gives a surjective morphism from the polynomial ring $k[x_i]_{i\in I}\to A$ given by sending $x_i\mapsto a_i$. The spectrum of this map is exactly the closed immersion of $X$ in to $\Bbb A^{(I)}_k$. This proof does not care whether $I$ is finite or not.
Comment: Thank you very much.


Is ANOVA relying on the method of moments and not on the maximum likelihood?

Question: I see mentioned in various places that ANOVA does its estimation using the method of moments.
I am confused by that assertion because, even though I am not familiar with the method of moments, my understanding is that it is something different from and not equivalent to the method of maximum likelihood; on the other hand, ANOVA can be seen as a linear regression with categorical predictors and OLS estimation of regression parameters is maximum likelihood.
So:

What qualifies ANOVA procedures as the method of moments?
Given that ANOVA is equivalent to OLS with categorical predictors, isn't it maximum likelihood?
If these two methods somehow turn out to be equivalent in the special case of usual ANOVA, are there some specific ANOVA situations when the difference becomes important? Unbalanced design? Repeated measures? Mixed (between-subjects + within-subjects) design?
Comment: In the simple setting, and by simple I mean one and two-way ANOVA, the ANOVA is derived from an LRT under normal distributions with equal variances so it is maximum likelihood that is used. Of course for the normal case, the mle and the mom estimators coincide so the distinction is not of great importance. In the more complex settings, however, rather than deriving LRTs, we rely on OLS regression. The OLS is only the mle under a normal distribution and is a mom estimator in the more general setting, if we impose the orthogonality with the residuals that is.
Comment: @amoeba. I edited my answer to address your first point about ANOVA being a method of moments estimator. That's only true for random effects.
Comment: @JohnK, thanks a lot for your comment but I have hard time understanding some parts of it, in particular the second part: what are "more complex settings" in which ANOVA relies on OLS instead of LRT (and why)? Why is OLS not MLE in this "more general setting" -- I thought that normal errors are always assumed in any ANOVA scenario? What does orthogonality with the residuals have to do it? I will greatly appreciate if you expand your comment into an answer.
Answer: I first encountered the ANOVA when I was a Master's student at Oxford in 1978. Modern approaches, by teaching continuous and categorical variables together in the multiple regression model, make it difficult for younger statisticians to understand what is going on. So it can be helpful to go back to simpler times.
In its original form, the ANOVA is an exercise in arithmetic whereby you break up the total sum of squares into pieces associated with treatments, blocks, interactions, whatever. In a balanced setting, sums of squares with an intuitive meaning (like SSB and SST) add up to the adjusted total sum of squares. All of this works thanks to Cochran's Theorem. Using Cochran, you can work out the expected values of these terms under the usual null hypotheses, and the F statistics flow from there.
As a bonus, once you start thinking about Cochran and sums of squares, it makes sense to go on slicing and dicing your treatment sums of squares using orthogonal contrasts. Every entry in the ANOVA table should have an interpretation of interest to the statistician and yield a testable hypothesis.
I recently wrote an answer where the difference between MOM and ML methods arose. The question turned on estimating random effects models. At this point, the traditional ANOVA approach totally parts company with maximum likelihood estimation, and the estimates of the effects are no longer the same. When the design is unbalanced, you don't get the same F statistics either.
Back in the day, when statisticians wanted to compute random effects from split-plot or repeated measures designs, the random effects variance was computed from the mean squares of the ANOVA table. So if you have a plot with variance $\sigma^2_p$ and the residual variance is $\sigma^2$, you might have that the expected value of the mean square ("expected mean square", EMS) for plots is $\sigma^2 + n\sigma_p^2$, with $n$ the number of splits in the plot. You set the mean square equal to its expectation and solve for $\hat{\sigma_b^2}$. The ANOVA yields a method of moments estimator for the random effect variance. Now, we tend to solve such problems with mixed effects models and the variance components are obtained through maximum likelihood estimation or REML.
The ANOVA as such is not a method of moments procedure. It turns on splitting the sum of squares (or more generally, a quadratic form of the response) into components that yield meaningful hypotheses. It depends strongly on normality since we want the sums of squares to have chi-squared distributions for the F tests to work.
The maximum likelihood framework is more general and applies to situations like generalized linear models where sums of squares do not apply. Some software (like R) invite confusion by specifying anova methods to likelihood ratio tests with asymptotic chi-squared distributions. One can justify use of the term "anova", but strictly speaking, the theory behind it is different.
Comment: The F-test of one-way and two-way ANOVA *is* a likelihood ratio test and you can consult Hogg and Craig, Intrduction to Mathematical Statistics, chapter 9 if you don't believe me. Moreover, the F-test used in normal regression is also an LRT, numerous references for that out there.
Comment: After 1.5 years I re-read your answer and realized that it's pretty clear, so I finally marked it as accepted :-) Cheers.
Comment: I'll check. For now, I have removed the paragraph.
Comment: +1, thank you very much for the answer. It's exactly your linked answer that triggered my question, by the way. There are many things that I don't quite understand in what you wrote. I will be traveling over New Year and will have no time to think about it, but I will come back to this thread once I am back in January. In the meantime, I'd like once again to encourage @JohnK to post an answer expanding on the points that he made in the comments. I'd particularly appreciate some more technical explanation, perhaps with a specific example. Merry Christmas and happy New Year to all of you!
Comment: Merry Christmas to you also. In my linked post, I was just thinking about the estimation of the random effect variance, which is MOM in the traditional approach. Sorry if my remark sounded more general that I intended.


Find asymptotics in a given form $n=(e+o(1))^{f(s)}$

Question:
Let $p\to\infty$, $s={\binom {p^4} p}$ and $n={\binom {p^4}{p^2}}$. Find a function $f(s)$ in the following form $$\large n=(e+o(1))^{f(s)}$$

I've tried to use the followinf asymptotics for binomial coeffs:
$$\binom n k =  \frac{n^k \exp\left(k^2/2n\right)}{k!}(1+O(1))$$
And I've got the following results:

$$s={\binom {p^4} p} = \exp\left({2p^2 \ln p - \frac{1}{2} (1 + \ln 2\pi) + p^2 + \ln p + O\left(\frac{1}{p^2}\right)}\right)$$
$$n={\binom {p^4}{p^2}} = \exp\left({4p\ln p - \frac{1}{2p^2} - \left(p + \frac{1}{2}\right)\ln p + p - \frac{1}{2}\ln 2\pi + O\left(\frac{1}{p}\right)}\right)$$

What should I do next? A hint would be useful!
Comment: Perhaps use Stirling's asymptotic approximation for $n!$.
Answer: For the beginning some preparatory computations:
$$
\begin{align}
{n\choose k}
&=\frac{n\ldots (n-k+1)}{k!}\\
&=\frac{n^k}{k!}\left(1-\frac{1}{n}\right)\ldots\left(1-\frac{k-1}{n}\right)\\
&=\frac{n^k}{k!}\exp\left(\sum_{i=1}^{k-1}\ln\left(1-\frac{i}{n}\right)\right)\\
&=\frac{n^k}{k!}\exp\left(\sum_{i=1}^{k-1}\left(-\frac{i}{n}+O\left(\frac{i^2}{n^2}\right)\right)\right)\\
&=\frac{n^k}{k!}\exp\left(-\frac{k(k-1)}{2n}+O\left(\frac{k^3}{n^2}\right)\right)\\
\end{align}
$$
Thus
$$
{n\choose k}=\frac{n^k}{k!}e^{-\frac{k(k-1)}{2n}+O\left(\frac{k^3}{n^2}\right)}
$$
Given this formula and Stirling's approximation we get
$$
\begin{align}
\ln s
&=\ln {p^4\choose p}\\
&=p\ln p^4-\ln p!-\frac{p(p-1)}{2p^4}+O\left(\frac{p^3}{p^8}\right)\\
&=4p\ln p-\left(p\ln p-p+\frac{1}{2}\ln p+\ln\sqrt{2\pi}+O\left(\frac{1}{p}\right)\right)-\frac{1}{2p^2}+\frac{1}{2p^3}+O\left(\frac{1}{p^5}\right)\\
&=3p\ln p+p-\frac{1}{2}\ln p-\frac{1}{2}\ln 2\pi+O\left(p^{-1}\right)\\
&=3p\ln p+O(p)
\end{align}
$$
$$
\begin{align}
\ln n
&=\ln {p^4\choose p^2}\\
&=p^2\ln p^4-\ln (p^2)!-\frac{p^2(p^2-1)}{2p^4}+O\left(\frac{p^6}{p^8}\right)\\
&=4p^2\ln p-\left(p^2\ln p^2-p^2+\frac{1}{2}\ln p^2+\ln\sqrt{2\pi}+O\left(\frac{1}{p^2}\right)\right)-\frac{1}{2}+\frac{1}{2p^2}+O\left(\frac{1}{p^2}\right)\\
&=2p^2\ln p+p^2-\ln p-\frac{1}{2}\ln 2\pi e+\frac{1}{2p^2}+O\left(p^{-2}\right)\\
&=2p^2\ln p+O(p^2)
\end{align}
$$
We claim, that
$$
f(x)=\frac{2\ln^2 x}{9\ln\ln x}
$$
is the desired function. Indeed,
$$
\begin{align}
\ln^2 s
&=(3p\ln p+O(p))^2\\
&=9p^2\ln^2 p+6p\ln p O(p)+O(p)^2\\
&=9p^2\ln^2 p+ O(p^2\ln p)+O(p^2)\\
&=9p^2\ln^2 p+O(p^2\ln p)\\
\end{align}
$$
$$
\begin{align}
\ln\ln s
&=\ln(3p\ln p+O(p))\\
&=\ln(3p\ln p(1+O(\ln^{-1}p)))\\
&=\ln 3+\ln p + \ln\ln p + \ln(1+O(\ln^{-1}p))\\
&=\ln p + \ln\ln p+\ln 3+O(\ln^{-1} p)\\
&=\ln p+O(\ln\ln p)\\
\end{align}
$$
$$
\begin{align}
f(s)
&=\frac{2\ln^2 s}{9\ln\ln s}\\
&=\frac{2(9p^2\ln^2p+O(p^2\ln p))}{9\ln p+O(\ln\ln p)}\\
&=\frac{9\ln p(2p^2\ln p+O(p^2))}{9\ln p\left(1+O\left(\frac{\ln\ln p}{\ln p}\right)\right)}\\
&=(2p^2\ln p+O(p^2))\left(1+O\left(\frac{\ln\ln p}{\ln p}\right)\right)\\
&=2p^2\ln p+O(2p^2\ln\ln p)+O(p^2)+O\left(p^2\frac{\ln\ln p}{\ln p}\right)\\
&=2p^2\ln p+O(p^2)\\
\end{align}
$$
Since
$$
\ln n-f(s)=2p^2\ln p+O(p^2)-(2p^2\ln p+O(p^2))=O(p^2)=o(2p^2\ln p+O(p^2))=o(f(s))
$$
then $n=(e+o(1))^{f(s)}$
Comment: I don't recall that. A reference would be nice. Also, what is the range of $k$ for which the approximation holds?
Comment: @martycohen see edits to my answer


Robust linear regression for group differences

Question: I am trying to understand what it means when a p value for a grouping variable is < 0.05 after running robust linear regression.
Does this mean that the 2 groups significantly differ with respect to the dependent variable?
How is this method conceptually different from running a simpler anova?
Thank you in advance for your help.
Comment: Q1 yes, Q2 not really.
Comment: It will be helpful to write down exactly what the null and alternative hypotheses are, both for this and a regular ANOVA F-test (in regression form).
Answer:
Does this mean that the 2 groups significantly differ with respect to the dependent variable?

If you run a regression where $z$ is a binary indicator for group membership, the the coefficient $\beta_2$ in the model
$$ y_i = \beta_0 + \beta_1 x_i + \beta_2z_i + \varepsilon_i$$
represents the difference in the expectation conditioned on $x$.

How is this method conceptually different from running a simpler anova?

In the case where the grouping variable has several groups and you have no other covariables to adjust for ($x$ in the model above) then the regression model is exactly an ANOVA.


Distribution of Data Within Hypersphere That Maximizes the Nuclear Norm?

Question: Suppose I have $N$ points in $\mathbb{R}^D$ such that for each point $x_n$, its L2 norm is at most 1:
$$||x_n||_2^2 = x_n^T x_n \leq 1$$
Assuming $N > D >> 0$, if I construct a matrix $X \in \mathbb{R}^{N \times D}$ where the $n$th row of $X$ is $x_n$, what distribution over $x_n$ maximizes the nuclear norm (also called trace norm) of $X$?
$$||X||_* := \sum_{r=1}^{rank(M)} \sigma_r(M)$$
I know that, in this setting, the nuclear norm is upper bounded by $\sqrt{ND}$, and I believe that the uniform distribution on the surface of the sphere achieves this upper bound. Is that correct? Do other distributions also achieve this upper bound?
Comment: How do you consider on the one hand a 'distribution' which results in stochastic variable behaviour, and on the other hand a maximisation of a 'norm' that does not incorporate how to deal with the stochastic behaviour? For example, two random points (N=2) distributed on a circle (D=2) will not have a nuclear norm that is constantly equal to $\sqrt{ND} = 2$.
Comment: In what sense can a *distribution* maximize anything that is a varying function of the random variable?  Are you perhaps asking for the *expectation* of the trace norm?  Are you assuming the $N$ points are independent or not?
Answer: I get a larger norm when I select points from a distribution centered at the axes of the sphere.
An example computation is with the code below. (The one distribution will end up with a norm equal to $\sqrt{ND}$ but the uniform distribution is not)
<code>set.seed(1)
n = 30

### n points from a uniform distribution on a sphere
phi = 2*pi*rnorm(n)
x = cbind(cos(phi),sin(phi))

### n points from a discrete distribution at four points
rows = cbind(c(0,0,1,-1),c(1,-1,0,0))
k = sample(1:4,n, replace =1)
y = rows[k,]

sum(svd(y)$d)^2 ### 60 = 30*2 = n*d
sum(svd(x)$d)^2 ### 59.64603
</code>
But this is just a single sample. The average of samples might be a different issue (the equality with $\sqrt{ND}$ in the above example is a coincidence). Is is the average that you are after?


Staccato and legato in Beethoven's Op.2 No.1 - how to play?

Question: How should one play this passage in Beethoven's Op.2 No.1?  One cannot play staccato and use the pedal because notes on the upper stave would not sound staccato.
Comment: Related with https://music.stackexchange.com/questions/5546/can-legato-notes-be-played-staccato
Answer: Why would you want to play anything but staccato? That's all that's marked. There's no pedal marking at all. Did you think 'pp' meant pedal? It means fairly quietly.So, it could be played with the soft pedal depressed.
Comment: @AlbrechtHügli - OP may be confused, thinking slur marks equal 'use the damper pedal', which is not so. Pedal marks usually have 'Ped'.
Comment: Tim, I think Rui means the slurs above the 4 staccato signs.
Comment: So - as far I have learnt from you - this posting is rather acomment thanan answer? ;)
Comment: @AlbrechtHügli - whatever you prefer - but OP asks about *piano*, portato is *strings*.
Comment: According e.g. to Wikipedia, «A slur is a symbol in Western musical notation indicating that the notes it embraces are to be played without separation (that is, with legato articulation).» Since using the pedal is a possible solution when playing legato with the fingers is infeasible, it seemed reasonable that staccato under a slur would be played using staccato in your fingers and the pedal for connecting the notes (the sound quality is different from regular playing with the pedal).
Comment: @Rui - no, pedal is not usually used when playing slurred notes. Slurring is rather like speaking a phrase in one breath. The first word we speak doesn't carry on when the next comes out. Playing is the same. As one note stops, another starts. Pedalling will not give that effect. And - that slur - quite probably a phrase mark anyway - means all the notes are NOT staccato - they're not marked as such, so there is no need to pedal any of that anyway. No need, and certainly no direction, and you wouldn't find any good player even considering pedalling there. All 4 notes are easily played legato.
Comment: @Tim - I agree that this slur must be a phrase mark, no legato intended. What confused me is that slurs are also used to imply legato articulation.
Regarding the pedal, it can definitely be used for playing legato even when you don't want previous notes to carry on, you just need to momentarily release it and depress it again as soon as you play a new note.
Comment: @Rui - of couse the pedal gets used for legato playing, but usually when there's no other way to sustain notes. Id like to see how you would play those semis using the pedal No-one could operate it that quickly, and with all notes falling under the fingers, why would it be needed anyhow? And - slur - phrase mark - legato - all amount to the same end product. Those notes were never staccato.
Answer: The bow or slur above the staccato notes is
one type of portato notation, also used for staccato and flying spiccato.
https://en.wikipedia.org/wiki/Portato
Not only for strings, for all iinstruments and also for pianos this slur means the same articulation, but it is not a legato and is not played with a pedal:
The desire of editors and composers to make their intentions clear down to the very last detail includes the use of large sweeping 'slur-like' lines called 'phrase marks'. Slurs, which tend to embrace a smaller number of notes, help to shape the musical line even within broader phrasing marks and performers must be able to distinguish between them. On wind instruments, all the notes under the slur except for the first, are untongued, the breath flowing continuously while the fingers move. On stringed instruments, the equivalent effect is achieved by using a single sweep of the bow for each slur or phrase. On keyboard instruments the notes are played legato (smoothly) and with a light touch.
The slur removes the attack from the start of each note under it except for the first so providing a contrast in strength, a dynamic variety, between the first and the later notes. If slurring is to be effective, or indeed a distinction made between different phrases, the performer must avoid playing unslurred notes too smoothly. Evidence from the eighteenth century suggests that music then was played in a more detached manner than we associate, say, with the repertoire of the late-Romantic.
The way a staccato mark under a slur is realised will also depend on the instrument for which the instruction refers. On a piano, the staccato under a slur is a portato where the individual notes sound for three-quarters of their written duration.
Source: https://www.dolmetsch.com/musictheory21.htm
Answer: Slurs are not pedal marks.  In this case I would interpret the slurs as phrasing slurs, meaning that while playing all of them staccato, one bar forms a phrase of them.  A phrase can be executed by a consistent execution, like a subtle development in volume or staccato shortness or accent that repeats every measure.
When the bass line is taken by a bowed string instrument (obviously not the case for a piano sonata), this kind of notation means to change bow direction every bar even while every note is staccato in itself.  The musical effect of tying the notes of one measure into a phrase then has a more tangible expression.  Maybe entertain a mental image of that when playing it on the piano.
Comment: I agree with your answer and accepted it as correct. However, according to [this](https://msu.edu/~newmanr/484/Handouts-Worksheet/Articulations/Articulations.htm) «staccato notes under a slur, indicating somewhat obscurely that these should be "smoother" notes, with just a small space between the notes» Music is definitely not an exact science. :-)


How to return TRUE with time()?

Question: How to return TRUE when an account was created more than 30 days ago?
I have the following date:
$udata['joined']; - record date in time():
I tried like this
If($udata['joined'] = strtotime ("+30 days", time())){
    return true;
}

Any idea why it's not working correctly?
Return empty.
Comment: A single `=` is an assignment [operator](https://www.php.net/manual/en/language.operators.php). For readability, I would utilise converting it to a `DateTime` object and then using the inbuilt `diff` method. [See an example on 3v4l.org](https://3v4l.org/hIWtT)
Answer: I guess you want
If timestamp is smaller than (or exactly) 30 days ago
if ($udata['joined'] <= strtotime("-30 days", time()) {
    return TRUE;
}

(you need to substract 30 days from now and remove all syntax errors)
Answer: You are assigning a value instead of using an operator, i.e. you are using = instead of ==. Try this:
If($udata['joined'] == strtotime ("+30 days", time())){
    return true;
}

Edit
As others pointed out, checking for equality will most likely always return false anyway, because you'd be very luck to hit the exact same timestamp!
What you are looking for is the <= (less than or equal) operator to check if $udata['joined'] is a timestamp before 30 days ago. In other words :
// true if the provided date is before 30 days ago
return strtotime($udata['joined']) < strtotime("-30 days", time());

How to return TRUE with time()?


Is it valid to apply large scale statistics to a single case?

Question: I have a small black box that displays a 0 or a 1 every time I press its button.
I can tell you, truthfully, that over the past 20,000,000,000 times it has been pressed, 19,999,999,990 times it has shown a 1.
I ask you to make a prediction of what number will appear when I press the button next.
For the sake of simplicity, I won't attach any form of consequences to the results. You make a guess, and you are either right or wrong.
How do you make your choice, and in what way do you find that choice to be valid?

Here's some other constraints that you can feel free to apply or discard if you think the result would be interesting:
<code>1. The temporal distribution of the recorded results is unknown.
2. The display is blank until the button is pressed, and the digit will appear for a short amount of time afterwards. It is blank when you see it.
3. The button being pressed causes the display of the digit.
</code>
Comment: Feel free to explore any of those possibilities and how they would affect your decision, but I can add some specifics to the problem if that would help. I would assume a random temporal distribution. The display is blank until the button is pressed, and the digit will appear for a short amount of time afterwards. It is blank when you see it. The button being pressed causes the display. But again, feel free to inform me on how a different constraint would change the problem significantly and use that as rationale.
Comment: I had a discussion that led me to Propensity Probability and a problem like this, and thought I would see if there were any other rational answers for this problem.
Comment: Any additional info available about when the zeros occurred in the sequence of 20 billion presses, or whether either number is displayed by default (i.e., does the button display something that doesn't appear otherwise, or does it change the display only sometimes), or whether the relationship between the button and the display is causal (i.e., does the button actually affect the display)?
Answer: First I would like to say that I'm not sure if I fully understand what you ask in your actual question. The whole concept of statistics (or more rigorously inference theory) is to draw conclusions from the given data, so yes it is possible to use statistics to make predictions about a single case as long as you have any data to base you prediction on. You would not need statistics to predict the outcome if you know all the variables and relations in the the process exactly.
In your example you are asking for a prediction of the next outcome in some unknown random process. We have no knowledge of the dependence between the trials you describe. What we do know is that we have a dichotomous outcome ($0$ or $1$) with an unknown probability $p$.
Essentially what we are looking for is the conditional expectation of the next state given all previous values.
$$
  E[X_{i+1}|X_i, X_{i-1}, \ldots, X_0]
$$
Here we need to make an assumption on the dependence between trials in order to continue. Lets investigate both possible assumptions.
1. Independent trials
Assuming the trials are independent, i.e the expected outcome is independent of previous outcomes. If this is the case you describe something which is known as a Bernoulli trial. The best estimator of the probability of success (to get $1$) is the sample mean.
$$
 \hat p = \frac{1}{N}\sum_{i=0}^N x_i,
$$
where $x_i$ are each of our previously recorded outcomes. Each outcome is however not given in the problem but instead only the count of events displaying $1$ (lets call this sum $T$). Luckily $T$ is a sufficient statistic for the probability parameter $p$ of the Bernoulli distribution. By sufficient statistic we mean a summary statistic containing all information about the sought parameter.
$$
 \hat p = \frac{1}{N}T = \frac{19999999990}{20000000000} \approx 1.
$$
This gives us a probability very close to 1 of getting a $1$ in a trial. The expectation of the next trial is thus
$$
 E[X_{i+1}] = p \approx 1
$$
And our best estimate of the next trial is $1$ with a very high probability.
2. Conditional trials
Here we assume the expected outcome is dependent on previous outcomes. This seems very reasonable, since as the process is unknown we cannot rule out that we have a dependence on previous values. However, dependence is something we cannot really address as we have only been given a summary statistic which is not sufficient for models making use of this dependence. (At least I do not know of any such model)
Say for example that the process is a Markov process with a large probability of staying in the same state. In this case our prediction in the independent model might be very wrong if the last observation was $0$. However, as the summary statistic ($T$) given in the problem statement is not sufficient for the parameters in this model.
Conclusion
This leaves us with only one option. In order to make a prediction given the data at hand we have to assume independence. If we were to use a more complex model without the support of data we would have to start guessing.
The best prediction given the data is therefore $1$.
I hope this answers your question.
Comment: No worries, but I thought I did. I think what you are after is some deeper discussion on the meaning of probability. Probability absolutely makes sense in one trial. Take the example of throwing a fair die. Each throw you will have a 1/6 chance of getting 1 (or whatever single outcome you want) regardless if the die is hidden or not. This is not based on any frequenzy of the outcomes but the structure of the problem. The probability simply states how big your chance is of getting the desired outcome. If you cannot see this probability directly you can estimate it using previous observations.
Comment: Sorry if I sound pedantic, but can you give a citation or explanation on why it's reasonable to expect that the i+1 trial will be 1? My understanding is that probability only describes a relative frequency over time (frequentism) and as such using a calculated probability to predict the result of a single trial is not valid. At least, this is the point of contention for me.
Comment: That is what I am after I believe. I'm finding more and more that it's not a commonly touched subject. Thanks for your help though.


Why did Albéniz write in C♭ instead of B?

Question: I'm referring to Evocación, the first movement of Iberia, which is in the key of C flat (7 flats, every note flat). The key of B uses exactly the same hotes, but using 5 sharps instead of 7 flats. To the listener the C♭ and B keys sound identical. 5 sharps are easier, one would think, to deal with than 7 flats. The meaning of choosing C♭ over B has nothing to do with the sound of the piece, and it makes the work harder notationally for the performer. There is a message to the performer (who is the only one who would know) in the choice of the C♭ key. If you can't play this key you shouldn't even be looking at this piece? Flats are more dreamy, but sharps grate? For the performer only? Commentary welcome.
I'm a pianist, and have performed this piece, for myself only, many times.
Comment: Personally I think Cb major is quite a straightforward key to play in, because everything is flat.   No harder than B major in my view.
Comment: I disagree with this. In Cb you have to play B instead of C and E instead of F. For me that's at least a little confusing. The key of B just uses all five black keys instead of the white keys just below them.
Comment: @JimM Conceptually, C♭ seems easier for me, because it's literally "C but everything has a flat". But playing it, it seems harder for me than B major. Maybe that says something about how I (and other people) conceptualise music? Or maybe I'm overanalysing.
Answer: It's a trade-off over how to write the accidentals to be consistent with the harmony and avoiding enharmonic "jumps" in the notation.
Even with 7 flats in the key signature, there are a couple of bars in the middle which are full of sharps, which might be a notational mess in B major. (I haven't actually written it out B to check, though!)
The ending is in A flat major with a change of key signature, but a G sharp major ending would have had 9 sharps in the key signature.
Comment: @Andy Nothing is _wrong_ in terms of the notes played when your instrument is 12-TET. However, moving Cb -> Ab is a I -> VI movement (common), but B -> Ab is I -> VIIbb (what!?). There is something to be said for picking the key of least friction, but having the notes be meaningful in they key is also important, as the relativity of notes influences their function within the piece. I have seen "notationally correct" pieces with double sharp/flat key signatures for this reason. Those weren't the versions given to performers though.
Comment: What's wrong with B major followed by Ab major? Why does it matter if one key has sharps and the next has flats?
Comment: It's relatively common for piano music to modulate to the enharmonic equivalent of a certain scale degree to avoid overly complex key signatures. Chopin does it quite often and even Schubert is not afraid of this.
Comment: @CAD97 If your comment were fleshed out into an answer, it would probably be the best one. (Not that the existing ones are bad, that's just a very valuable comment.)
Comment: @11684 Similarly, see any piece modulating through all twelve major keys (Beethoven, for instance, has a set of two preludes that do this); of course somewhere in the middle of the sequence there's a modulation that only makes sense enharmonically!
Comment: @11684 I suspect that to be one reason why I've never much enjoyed Chopin or Schubert. They write too much from a 12-edo aligned point of view, making the mostly-consonant parts boringly directionless and the more unusual harmonic stuff jarring and without really conclusive effect. (Of course, others might well consider the style as particularly dreamy and detached from previous rules, YMMV. Debussy took it to the extreme where I start liking it again.)
Comment: @leftaroundabout Perhaps you'd prefer their music in a less anachronistic tuning system?
Comment: The "bars full of sharps" are where Albeniz has done an enharmonic change. If he had started in g# minor, there would have been no enharmonic change and no mess.
Answer: There are many valid reasons to prefer one enharmonic variant over the other.

As alephzero has pointed out, if the harmonic structure of your movement tends to modulate upward it is almost certainly better to notate seven flats than five sharps, to avoid a disruptive break in notation half-way through.
J. S. Bach was quite capable to notate a piece in D sharp rather than E flat simply because he needed to plug a gap in his omnitonal works, he already had a fugue in D lying around and transposing D to D sharp is easier for the copyist than D to E flat.
When a harp piece is notated in C flat, this means that you're using the longest, least tense position of each string, which results in a particularly mellow sound.

The point is, without a source documenting that Albeniz chose this variant for one particular reason rather than another, there are too many possibilities to decide that question.
Comment: Whoah! Whole can of worms opening here! Basic harp tunings are C, Eb and Ab - geographically  influenced, in the main. But - often they are tuned to coincide with the key of the piece, so I guess, without looking at the score, this harp would be retuned to Cb (or maybe B...)  Lever harps have levers that allow two not choices ( natural/sharp or natural/flat), whereas pedal harps have three choices - flat/natural/sharp.
Comment: @Tim Lever harps and other "folk music" harps follow their own rules. Kilian Foth was talking about orchestral harps which are standardized (7 strings per octave tuned by C flat major, pedals with two notches to raise the pitch to natural or sharp). To an orchestral harpist, written B and Cb are always notes played on different strings. For diminished 7th glissandos, you do set the pedals to produce some doubled notes on adjacent strings - e.g. C dim7 would be C D# Eb F# Gb A B#. Like a guitar, the open strings (tuned in flats) are more resonant than "fretted" strings using the pedals.
Comment: Could you expand the harp theory, please? I'd have thought ( maybe erroneously) that the Cb string on a harp is also the B string. When I play guitar/bass, I pluck in different positions along the string, and although that changes the tone, it doesn't change pitch, and if it does, it's only for the first fraction of a second.
Comment: @Tim The harp is quite interesting: it has a pattern of 7 strings, CDEFGAB, which you then use pedals to tune up or down a half step. I thought originally they had a pattern of 12 (semitonal) strings, but the actual pattern is the 7 strings of the C scale, allowing for the traditional harp gliss. [Read More](https://en.m.wikipedia.org/wiki/Harp)
Comment: @CAD97 - so,  similar to a chromatic harmonica, or pedal steel guitar, in different ways! I haven't tinkered with a harp since 1967, so it's all been forgotten. And maybe the Welsh harp is different anyway? Still has coloured strings, I guess?  AND - does a pedalled Cb sound the same as an open B??
Comment: As I recall a concert harp is tuned to a scale of Cb major.  It has 7 pedals which will each lock into three different positions.  Each pedal does ALL the strings of a particular pitch, so one pedal does all the Cs, another all the Ds etc. So for each string you can have the basic note or the one a semitone above or the one a semitone above that.  So you can put all strings up a semitone to get C major or all up again to get C# major.  Clearly you can then get any key that you want.
Comment: Just to add that some fully chromatic orchestral harps (12 strings per octave) have been made. They are required for some 20th/21st century works. In fact the Welsh harp was a predecessor of this - it has three "layers" of strings, the outside two tuned in unison to the diatonic scale of the piece, and the middle layer to the other 5 chromatic notes. Re-tuning is done by pedals as with the orchestral harp. The duplicated diatonic strings, one set for each hand to play, adds some more playing techniques like quick repetition of a note using both hands on the pair of unison strings.
Comment: I would say it's about the same as asking whether the same pitch played on two guitar strings is "actually identical" - depends on the weather, the phase of the moon, and whether you made the correct sacrifices to the harp-god ;) Of course if you want to treat the harp as a purely diatonic instrument and ignore the pedals, you can tune it to any temperament you like.
Comment: In Strauss's "Ein Heldenleben", one section of the harp part is written in C flat, while the rest of the orchestra score is in B. Strauss knew how to orchestrate to get the effect he wanted!
Answer: A simpler explanation is that the movement is in A♭ minor, and C♭ major is its relative major. Therefore its key signature is C♭.
From wikipedia page A-flat minor :

Its relative major is C♭ major.
Answer: An excellent question which I came across as I am just about to publish an edition of Evocación.
One of my first tasks was to see how it looked in B major; I cannot deny that it felt wrong. I found it quite difficult to find a valid reason and in the end opted to keep it in the original key.
It is always interesting to examine the choice of key and time signatures by composers, and although with equal temperament all keys should sound the same on a piano, it has to be said there is something sensual, dynamic and practical in preferring to compose in a particular key. Albeniz is a special case as in 10 of the 12 pieces of Iberia, he does not change key signature in spite of many complicated modulations, and this often presents a baffling number of awkward accidentals; these will always indicate either "exotic" deviations or a change of key, and in my view it is much clearer to change the key signature if the modulation lasts for more than a few bars. By 1915 In the study pour les arpèges Debussy changes key signature mid-bar.


Schlegel diagram and d-diagram

Question: Here I have the following definitions for Schlegel diagram and d-diagram.

I don't understand the last two examples at the end of the latter definition.
For this one,

how do we know that it's not a Schlegel diagram?
And for this one,

why isn't it a d-diagram?
Answer: From the first pic you'd deduce that the second pic ought be a triangle prism with diagonals drawn onto the squares, or at least some parallely truncated triangular pyramid with diagonals drawn on the tetragons. But surely such additional edges would ask to be inserted between 2 coplanar faces, which is not allowed for convex polyhedra.
The third pic cannot be a polyhedron either, as there would be 3 vertices (e.g. the bottom one of that pic), which would have just 2 incident faces.
--- rk
Comment: Thank you for the answer. I understand the reasoning for the second pic, but not the third one. By the definition, for a pic to be a d-diagram, the intersection of each polytope in the complex and the complex must be a face of the complex. I can't find any polytope that doesn't satisfy this requirement, yet the pic is not a d-diagram?

Schlegel diagram and d-diagram


Saída incorreta de dados na lista

Question: Olá, o método a seguir não está mostrando corretamente a saída dos dados. No final da execução ele mostra o nome do produto e em seguida a mensagem "CPF não cadastrado". Segue uma imagem para facilitar o entendimento.
<code>   public void consultarCompra(){

   System.out.println("INFORME SEU CPF: ");
    String cpf = entrada.next();

    for (int i = 0; i < dados.size(); i++) {
        if (dados.get(i).cpf.equals(cpf)) {
            System.out.println("O DONO DESTE CPF COMPROU: \n" + dados.get(i).nome);

    } else {
        System.out.println("CPF NÃO ENCONTRADO");

    }
}
</code>
}
Comment: Se tiver mais um item nessa lista que o CPF 123 não comprou, vai aparecer mais uma vez o "CPF NÃO ENCONTRADO". Agora pense...
Answer: Na maneira que você programou para cada item da lista que não tenha comprado algo você imprime "CPF NÃO ENCONTRADO".
O correto para isso seria o uso de uma solução chamada de flag, que consiste em criar uma variável com um valor false, e se acontecer uma "determinada coisa" dentro do FOR, muda para true para poder usar essa informação fora do laço de repetição.
Olhe a solução:
<code>public void consultarCompra(){

    boolean comprouAlgo = false;
    for (int i = 0; i < dados.size(); i++) {

        if (dados.get(i).equals(cpf)) {
            System.out.println("O DONO DESTE CPF COMPROU: \n" + dados.get(i));
            comprouAlgo = true;
        }
    }
    if (!comprouAlgo) {
        System.out.println("CPF NÃO ENCONTRADO");
    }
}
</code>

Saída incorreta de dados na lista


Analyzing traceroute

Question: I'm not a big network expert, but I'm having trouble accessing vmware.com and I'd like to try to further understand the issue. This is the traceroute I'm getting:
http://pastebin.com/MDaw5MRG
On the 17th hop it seems like the packet "almost" reached it's destination but then it gets lost. I know the site is up since I checked with a different ISP, now I'm just wondering if this is a good enough reason to ditch them (especially since they keep insisting they have no issues).
Answer: All the trace tells you is that those hosts don't respond to traceroute packets (ICMP). In some cases, depending on the problem, you could look at this and say "there's something wrong in the path from me to vmware", but in most cases it doesn't give you any solid evidence one way or the other. Many routers won't respond to ICMP traffic, due to the fact that responding to ICMP traffic diverts a router from it's intended job, which is to route "real" traffic as quickly and efficiently as possible. In addition, many web servers are configured to not respond to traceroute or ping traffic as well. I don't allow ping or traceroute traffic to any of my servers. I only allow ping and traceroute to one host on the perimeter of my network, as a basic diagnostic tool.
I ran a tracert to vmware.com and got the same results as you... because vmware.com and www.vmware.com resolve to different ip addresses in different net blocks... so your traceroute is not testing the right end point anyway. I can traceroute successfully to www.vmware.com.
Comment: If @Danny is using "traceroute" (e.g. on Linux or UNIX) it's more than likely using UDP packets by default, which will be dropped at VMWare's border. "tracert" on Windows uses ICMP by default, which appears to be allowed at VMWare's border. On Linux and OS X "traceroute www.vmware.com" fails but "traceroute -I www.vmware.com" works.
Comment: …which is why I usually a tracing tool that supports TCP probes such as "tcptraceroute" or "nmap --traceroute -p ". Also, nmap tends to provide faster results.
Answer: If traceroute (or tracert on Windows) doesn't show enough intersting results use the command mtr (or winmtr on Windows).
MTR stands for My TraceRoute, it will show you interesting results after running it for a good minute.
http://www.bitwizard.nl/mtr/ (packaged by most Linux distributions / FreeBSD / etc)
http://winmtr.sourceforge.net/
Answer: You might also want to try tcptraceroute.  It uses TCP packets instead of ICMP packets.

Analyzing traceroute