Maven not picking JAVA_HOME correctly

Question: I am on windows environment and using maven to compile my project. Although I just created the project and added the dependencies for various libararies.
As I added them maven started complaining for the missing tools.jar, so i added below to my pom.xml:
<dependency>
  <groupId>com.sun</groupId>
  <artifactId>tools</artifactId>
  <version>1.6</version>
  <scope>system</scope>
  <systemPath>${java.home}/../lib/tools.jar</systemPath>
</dependency>

When i ran the maven install, i got an error for the missing jar as below :
[ERROR] Failed to execute goal on project GApp: Could not resolve dependencies for project GApp:GApp:war:0.0.1-SNAPSHOT: Could not find artifact com.sun:tools:jar:1.6 at specified path C:\Program Files\Java\jre6\lib\tools.jar -> [Help 1]

The issue is that the tools.jar is in "C:\Program Files\Java\jdk1.6.0_26\lib" and is correctly set in the JAVA_HOME environment variable but the maven is still looking in jre folder as in error message "C:\Program Files\Java\jre6\lib\tools.jar".
C:\>echo %JAVA_HOME%
C:\Program Files\Java\jdk1.6.0_26

Interestingly: when i set the full path in dependency, it worked just fine. But i don't want to hard code it.
<dependency>
  <groupId>com.sun</groupId>
  <artifactId>tools</artifactId>
  <version>1.6</version>
  <scope>system</scope>
  <systemPath>C:\Program Files\Java\jdk1.6.0_26\lib\tools.jar</systemPath>
</dependency>

Can someone suggest any dynamic solution for this?
Comment: What's the value given for ${java.home}?
Comment: Are you running Maven from the command line or in an IDE like Eclipse or IntelliJ?
Comment: @metalmadz JAVA_HOME is environment variable
Comment: @cuberoot, i am running it from within the Eclipse
Comment: I have always avoided placing the JDK/JREs in directories containing spaces (cf. "Program Files") as that has been known to mess with Maven. Perhaps give that a try?
Answer: It's a bug in the Eclipse Maven support. Eclipse doesn't support all of the global Maven properties as per the Maven specs.
According to the specs:

${java.home} specifies the path to the current JRE_HOME environment
  use with relative paths to get for example

At least in Eclipse 4.3.1 that is not the case, here java.home always points to the JRE that was used to launch Eclipse, not the build JRE.
To fix the issue you need to start Eclipse using the JRE from the JDK by adding something like this to eclipse.ini (before -vmargs!):
-vm
C:/<your_path_to_jdk170>/jre/bin/server/jvm.dll

Comment: Five years after this answer this bug is still there (now is 2019-04-05).  I also want to note that be very careful with the path. 1) do not use double quotes around the string. 2) Use forward slash even in windows. 3) Use the jvm.dll 4) make sure you point to `jdk.../jre/...`.  5) as @Daniel Fernández has pointed out, need a line break after -vm (and not --vm!) For me the winning path is this `C:/Program Files/Java/jdk1.8.0_201/jre/bin/server/jvm.dll`
Comment: On a Mac/Linux the path would be smth like `//jre/bin/java`
Comment: Seems this issues still exists? The same error I got today, and your answer really helped. So, is this issues in existence, even after 4+ years? What exactly is this error?
Comment: Is there a link for the Eclipse Maven bug related to this?
Comment: What's the analog of `javaw.exe` in a Linux environment?  `jre/bin/` has a `java` and a `javaws`, but no `javaw`.
Comment: Works perfectly thanks. Garry, you could accept this ;)
Answer: You should NEVER use system scope dependencies. All the code in tools.jar will be available just via the running JVM already. You should remove this dependency altogether..
Also in order to check what runtime Maven is using just call
mvn -v

If you are still having a dependency to the tools jar as a problem, one of the dependencies you added has that dependency (and it is really bad quality). To find out which one it is run
mvn dependency:tree

or if that fails just remove one dependency after another until the problems is gone for the command above.
Then, when you know where it comes from you can decide what to do next. One path would be to use an exclusion on the dependency that pull tools in.
Comment: i know i should never use system scope dependencies but as i communicated in my question, when i don't mention the tools.jar in dependency maven starts complaining for missing artifact "com.sun:tools:jar:1.4.2".
Comment: Below is the output of mvn -v

C:\>mvn -v
Apache Maven 3.0.3 (r1075438; 2011-02-28 23:01:09+0530)
Maven home: C:\Custom Programs\apache-maven-3.0.3\bin\..
Java version: 1.6.0_26, vendor: Sun Microsystems Inc.
Java home: C:\Program Files\Java\jdk1.6.0_26\jre
Default locale: en_US, platform encoding: Cp1252
OS name: "windows xp", version: "5.1", arch: "x86", family: "windows"
Answer: It seems your JAVA_HOME is set to point to the JRE in eclipse.
Answer: Maven ${java.home} property is set and taken from different places depending your Eclipse execution:

from the default JRE selected for the workspace

Window>Preferences>Java>Installed JREs

from the specific Eclipse project,

Java Build Path>Libraries>JRE System Library

from the Run configuration.

Run Configurations> Specific Run Configuration > JRE

Remember your JRE home paths points to a JDK or JRE under JDK
Comment: This answer is still accurate 6 years later (for Eclipse 2020-09)! In my case, the run configuration setting was the faulty one.
Answer: When you add the JAVA_HOME environment variable, if there are spaces in the path you must wrap the whole thing in quotes.
Answer: You might be using the wrong Maven installation. Switch it in Window > Preferences > Maven > Installations. I had mine set to the Fedora Maven install; changing it back to the default (the version embedded in m2e) fixed the problem for me.
I suspect what was causing this issue is that the Fedora Maven install was using Fedora's OpenJDK, which probably puts tools.jar in a weird location (everything about Fedora's OpenJDK is weird and non-standard), so Maven can't find it.
Answer: Also look in the .mavenrc file in your home dir.
This caught me off guard.
I changed everything as suggested only to find that my .mavenrc file set the JAVA_HOME to an older version.
Answer: Sounds like you are running Maven in Eclipse. Eclipse does not consult JAVA_HOME.
Make sure you have set your JRE in Eclipse preferences to your desired JDK.
Answer: Check to see if you have a .mavenrc file, it may be forcing JAVA_HOME to be something other that what is set in the environment variable.
Answer: it's just a bug in maven support for eclipse. You can ignore this error for now.
The support for local dependencies will be discontinued in near future, I think the maven developers understand this approach is not the best way to resolve this, but we know that exists some proprietary jars (like db2's JDBC driver license) that never will resided in a public repository ...

Maven not picking JAVA_HOME correctly


Possible to have only zero eigenvalues of the Hessian of a harmonic function that is neither of the form $ax+by+cz+d$ nor a constant?

Question: (Following an earlier post here) I intuit that  if we restrict to functions $f(x,y,z)$ that are harmonic (i.e. satisfying $\nabla^2f=0)$ but neither of the form $ax+by+cz+d$ ($a,b,c,d\in\mathbb{R}$) nor a constant, all the three eigenvalues of the $3\times 3$ Hessian matrix
$$
H(x,y,z)=
\begin{bmatrix}
f_{xx} & f_{xy} & f_{xz}\\
f_{yx} & f_{yy} & f_{yz}\\
f_{zx} & f_{zy} & f_{zz}\\
\end{bmatrix},
$$
cannot all be zero. Of course, I don't have a proof. But does anyone have any counterexample?
Comment: The Hessian is symmetric, if all the eigenvalues are zero, then the Hessian is the zero matrix, which implies that the gradient is constant, which implies that $f$ is an affine function.
Comment: That is true. Examples are $f=$constant and linear $f$. Any other example possible?
Comment: Any affine function, like $f(x,y,z) = x+5$.
Comment: Of course. I included that into my definition of linear. So my intuition is right?
Comment: Do not call affine functions linear.
Comment: Okay. Let me edit the question a bit
Comment: My argument above only shows that we cannot have that all the eigenvalues of the Hessian are zero for all $(x,y,z)$. It does not rule out the possibility that this happens at some points.
Comment: @SeverinSchraven Do you have any such example i.e. not affine yet Hessian has all zero eigenvalues at least at one point?
Comment: I do not know any such example. I am just saying that you want to specify what you are interested in.
Comment: I am interested in showing that the solutions to Laplace's equation in 3D, $\nabla^2f=0$, do not tolerate any local maximum or minimum. I know that this can be proved using the mean value property of the harmonic functions. But I want to prove it using the knowledge of Hessians. It turns out that for a Harmonic function, $f$, due to Laplace's equation, the trace of the Hessian ${\rm Tr}(H)=0$. Therefore, either all eigenvalues of zero or they have mixed signs. If they have mixed signs, then it follows that $f$ cannot have a local maximum or minimum.
Comment: On the other hand, when all eigenvalues are zero, the Hessian test fails. Now, if all eigenvalues are zero, the function is affine. Affine functions also do not have any local maximum or minimum. Right? So have I proved that Laplace equation do not have any local maximum or minimum?
Answer: The answer depends on the precise formulation of the question.
The Hessian vanishes everywhere: In this case the function must be (locally) affine. Indeed, if the Hessian vanishes, then we have for every $j\in \{1,2,3\}$ that $$\nabla (\partial_j f)(x,y,z)=((\partial_1 \partial_j f)(x,y, z), (\partial_2 \partial_j f)(x,y,z), (\partial_3 \partial_j f)(x,y,z))=(0,0,0).$$ This means that $\partial_j f$ is (locally) constant. This implies that $f$ is (locally) affine.
Hessian is only vanishing at certain points: The function $f(x,y,z) = xyz$ is a counterexample to the claim "if $f$ is harmonic and the Hessian vanishes at least in one point, then $f$ must be an affine function". It is harmonic, we even have $\partial_j^2 f \equiv 0$ for all $j\in \{1,2,3\}$. However, we have
$$ Hf(x,y,z) = \begin{pmatrix} 0 & z & y \\ z & 0 & x \\ y &x & 0 \end{pmatrix}. $$
Thus, we get that $Hf(0,0,0)$ is the zero matrix.
Note that we also have $\nabla f(0,0,0)=(0,0,0)$ (it is also a critical point). Thus, if you are trying to show that harmonic function do not have local extrema, then you need to find a way to deal with the second case too.
Comment: I seem to have got it now. For a harmonic function, $Tr(H)=0$ at all points. This leads to three possible cases. All the eigenvalues are zero at all points, the eigenvalues have mixed signs at all points, and the last case, all eigenvalues are zero at some points and mixed signs at other points. Your function belongs to the last case. I erroneously missed the last. I think that harmonic together with the condition that all eigenvalues of the hessian are zero at all points implies affine function.
Comment: But all three eigenvalues ate zero here. So this is not a counterexample.
Comment: @Solidification What do you mean? You are asking whether Hessian being the zero matrix at some point implies that the function must be affine... and the answer is no.
Comment: Otherwise you need to elaborate on what you are looking for.
Comment: Have you read the comment "I am interested... " and the comment following that? Should I make it part of the question to make the context clearer? I can do that.
Comment: @Solidification I have read it now and it is simply not true. My answer gives an example of a harmonic function which has a point where the Hessian vanishes (i.e. all eigenvalues are zero), but the function is not affine. In fact, it is even worse, the function I give above also has a critical point there. So your approach simply does not work. I do not understand what you are expecting more from an answer to your question.
Comment: @Solidification Yes, that is correct.
Comment: @Solidification That is exactly what Severin proved in his very first comment.  If this was your question all along, I suggest Severin replace their answer with their comment, and you accept it once you are happy with it.


proof that $g\left(\boldsymbol{x}\right)=-\prod_{i=1}^{n}x_{i}^{p_{i}},p_{i}\geq0,\sum_{i}p_{i}=1$ is convex given $p_{i}\geq0,\sum_{i}p_{i}=1$

Question: I want to proof   that for the function:
Let $g\left(\boldsymbol{x}\right):\mathbb{R}_{++}^{n}\longrightarrow\mathbb{R}$ be
$g\left(\boldsymbol{x}\right)=-\prod_{i=1}^{n}x_{i}^{p_{i}}$ and $\sum_{i=1}^{n}p_{i}=1,\forall i\in\left\{ 1,\ldots,n\right\} :p_{i}\geq0$
proof that $g\left(\boldsymbol{x}\right)$ is convex function for all $\boldsymbol{x}\in\mathbb{R}_{++}^{n}$.
what I tried so far:

tried to look for a transformation that preserve convexity (like log ... etc) , but $g\left(\boldsymbol{x}\right)$ is negative for all $\boldsymbol{x}\in\mathbb{R}_{++}^{n}$. so log is not a valid transformation .
tried to understand how can I use Jensen's inequality with another convex function f : $$f\left(\sum_{i=1}^{N}\lambda_{i}x_{i}\right)\leq\sum_{i=1}^{N}\lambda_{i}f\left(x_{i}\right)\\\sum_{i=1}^{N}\lambda_{i}=1\\\lambda_{1},\ldots,\lambda_{N}\geq0$$
tried to use First-order characterization: $$\forall\boldsymbol{x},\boldsymbol{y}\in\text{dom}\left(f\right):f\left(\boldsymbol{y}\right)\geq f\left(\boldsymbol{x}\right)+\nabla f\left(\boldsymbol{x}\right)^{T}\left(\boldsymbol{y}-\boldsymbol{x}\right)\text{ and }\text{dom}\left(f\right)\text{\,is convex}\iff f\text{\,is convex}$$ but without any meaningful results..
tried to understand how can I use second-order characterization as well but with no success.

Thanks :D
Answer: $$
\frac{\partial g}{\partial x_j\partial x_k}(x)=\cases{-\frac{p_jp_k}{x_jx_k}\prod_\limits{i=1}^nx_i^{p_i}& if $\ j\ne k$\\
-\frac{p_j\left(p_j-1\right)}{x_j^2}\prod_\limits{i=1}^nx_i^{p_i}& if $\ j=k$}\ .
$$
Therefore
\begin{align}
\sum_{j=1}^n \sum_{k=1}^ny_jy_k \frac{\partial g}{\partial x_j\partial x_k}(x)=\\
-&\left(\left(\sum_{j=1}^n \frac{p_jy_j}{x_j}\right)^2-\sum _{j=1}^n \frac{p_jy_j^2}{x_j^2}\right) \prod_\limits{i=1}^nx_i^{p_i}\ .
\end{align}
By the Cauchy-Schwarz inequality,
\begin{align}
\left(\sum_{j=1}^n \frac{p_jy_j}{x_j}\right)^2
&= \left(\sum_{j=1}^n \sqrt{p_j}\frac{\sqrt{p_j} y_j}{x_j}\right)^2\\
&\le \left(\sum_{j=1}^n p_j\right)\left(\sum_{j=1}^n \frac{p_jy_j^2}{x_j^2}\right)\\
&= \sum_{j=1}^n \frac{p_jy_j^2}{x_j^2}\ ,
\end{align}
from which it follows that $\ \displaystyle \sum_{j=1}^n \sum_{k=1}^ny_jy_k \frac{\partial g}{\partial x_j\partial x_k}(x)\ge0\ $ for all $\ x\in\mathbb{R}_{++}^n\ $ and all $\ y\in\mathbb{R}^n\ $. That is, the Hessian of $\ g(x)\ $ is non-negative semidefinite for all $\ x\in\mathbb{R}_{++}^n\ $, from which it follows that $\ g\ $ is convex on $\ \mathbb{R}_{++}^n\ $.
Answer: Remind that $-g$ is Cobb-Douglas function. The prove is that way:
First, $g$ is convex iff $-g$ is concave. So you can take $ln(g)=\sum_i p_i ln(x_i)$, which is clearly concave, thus quasi-concave.
Second, the increasing transformation of quasi-concave function is quasi-concave. So take $e^{ln(g)}=g$ gives quasi-concavity of $g$. Besides, it is easy to verify that g is homogenous of degree 1.
Last, it is not hard to show that a function is quasi-concave and homogenous of degree 1 is concave so g is concave.


Proving convergence of a sequence with a given property

Question: Let $$a_{n + 1} = \begin{cases} a_{n} + 1/n &  \text{ if }  a_{n}^{2} \leq 2 \\
a_{n} - 1/n & \text{ if } a_{n}^{2} > 2
\end{cases}$$
Show that for every index $n$, $\left|a_{n} - \sqrt{2}\right| < 2/n$, and use this property to show that the sequence converges to $\sqrt{2}$.
So, I did the first part of this problem by proving by induction. The base case is obvious, and then for the induction step I just split it into two cases, one for each condition. But, now I'm having trouble using this sequence converges to $\sqrt{2}$ using the property that I established.
I'm pretty sure that I need to do an $\epsilon-N$ verification, since this is a real analysis book, in the convergence section. I'm really not sure how I would go about it, though.
Comment: Can you show $\frac{2}{n} \to 0$ using $\varepsilon$-$N$? Exactly the same $N$ will work for $a_n \to \sqrt{2}$, using the first part of the question.
Comment: Okay, I have proved that $2/n \rightarrow 0$, but I'm not sure how the result follows.
Comment: Well, you have $n \ge N \implies \frac{2}{n} < \varepsilon$, right? Well then, using the same $N$ for the given $\varepsilon$, we also have $$n \ge N \implies |a_n - \sqrt{2}| < \frac{2}{n} < \varepsilon,$$ using part (a). So, in total, you've found an $N$ such that $n \ge N \implies |a_n - \sqrt{2}| < \varepsilon$.
Answer: Hint: $2/n\to 0$ when $n\to\infty$.

 For $\epsilon>0$, choose $n_0\in\mathbb N$ such that $2/n_0<\epsilon$. Then we have, for $n>n_0$,
 $$|a_n-\sqrt{2}|\le 2/n < 2/n_0 < \epsilon$$


A relation between permanents and determinants

Question: I have skimmed this video that I found on mathoverflow:
http://tube.sfu-kras.ru/video/407?playlist=397
At about 15:05 the lecturer wrote down an equality
$\sum F(m_1, \ldots, m_m)z^{m_1}\ldots z^{m_m} = \frac{1}{det(zI - A)}$, where F is given in terms of coefficients of the $m$-by-$m$ matrix $A$. The definition of $F$ doesn't yet make much sense to me, but that's beyond the point.
My question is, how is this equality possible? the right hand side obviously has poles—the eigenvalues of $A$, but the left hand side is just a polinomial, it can't have poles! Is there something I'm missing?
EDIT: well, it was actually
$\sum F(m_1, \ldots, m_m) z_1^{m_1}\ldots z_m^{m_m} = \frac{1}{det(z - A)}$.
Here I have abused the notation slightly: the z means actually the diagonalization of the corresponding vector. However, when you take $z_1 = \ldots = z_m$, the question still stands.
The domain is real, as I understand from the context of the lecture :), so the use of the term pole isn't really correct, I just forgot the right word in English :)
Comment: Take 1×1 matrices maybe. Sum(z^n,n=0…∞) = 1/(1-z).
Comment: Cool, it's Doron Zeilberger! If you had written that instead of just "the lecturer", this question would immediately have become more interesting. ;)
Comment: The LHS is not a polynomial; it's a power series.
Comment: And the formula is, as mentioned in the video, MacMahon's Master Theorem: http://en.wikipedia.org/wiki/MacMahon_Master_theorem. The summation runs over all nonnegative integer vectors, but it appears that Zeilberger made a little mistake; it should be det(I-ZA), not det(Z-A). (Otherwise it doesn't even work for Z=0.)
Comment: Err... how? Can power series have singularities?
Comment: @Jack, thanks for the example :)
Comment: Over what integers does the sum run? Does it allow negative integers?
Comment: I have no idea. Probably for all $m_i$ from $1$ to $\infty$ for the Jack Schmidt's example to hold.
Answer: From the comment by @HansLundmark above.

The formula is MacMahon's Master Theorem, as mentioned in the video. The summation runs over all non-negative integer vectors, but it appears that Zeilberger made a little mistake; it should be $\det(I-ZA)$, not $\det(Z-A)$. Otherwise, it doesn't even work for $Z=0$.


Desenvolver testes de integração corretamente

Question: Estamos escrevendo diversos testes para a aplicação, há testes unitários e começamos testes de integração.  Toda a comunicação com o DAO é mockada, porém quando eu testo a API eu devo testar novamente os casos que já foram testados no service?
Por exemplo:
API
@RequestMapping(value = "", method = RequestMethod.POST)
    public Validacao create() {
        Validacao validacao = new Validacao()
                .setDataAtualizacao(DateTime.nowISODate())
                .setDataCriacao(DateTime.nowISODate())
                .setEmail(activeUser.getUser().getEmail())
                .setInstancia(activeUser.getInstancia().getInstancia());

        validacaoService.create(validacao);

        return validacao;
    }

Service
public Validacao create(Validacao validacao) {
        validacao = validacaoDAO.save(validacao);
        if (validacao == null) {
            throw new InternalServerErrorException("Ocorreu um erro ao criar a validação.");
        }
        return validacao;
    }

No teste unitário do Service, já há um caso de teste caso a validação seja nula. Esse teste deve se repetir novamente no teste de integração? Não é uma redundância?
Há casos em que o meu Service utiliza outro Service, isso deve ser mockado ou crio uma nova instância?
Comment: O intuito dos testes de integração é, como o nome indica, testar como os vários componentes/camadas funcionam(integram) em conjunto. Por isso não devem incidir nas questões particulares de cada componente/camada, questões essas que devem ser testadas através de testes unitários .
Answer: Não se preocupe com redundância. Testes de integração são pra testar como os vários componentes do seu sistema trabalham em conjunto.
Principalmente casos de falha. Na realidade os testes são o lugar perfeito pra ver o que acontece se estourar uma exceção três ou mais camadas abaixo do serviço sendo testado.
Persistência e acesso a serviços externos (SOAP, REST, JMS, etc) podem ser mockados, mas eu prefiro usar o quanto eu puder dos serviços reais em testes de integração.
Finalmente, cuidado com os academicismos. Faça o que funciona pro seu projeto, sem medo de quebrar as regras.
PS.: Se isso for um trabalho pra sua faculdade, se professor vai falar que eu estou errado e te dar uma nota baixa.
Comment: Realmente mas me preocupo principalmente se tiver boas práticas (já que não é minha área), é perigoso criar testes mal feitos e depois prejudicar a manutenção e o próprio resultado do teste
Comment: Mais perigoso é não ter teste nenhum.
Comment: E que história é essa de "não é minha área"? Você desenvolve, você escreve testes... Esse lance de pegar uma pessoa, ou uma área, e dedicar fazer testes exclusivamente é coisa de quem acha que software se faz em linha de montagem.

Escrever testes deve fazer parte da sua rotina como desenvolvedor, você não tem que depender de outras pessoas pra testar seu código. Não precisa ser um fanático do TDD, mas escrever testes te facilita a vida.

QA deve ser uma responsabilidade da equipe como um todo.
Answer:
Quando eu testo a API eu devo testar novamente os casos que já foram testados no service?

Não, não deve.
O problema não é a redundância no sentido de o mesmo código ser executado por testes em diferentes níveis. Os problemas são:

Você está explicitamente testando a mesma regra duas vezes.

Você está testando em uma camada do sistema as regras de outra camada.

Veja, lançar exceção no caso de não poder salvar a Validação é uma regra do "service", então está correto você testar esta regra ao testar este service. Mas você não deveria testar esta regra na camada acima ("API") pois esta não é uma regra desta camada.
Mesmo que a gente simplifique e troque o termo "camadas" por "objetos", no seu teste você está verificando em um objeto uma regra que é responsabilidade de outro objeto, e é por isso que você ficou com essa sensação estranha de estar testando duas vezes a mesma coisa.
A sua API não está fazendo muita coisa, é difícil decidir o que testar ali. Nestes casos, geralmente, eu não testaria nada. Se não sei o que testar, por que vou escrever um teste?
Se, por outro lado, o projeto exige 100% de cobertura de testes, você pode testar se a API retorna um objeto Validação com as propriedades preenchidas conforme o esperado, assim você cobriria as linhas desta API sem testar algo que não seja a responsabilidade dela e manteria os 100% de cobertura.
Outras notas sobre o seu código - Exceções
Em ValidacaoDAO.save() você está retornando null como código de erro. Null é um código de erro ruim.

Se um método não conseguiu fazer o seu trabalho (não conseguiu realizar o que o seu nome sugere) ele deve ou lançar uma exceção ou retornar um código de erro (caso a sua decisão de design seja trabalhar com códigos de erro em vez de exceções).

A semântica de null é "valor desconhecido" ou "não encontrado" ou "inexistente", e isso por si só não sugere um erro (eventualmente o consumidor pode decidir que isso é um erro dado o contexto).
Pode ser útil retornar null em um método find, por exemplo, indicando que o que era procurado não foi encontrado; e então o código consumidor decide o que fazer, por exemplo não fazendo nada ou lançando uma exceção caso aquilo que era procurado devesse, no determinado contexto, estar lá.
De qualquer modo, não me parece que você esteja interessada em códigos de erro, uma vez que você está de fato lançando uma exceção ao detectar um null. Neste caso, em vez de retornar null, o método ValidacaoDAO.save() deveria ele próprio lançar a exceção se não conseguir fazer o seu trabalho. Ou ainda, ele não deveria explicitamente lançar exceção nenhuma mas apenas deixar propagar uma exceção que porventura venha a impedí-lo de realizar o seu trabalho.
Conclusão
Fatalmente, ao testar uma camada superior, as regras das camadas inferiores entrarão em ação. Mas um teste deve explicitamente verificar apenas as regras da camada ou objeto que ele está testando, e não deve verificar as regras específicas das camadas abaixo que em tese ele não conhece. Exemplo:
API:
void facaAlgo() {
    if (condicaoRuim_X) {
        throw new ExceptionA("As condições estavam desfavoráveis na API");
    }
    Service.facaAlgo();
}

Service:
void facaAlgo() {
    if (condicaoRuim_Y) {
        throw new ExceptionB("As condições estavam desfavoráveis no Service");
    }
}

Agora, ao testar o "service", eu verifico a exceção ExceptionB e ao testar a API eu verifico a ExceptionA.
Se não existisse nenhuma lógica na API, então eu poderia:

ou não testar este método da API;
ou testar apenas o caso feliz, validando os resultados no caso de tudo der certo, ignorando as regras específicas das camadas abaixo.

Quanto a mocks, use o mínimo possível. Eles dão muito trabalho e podem tornar a nossa vida infeliz, que é inverso do objetivo dos testes automatizados. Veja nestas respostas um pouco mais sobre mocks e outros "dublês":

Qual a diferença entre mock & stub?
Teste unitário / Mock de uma consulta JPA
Comment: Ótima resposta! Testar já é algo bem tedioso e ainda ter de usar mocks todo o tempo. Uma observação do DAO, foi definido que sua função é apenas a comunicação com o banco, toda e qualquer parte lógica é responsabilidade do Service
Comment: @DanielaMarquesdeMorais Havia um tempo que eu escrevia os testes como sendo a cereja do bolo, o toque final para entregar um trabalho completo. Eu ainda acho que os testes de código são essenciais para entregar um trabalho completo, mas não acho mais que sejam a cereja do bolo - ao contrário, são a base dele. Assim como você, eu acho um tédio ter que escrever testes depois do código pronto - então eu faço diferente, escrevo os testes antes :-) Recomendo dar uma estudada em TDD (leia o livro do Kent Beck, eu acho que você vai gostar).


Passing lot of parameters into Web Service

Question: I have a web service in ASP.NET a simple one but the web method takes 5 parameters. Is there any other way to pass the parameters? like array or list?. I would like to limit it to 3.
I tried SetMethod(string param) and dint work.
Thanks.
Comment: Huh? Your question makes no sense.
Answer: Why don't you create a Class that has those parameters as it's properties, then you would pass an instance of the class as a parameter to the web method.
Changing something like this..
<code>[WebMethod]
public void SomeMethod(string param1, string param2, string param3)
{
    //some code
}
</code>
to something like this...
<code>[WebMethod]
public void SomeMethod(SomeClass myClass)
{
    //some code
}

public class SomeClass
{
    public string Param1 { get; set; }
    public string Param2 { get; set; }
    public string Param3 { get; set; }
}
</code>
and you would use it like so...
<code>SomeClass myClass = new SomeClass();
myClass.Param1 = "some data";
myClass.Param2 = "more data";
myClass.Param3 = "even more";

// make the webservice call
someObject.SomeMethod(myClass);
</code>
Answer: <code>    List<Student> list = new List<Student>();
    [WebMethod]
    public string InsertUserDetails(Student  userInfo)
    {
        list.Add(userInfo);
        //string Message;
        SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Sample;Integrated Security=True");
        con.Open();
        foreach (Student s in list)
        {
            SqlCommand cmd = new SqlCommand("insert into userdetail(username,password,country,email) values(@UserName,@Password,@Country,@Email)", con);
            cmd.Parameters.AddWithValue("@UserName", userInfo.UserName);
            cmd.Parameters.AddWithValue("@Password", userInfo.Password);
            cmd.Parameters.AddWithValue("@Country", userInfo.Country);
            cmd.Parameters.AddWithValue("@Email", userInfo.Email);

            int result = cmd.ExecuteNonQuery();
        }

            //if (result == 1)
            //{
            //    Message = userInfo.UserName + " Details inserted successfully";
            //}
            //else
            //{
            //    Message = userInfo.UserName + " Details not inserted successfully";
            //}
            //con.Close();

           // return Message;
        return "done";

    }
</code>
you can do like this>>>>>>>>>>>>>
Comment: I think you are answering some other question. The OP is asking about [tag:web-services] and you are answering about [tag:sql].
Comment: Please provide a little more description about your solution


Let G be a regular graph. Prove that every bridge of G is in every perfect matching of G.

Question: Struggling with a proof for the following:
Let G be a regular graph. Prove that every bridge of G is in every perfect matching of G.
I have ran into this whilst doing some revision work on graph theory.
Can anyone point me in the right direction. I am considering a proof by contradiction though I am unsure how to continue from there.
Comment: Welcome to MSE. Your question is phrased as an isolated problem, without any further information or context. This does not match [many users' quality standards](http://goo.gl/mLWc8), so it may attract downvotes, or closed. To prevent that, please [edit] the question. [This](http://goo.gl/PlJyVQ) will help you recognise and resolve the issues. Concretely: please provide context, and include your work and thoughts on the problem. These changes can help in formulating more appropriate answers.
Comment: Thank you for your welcome.

I've provided my thoughts on the question and have titled it as the question itself, which is what the quality standards suggest.

It has tags relating to the context of the question, and I even provided where I think would be a good point to start.

I'm unsure what you're alluding to with my question not following the users' quality standards.
Answer: Hints.
If the graph is not regular, it is not true.
Take a simple path with four vertices $1,2,3,4$
and three edges $12$, $23$, $34$.
The $23$ edge is a bridge and the $12$, $34$ edges form a  perfect matching.
Let $G$ be a regular graph of degree $d$ and $e=uv$ be a bridge.
Let a perfect matching does not contain edge $e$.
Then graph $G-e$ has two components $G_1$ and $G_2$ ($u\in V(G_1)$ and $v\in V(G_2)$) and
the number of vertices of each component is even. (why?)
On the other hand, by the handshaking lemma we have for the graph $G_1$
$$
2|E(G_1)|=\sum_{x\in V(G_1)}\operatorname{deg}(x)=d(|V(G_1)|-1)+(d-1)=d|V(G_1)|-1.\ (\rm why?)
$$
Contradiction.
Comment: I'm unsure as to why the number of vertices is even in the components and how this leads to a contradiction. I apologise for my unfamiliarity but if you could please provide some further hints as I would love to learn how this is so.
Comment: Why is the number of vertices in each component even?
Our perfect matching has no edges connecting vertices $G_1$ and $G_2$. So each of its edges lies in $G_1$ or $G_2$. That is, $G_1$ (and $G_2$) has a perfect matching. I hope you understand that a graph with perfect matching has even number of vertices.
Comment: Ah I see! Yes, I understand why a perfect matching has an even number of vertices. This makes a lot sense. Appreciate the help!


Error: Path must be a string. Received undefined / codorva add platform android

Question: quando vou gerar no codorva a plataforma android, ele começa a instalar os plugins, mas no whitelist ele ocorre o seguinte erro?
<code>    Installing "cordova-plugin-whitelist" for android

 This plugin is only applicable for versions of cordova-android greater than 4.0. If you have a previous platform version, you do *not* need this plugin since the whitelist will be built in.

    **Error: Path must be a string. Received undefined.**
</code>
Por que isto acontece? Como posso sanar?
Comment: Você precisa atualizar o *Cordova* para versão *4.0* ou para uma versão superior a ela.
Comment: C:\projetos\primeiro>cordova platform version android
Installed platforms:

Available platforms:
  android ~6.3.0
  blackberry10 ~3.8.0 (deprecated)
  browser ~5.0.0
  ios ~4.5.1
  osx ~4.0.1
  ubuntu ~4.3.4 (deprecated)
  webos ~3.7.0
  windows ~5.0.0
  www ^3.12.0

C:\projetos\primeiro>cordova -v
7.1.0
Comment: esta na versao 7.1.0.
e o codorva-android 6.3.0
Comment: Para qual versão do *Android* você está utilizando esse plugin?
Comment:
Comment: percebi que meu erro está em algum path aqui, estou olhando e não achei erros nas variaveis de ambiente.
Comment: Esta utilizando algum *Framework* ?? *Ionic* ?
Comment: não, nenhum plugin a mais só exportei do intel xdk, fiz o que tinha que fazer, mas agora não compila
Comment: @Morvy poderia colocar aqui onde você achou esse path que você conseguiu corrigir o problema?
Answer: Bom, arrumei uma solução. Quanto aos erros ocorridos por causa da versão e tal, este não tem problema, ainda sim é gerado, o que travava todos o processo era este erro:
<code>Error: Path must be a string. Received undefined.
</code>
achei um path aleatório, da qual nem tinha me tocado o por que estava ali, ou para que servia. Simplesmente removi e ele compilou perfeitamente, agora vamos testar para ver se gera o app e rode, obrigado.


Testing Ipad Touch Events in Windows

Question: I have a website that I would like to be iPad compatible. However, I use Windows, so I can't install the official emulator.
I tried iBBDemo2 (http://code.google.com/p/ibbdemo2/) which looks good, but it uses regular mouse events instead of the touch events (so I can double click with my mouse and fire a dblclick event on an element... which in this case would just cause a zoom to occur on a real iPad)
Is there any way at all to test this?
Answer: Have you tried Ripple emulator? It is a very useful chrome extension. It has accelerometer support and other features.
The link is here.
I don't know if really solves your problem, but you can try it for free.

Testing Ipad Touch Events in Windows


How to resolve standradError In ROR-4

Question: Can any body find out the solution for this error ?I am following this  Link and tring to make one app.First i typed command
"rails generate paperclip user avatar".when i ran command rake db:migrate,it gave this error.
Error:
StandardError: An error has occurred, this and all later migrations canceled:

SQLite3::SQLException: no such table: users: ALTER TABLE "users" ADD "avatar_fil
e_name" varchar(255)c:/Site/attachment1/db/migrate/20141220045244_add_attachment
_avatar_to_users.rb:4:in `block in up'
c:/Site/attachment1/db/migrate/20141220045244_add_attachment_avatar_to_users.rb:
3:in `up'
C:in `migrate'
Tasks: TOP => db:migrate
(See full trace by running task with --trace)

my 20141220045244_add_attachment_avatar_to_users.rb file contains
class AddAttachmentAvatarToUsers < ActiveRecord::Migration
  def self.up
    change_table :users do |t|
      t.attachment :avatar
    end
  end

  def self.down
    remove_attachment :users, :avatar
  end
end

Please help to resolve this error.
Comment: Does your app have a Users model/table?
Comment: `no such table: users`
Comment: Loading the rake db:schema:load corrected the issue.
Comment: check: 1> if there exists a table user 2> are you using correct database in database.yml
Comment: @subhra : You should have user model to add avatar for user. please check your model or post your schema file.
Answer: Your problem is there is no 'users' table.
SQLite3::SQLException: no such table: users

How to resolve standradError In ROR-4


Notation for a unison double stop

Question: What's the standard notation for the occurrence of the same pitch played on two different strings of the same instrument simultaneously, to be used within the same staff?
The typical context would be a double stop lick that needs to resolve in unison, perhaps on the tonic.  The reason for playing the same note on two strings rather than one might be uniform volume across the lick or just the special quality of the sound.  It might be quite inconvenient to split the entire double stop lick into two separate staves just to avoid the local issue of notation.
I understand that I could just write "On D and G" above a G note (if using English), but I wonder whether there's any established culture neutral notation as an alternative to that.  I don't care whether the individual strings are notated explicitly, or just the "doublestopness".
Comment: Related:  my question [Meaning of notation in violin part](https://music.stackexchange.com/questions/93506/meaning-of-notation-in-violin-part), where I (not a string player) got confused about the notation for a unison double-stop.
Answer: I would agree with @user1079505 about using two noteheads.
Elaine Gould, 2011, Behind Bars, p.397:
p.398:

p.399:
Comment: This is the notation style used in the Barenreiter edition of the Bach Suites FWIW.
Comment: @CarlWitthoft totally relevant, Barenreiter extremely well respected, very clean scores!
Answer: For notes with a stem one way would be for the note to have a double stem, one pointing up and one down.
For a whole note (no stem) this isn't possible so the next best way is to indicate the fingering with "0" above and "4" below the note indicating that the note should be played with both the 4th finger and open string.
Here is an example showing both used at the same time for the half note at the end of the third bar -
Comment: @user1079505:  Apparently a double stem and a single note-head is also used sometimes;  see [this question I once asked.](https://music.stackexchange.com/questions/93506/meaning-of-notation-in-violin-part)
Comment: You'd need not only two stems but also two note heads. Then it's fine also for a whole note. I'm not sure what is the convention for violins, but this is a general way to notate two different _voices_ played in unison.
Comment: @MichaelSeifert You're right! One head is OK, *except* for the whole note. And I guess a single note head _could_ be OK for a whole note, if the meaning would be obvious, but apparently we're dealing situation when it's not.
Answer: The question's been answered but the same convention of note stems going in different directions is also used when the notes to be played with the same pitch on different strings aren't played as a double stop but are instead played sequentially. Here's an example from the last page of Bach's Chaconne in D minor:

(James Ehnes plays this passage here)
and here's an example from the first page of the prelude from Bach's partita in E major for solo violin

with Midori playing it here.

Notation for a unison double stop


Cannot create an instance of because Type.ContainsGenericParameters is true

Question:
I am creating an instance dynamically using reflection.
var typesTR = Assembly.GetAssembly(typeof(BGenericConfigurationClass<>)).GetTypes()
            .Where(type =>
                    !string.IsNullOrEmpty(type.Namespace) &&
                    (type.Namespace == "EntitiesConfiguration"))
            .Where(type => type.BaseType != null
                           && type.BaseType.IsGenericType
                           &&
                           (type.BaseType.GetGenericTypeDefinition() == typeof(BGenericConfigurationClass<>) ||
                            type.BaseType.GetGenericTypeDefinition() == typeof(CGenericConfigurationClass<>) ));

foreach (var type in typesTR)
{

    dynamic configurationInstance = Activator.CreateInstance(type);
    modelBuilder.Configurations.Add(configurationInstance);
}

and my exception is following :-
"Cannot create an instance of CGenericConfigurationClass`1[T] because Type.ContainsGenericParameters is true."

Comment: *Give me...* Linguistically that's imperative, or "commanding". Doesn't work well at Stack Overflow where everybody volunteers in helping others. One of these volunteers correctly explained to you that you need `type.MakeGenericType` -- to which you didn't give any substantial response. Again, I suspect you're trying to reinvent the wheel that EF [already provides](https://stackoverflow.com/a/24222663/861716) but you don't respond to that either.
Comment: The image isn't helpful at all. Please remove it and show code instead. Also, note that EF has a built-in function to discover `EntityTypeConfiguration` classes in an assembly.
Comment: i want to use multi-level inheritance using EntityTypeConfiguration class of ef. Give me any idea or any solution.
Comment: sorry if you feel of my wrong word selection but i told exact point English is your mother language but i converted every sentence before writing..  i am not commanding i deeply appreciate  you replying and share my problem solution, thanks sir or brother take any word that you like. i feel guilty and shame rising of behavior mistake... please share skype or email address i share whole project.
Comment: No hard feelings, just explaining how SO works. But I'm also asking to respond to suggestions given so far.
Comment: @GertArnold I disagree with that, I'd say the image shows what the OP's mind is doing, which is what we're working with as answerers.  Keep the image!  It represents the OP's perception of the problem.
Comment: @ranalaiqueahmed were you able to find a fix for the solution
Answer: It looks like one of the types in typesTR is a generic type and you are attempting to create an instance of that type without specifying the generic type parameters. As an example, this is as if you were attempting to create an instance of List<>  but without providing the type between the angle brackets <>. This is not possible, Activator.CreateInstance() must be given a "closed generic type".
To do this, you could do something like the following, but based on your example, I don't think this will be very useful since you need to create numerous configuration instances and you may not know what generic type to pass in.
var t = type.MakeGenericType(typeof(SomeClassToBeUsedAsGenericTypeParameter));
dynamic configurationInstance = Activator.CreateInstance(t);
...

My guess is that typesTR has more types in it than you were expecting and includes one of the base classes which is generic. I think it should only include DClass and EClass, but is including one of the base classes.
Comment: sir i want to use multi-level inheritance using EntityTypeConfiguration class of entity framework. the above picture show main scenario  Give me any idea or any solution
Answer: In my case, which of course is different, but also has some similarities with the problem raised in the question, I managed to make part of my Entity mappings in EF generic by using the following code
 protected override void OnModelCreating(ModelBuilder builder)
 {
     RegisterMaps(builder);
     base.OnModelCreating(builder);
 }

 private static void RegisterMaps(ModelBuilder builder)
 {
     var mapLists = Assembly.GetExecutingAssembly().GetTypes()
            .Where(type => !string.IsNullOrWhiteSpace(type.Namespace)
                && typeof(IEntityMap).IsAssignableFrom(type)
                && type.IsGenericType == false
                && type.IsClass).ToList();

     foreach (var item in mapLists)
     {
         Activator.CreateInstance(item, BindingFlags.Public |
         BindingFlags.Instance, null, new object[] { builder }, null);
     }
}


Matlab function with array input problem

Question: My question is simple but I just don't understand. I just wanted to plot Scorer function which is $$Hi(x)=\int_0^\infty{\exp(xt-\frac{t^3}{3})}dt.$$
First I tried to write, for example, x=0:0.1:1.
Then I write
y =  1/(pi)*integral(@(s) exp(x*s -(s^3)/3),0,inf).
It shows error using * and inner matrix dimensions must agree.
I also tried .* and .^ but the error then becomes only, matrix dimensions must agree.
I know my question seems stupid but I am just starting to learn matlab. What is the problem and what should be the correct steps of plotting this function? Thank you!
Comment: did you try .*? as well as .^ ?
Comment: Use elementwise arithmetic operations (.* and .^) to apply the same function to all elements of a vector at once. Without the dot, it interprets * as dot product and ^ as matrix powers.
Comment: Actually, I tried using the dots before * and ^ but also failed.
Comment: When I use .* and .^, the error becomes, matrix dimensions must agree.
Comment: I got confused, which is the variable? I mean the integration variable? s or x? If s, then why there is a vector for x?
Comment: This is a function of x. So the integration variable is s. I just want to input a vector and that's the main problem.
Answer: You need to loop through the different x inputs.For instance, the following will do what you are looking for:
$\texttt{x=0:0.1:1;}$
$\texttt{y=zeros(size(x));}$
$\texttt{for k=1:length(x)}$
$\quad \texttt{y(k)=1/pi*integral(@(s) exp(x(k)*s-s.^3/3),0,Inf);}$
$\texttt{end}$
Comment: Thank you very much. It solves the problem and it works!


How to use app.selection[0] for scripts in Adobe InDesign

Question: I would like to run code by testing only the current selection (not the whole document) and I'm having difficulty understanding exactly how the array "app.selection" and its methods work.  To start, I use a "for" loop to cycle through each item selected by using:
for(loop = 0; loop < app.selection.length; loop++){
    var sel = loop;
}

This works okay, but when I want to get into determining what each item IS, it gets a little weird.  For example,
for(txt = 0; txt < app.selection[sel].textFrames.length; txt++){
    // do something to each text frame in the selection here.
}

does not work as expected, but
for(img = 0; img < app.selection[sel].allGraphics.length; img++){
    // do something to each graphic in the selection here
}

seems to work fine, regardless if the selection includes more than just graphics alone, or whether it is inside or outside a group.
At times, it seems like app.selection[0] is the only way to access the item by itself.  In other words, if a text frame is selected, app.selection[0] might be the same as app.document.textFrames[0], in which case it would be redundant (and incorrect) to say
app.document.textFrames[0].textFrames[0]

And yet the same concept on different page items works like a charm.  It is quite puzzling to follow.  Furthermore, it seems impossible to determine what kind of object the item is.  I want to say something along the lines of:
if (app.selection[0] == [object TextFrame])

but that does not seem to work for me.  Is there a way to clearly test if the current item is a group, a graphic or a text frame and do different things depending on the result?
Answer: app.selection returns an array of Objects, so each item in the array can be of a different type, and the properties and methods available to it will differ. When using the Extendscript Javascript Console you can see what a particular item in the array is on the fly by just typing
app.selection[0]

(or whatever number). The result will be something like [object TextFrame].
While looping through the selection array, you could use app.selection[0].constructor.name to determine the type of each. Or, if you're only interested in certain types,
if (app.selection[i] instanceof TextFrame){}

At that point you'll know more about which properties you can access, depending on the type.
To answer the second part of the question, there isn't an allTextFrames property, but there is an allPageItems property. This returns an array of pageItems (textFrames, groups, etc.), and you can work with it similarly to app.selection. So, if I have three text frames grouped on the first page of my document (and nothing else), I can see that the following are all true:
app.activeDocument.pages[0].textFrames.length == 0;
app.activeDocument.pages[0].allPageItems.length == 4;
app.activeDocument.pages[0].allPageItems[0] instanceof Group;
app.activeDocument.pages[0].allPageItems[1].constructor.name == "TextFrame";

So you could probably cycle through that array if it's more useful to you than the textFrames collection. Just keep in mind that you don't have access to the special collection properties of TextFrames (like everyItem()).
Comment: There isn't an allTextFrames property, at least not in any of the versions of ID that I've worked with (5.5 through CC). There is an allPageItems property. I'll add a note about it.
Comment: Excellent response!  I have another question regarding all text frames.  To update the situation in my question where app.selection.allGraphics[0] acted okay and app.selection.textFrames[0] misbehaved, it seems that it was not a matter of misunderstanding the selection array, (although your answer cleared up the questions I had about it.) allGraphics finds every last graphic available, while textFrames fetches the outermost text frames in a group.  Is there an equivalent to allTextFrames?
Comment: Great!  Thanks!  I've now got a working version thanks to allPageItems.
Answer: App.selection is indeed an array which every item can be accessed by its index:
var sel = app.selection //May be null on no open documents ! An empty array on no selection with an open document. One to n length array in case of selection.
then given that you selected one or several items, you can reach those objects by its index
sel[0] //This returns the first item of the array. Javascript starts counting at zero.
Once that said if you access, say sel[4] and selection count less than 5 items or column 5 is empty, then you get an undefined value. So you need to carefully check for selection item validity before using it and never presume it will return something.
HTH,
Loic
http://www.ozalto.com


Test for image in Codeception acceptance test

Question: I'm setting up a load of automated testing for our in house CMS.
At this moment in time, I want to be able to test that our test page has certain images in it.
I can check for the caption which will be displayed if the image exists...
$I->see('Image Caption');

...but I really want to actually be able to check for the presence of the image itself...
$I->seeImage('/path_to/image_file.jpg'); // I MADE THAT METHOD UP

...or at least the img tag...
$I->seeSourceCode('<img src="/path_to/image_file.jpg"'); // I MADE THAT METHOD UP TOO

Does anyone know how to do this?
Comment: What exactly do you mean by the image "caption"? That is what I'm trying to do..
Comment: It was just a bit of text that I was using to check that the image had probably loaded, because I couldn't work out how to check the actual image had loaded. I think the solution below worked for me at the time, but to be honest, we're not using Codeception any more so I have probably forgotten everything about it by now!
Comment: In WordPress, images have "captions" which are just text meta data blurbs. They can be found just with $I->"see"
Answer: seeElement() may fit your need, for instance:
$I->seeElement('//img[@src="/pixel.jpg"]');
please do see doc
 and, in order to make test more readable, I'd recommend to wrap the actual call to seeElement() in helper and in test have something like this
$I->seeImageWithSource('/pixel.jpg')
public function seeImageWithSource($image_url)
{
    $phpBrowser = $this->getModule('PhpBrowser');
    $phpBrowser->seeElement('//img[@src="'.$image_url.'"]');
}

Comment: You should invoke `seeElement` method from PhpBrowser module instance, i.e.
    `public function seeImageWithSource($image_url)
    {
        $phpBrowser = $this->getModule('PhpBrowser');
        $phpBrowser->seeElement('//img[@src="'.$image_url.'"]');
    }`
Comment: Thanks for this. This one works out of the box...

`$this->seeElement('//img[@src="'.$image_url.'"]');`

But I agree about wrapping it, so I add this in WebHelper

    `public function seeImageWithSource($image_url)
    {
        $this->seeElement('//img[@src="'.$image_url.'"]');
    }`

Ran the build command and tried...

`$I->seeImageWithSource($image_url);`

but got Call to undefined method Codeception\Module\WebHelper::seeElement().

What amd I doing wrong?


Does the Fourier inversion theorem hold if $f$ is square-integrable?

Question: I know that for $f$ an integrable function, it's Fourier transform may not be integrable, so the inversion theorem does not necessarily hold.
Assume $f$ is square-integrable instead. Does this imply that the inversion theorem holds, i.e. we can recover $f$ by integrating its Fourier transform? If not, what further assumptions are required?
I am getting different information from different notes online. Some say above is enough, others say that we need some continuity properties, and yet others say that the inversion theorem does not hold pointwise but only in $L^2$ sense?
Comment: The Placherel Theorem gives the truth of the matter here.
Answer: Here's the story. For $f\in L^1(\Bbb R)$ let $\hat f$ be the usual Fourier transform:
$\newcommand\ft{\frac1{\sqrt{2\pi}}}$
$$\hat f(\xi)=\ft\int e^{-i\xi t}f(t)\,dt.$$
One can state the Inversion Theorem like so:

Inversion Theorem. If $f,\hat f\in L^1$ then $\hat{\hat f}(x)=f(-x)$.

Now for $f\in L^2$ and $A>0$ define $$F_A(f)=\ft\int_{-A}^Ae^{-i\xi t}f(t)\,dt.$$
The main theorem is

Plancherel  Theorem There exists an isometric isomorphism $F:L^2\to L^2$ such that $\lim_{A\to\infty}\|Ff-F_Af\|_2=0$ for $f\in L^2$; $F$ is almost its own inverse: $FFf(x)=f(-x)$.

Note that if $f\in L^2\cap L^1$ then it's easy to see that $Ff=\hat f$;  this is why $F$ is also called the Fourier transform.
So in particular $F_Af\to Ff$ in norm, not almost everywhere. No. In  fact

Theorem (Carleson) If $f\in L^2$ then $F_Af\to Ff$ almost everywhere.

Proof: Very very hard. A huge big deal in Fourier analysis.

Corollary. If $f\in L^2$ then $Ff\in L^2$ and $F_AFf(x)\to f(-x)$ almost everywhere.

It's not clear to me exactly what it means to say the inversion theorem holds almost everywhere, but it seems pretty likely that the corollary answers your question.
Comment: @Hugocito I may have misinterpreted the question "does the inversion theorem hold almost everywhere" - after all, that's not very precisely formulated, a theorem is true or false, not true almost everywhere.  Trying to make sense of the question, i took it to be asking whether the Corollary was true. Carleson's theorem is not "overkill" for the Corollary, Carleson't  theorem is trivially equivalent to the corollary.
Comment: Using Carleson's theorem is kind of overkill, don't you think?
Comment: @Hugocito Huh? There's some question whether "pointwise" means the same to me as to the OP. With my version of "pointwise", Carleson's theorem **is** the answer to the question!
Comment: @Hugocito How do you show $F_AFf(x)\to f(-x)$ almost everywhere without using Carleson's theorem? Btw if you can give an easy proof of this you're going to be famous, because Carleson's theorem is a simple consequence.
Comment: There are two ways of proving it. In both cases you define separately the Fourier transform $\mathcal F$ and the inverse Fourier transform $\mathcal F^{-1}$.
1) Using distribuitions: $\mathcal F \mathcal F^{-1} u = u$ holds for tempered distributions, because it holds for the Schwartz spaces. Now, since both sides of the identity are in $L^2 \subset L_{loc}^1$, the identity also holds in $L_{loc}^1$ as consequence of Lebesgue differentiation theorem. So, the identity of functions $\mathcal F \mathcal F^{-1} u = u$ holds almolst everywhere.
Comment: 2) You can extend the Fourier transform from from Schwartz space $\mathcal S$ to L^2 by density. You have the maps $\mathcal F$ and $\mathcal F^{-1}$ defined on $\mathcal S$ and you extend both maps to isometries in $L^2$. Now, the identity $\mathcal F \mathcal F^{-1} u = u$ holds for functions in $\mathcal S$, and therefore, by density, it holds in $L^2$. In particular, we have $\mathcal F \mathcal F^{-1} u = u$ almolst everywhere.
Comment: @Hugocito I didn't ask how to show $\mathcal F\mathcal F^{-1}f=f$ almost everywhere. How do you show $\lim_{A\to\infty}F_AFf(x)=f(-x)$ without Carleson's theorem?
Comment: Sorry, I don't see why Carleson's theorem is related to the post. What is your point?
Comment: I see. So I think we were just addressing to different interpretations of the question. Thank you for your answer, I didn't know Carleson's theorem also holds for $L^2(\mathbb R^n)$. I just knew it for Fourier series. I understood he was asking if  $\mathcal F \mathcal F^{-1} u = u$ holds almost everywhere for $u\in L^2(\mathbb R^n)$.
Answer: The Fourier transform is always defined, but you have to work with tempered distributions. In what follows I will use the following definition of Fourier transform $$\mathcal F(\phi)(\xi) := \int_{\mathbb R^n}\phi(x)\exp(-2\pi i x \xi)dx$$ for $\phi \in L^1(\mathbb R^n)$.
The Fourier transform is also defined for the space $\mathcal S'(\mathbb R^n)$ of tempered distributions, and it is indeed a isomorphism. The Fourier transform in this case is given by
$$\langle \mathcal F(u),\phi\rangle:= \langle u, \mathcal F(\phi) \rangle,$$
for $\phi \in \mathcal S(\mathbb R^n)$, the Schwartz space of $\mathbb R^n$.
The space $L^2(\mathbb R^n)$ is contained in $\mathcal S'(\mathbb R^n)$, and restricting the Fourier Transform to it we obtain the isomorphism:
$$\mathcal F:  L^2(\mathbb R^n) \to L^2(\mathbb R^n).
$$
Furthermore, this isomorphism is an isometry, that is,
$$\Vert \mathcal F(\phi) \Vert = \Vert \mathcal \phi \Vert.$$
This identity is called Placherel theorem.
For a more detailed discussion about this I recommend you to take a look at Folland's book Real Analysis, and at the Fourier Analysis: An Introduction, by Stein and Shakarchi .
Comment: There's no need for tempered distributions to give the story for $L^2$.
Comment: Yes, I know you don't need tempered distributions to prove the extension to $L^2$. In Folland's book he does the extension using elementary functional analysis and density arguments. Nevertheless, it's much more natural to use distributions here.
Answer: Your last sentence is correct: the inversion theorem does not hold pointwise but only almost everywhere, which means that you recover the same function in $L^2$ sense (remember that two functions are considered equal in $L^2$ sense if they only differ an a null set). If you want it to hold everywhere you need some continuity properties. Thus all sources are probably correct; they just differ in what they mean with equality.
Comment: No, it does hold almost everywhere! That's a hugely deep theorem of Carleson.
Comment: @DavidC.Ullrich. That's what I wrote.
Comment: If by pointwise we mean at every point, as opposed to almost everywhere, then yes. But "pointwise" often means almost everywhere,  as opposed to just in norm. It's clear from the last sentence of the question that that's what "pointwise" meant in the question, and in that sense the inversion theorem _does_ hold pointwise.
Comment: @DavidC.Ullrich. I don't think that I've ever seen "pointwise" mean "almost everywhere". And doesn't convergence in $L^2$ norm imply convergence almost everywhere? I can easily find examples that the opposite implication isn't true, but not for this direction.
Comment: What? Cnvergence in $L^2$ norm certainly does not imply almost everywhere convergence. Describing the example is a little complicated - you can find it in any text on measure theory.
Comment: Regarding ' I don't think that I've ever seen "pointwise" mean "almost everywhere"': That's perfectly consistent with what I said - I didn't assert that _you_  had ever _seen_  this usage...
Comment: @DavidC.Ullrich. I found an example: https://math.stackexchange.com/a/138054/168433


Como fazer para o menu não ser atropelado pelo scroller do iPhone?

Question: No navegador do Safari / ou chrome na versão mobile iPhone, aparece uma barra de rolamento em cima do menu, existe uma maneira de resolver isso quando for iPhone?
SCSS:
@mixin getSideRadius($side:'normal', $radius:0) {
     @if ($side != 'normal') {
        border-#{$side}-radius:$radius;
        -webkit-border-#{$side}-radius:$radius;
        -moz-border-#{$side}-radius:$radius;
        -ms-border-#{$side}-radius:$radius;
     } @else {
        border-radius:$radius;
        -webkit-border-radius:$radius;
        -moz-border-radius:$radius;
        -ms-border-radius:$radius;
     }
  }

@mixin getMenu() {
  $black5: #595a5c;
  $black4: #86878b;
  $black2: #dee1e6;
  $black1: #f3f6fd;
  $black_bg: #f9fbff;
  $id_green: #96dd48;
  $size_mobile:768px;
  $white:#fff;
  $spacing_12:12px;
  $size_mobile_small:480px;
  $size_mobile_medium:580px;
  $size_desktop_small:800px;

    //MENU PRINCIPAL
    .menu-dropdown-base {
        position: fixed;
        bottom: 0;
        background: $white;
        height: 48px;
        display: flex;
        left: 0;
        right: 0;
        width: 100%;
        z-index: 23;
        justify-content:center;
        align-items: center;
        margin: 0 auto;
        border-top: 1px solid $black2;
    }

    .menu-dropdown-base ul.nav-menu-principal  {
        display: flex;
        -webkit-display: flex;
        flex-direction: row;
        flex-wrap: wrap;
        display: flex;
       justify-content: space-around;
    }
    .menu-dropdown-base ul.nav-menu-principal li {
        margin: 5px 0.51px;
        padding: 0 4.2px;
        text-align: center;
    }

   .menu-dropdown-base ul.nav-menu-principal li {
        margin: 0 4px;
        padding: 0 4px;
        text-align: center;
   }
   @media(min-width:400px) {
        .menu-dropdown-base ul.nav-menu-principal li {
            margin: 0 2vw;
            padding: 0 4px;
            text-align: center;
        }
    }

    @media(min-width:440px) {
        .menu-dropdown-base ul.nav-menu-principal li {
            margin: 0 4vw;
            padding: 0 4px;
            text-align: center;
        }
    }

     .menu-dropdown-base ul.nav-menu-principal li a {
         display: block;
         padding: 2px;
         width: 100%;
     }
    .menu-dropdown-base ul.nav-menu-principal li a > span {
        font-weight: 600;
        color: $black5;
        font-size: 10px;
        line-height: 12.8px;
        display: flex;
        padding-top: 2px;
    }

    .menu-dropdown-base ul.nav-menu-principal li.active a span,
    .menu-dropdown-base ul.nav-menu-principal li.active a i {
        color: $id_green;
    }
    .menu-dropdown-base ul.nav-menu-principal li a i {
        font-size: 17px;
        color: $black5;
        padding: 1px;
    }
    .menu-dropdown-base ul.nav-menu-principal {
        display:flex;
        flex-wrap: wrap;
    }
    .menu-dropdown-base ul.nav-menu-principal li.menu-notificacoes,
    .menu-dropdown-base ul.nav-menu-principal li.menu-mais,
    .menu-dropdown-base ul.nav-menu-principal li.menu-explorar {
        display: flex;
        position: relative;
    }
    .menu-account-user ul.drop-user-menu li.message-item-menu  > a,
    .menu-dropdown-base ul.nav-menu-principal li.menu-producao-textual,
    .menu-dropdown-base ul.nav-menu-principal li.menu-painel-educador,
    .menu-dropdown-base ul.nav-menu-principal li.menu-favoritos,
    .menu-dropdown-base ul.nav-menu-principal li.menu-tarefas {
        display: none;
    }

    .footer-content .menu-footer ul {
        display: flex;
    }
    .footer-content .menu-footer ul li {
       margin: 0 10px;
    }
    .footer-content .footer-menu-position {
        display: flex;
        flex-direction: row-reverse;
    }
    .footer-content .menu-footer ul li > a {
        display: inline-flex;
        border: 1px $black2 solid;
        @include getSideRadius('normal', 10px);
        padding: $spacing_12;
        color: $black4;
        font-size: 16px;
        line-height: 16px;
        &:hover {
            background: $black_bg;
        }
    }

    @media(min-width:$size_mobile_small) {
        .menu-dropdown-base ul.nav-menu-principal li {
        margin: 0 4.5vw;
        padding: 0 4px;
        text-align: center;
        }
    }

    @media(min-width:$size_mobile_medium) {
        .menu-dropdown-base ul.nav-menu-principal li {
        margin: 0 5vw;
        padding: 0 4px;
        text-align: center;
        }
    }

    @media(min-width:600px) {
        .menu-dropdown-base ul.nav-menu-principal li {
        margin: 0 5vw;
        padding: 0 4px;
        text-align: center;
        }
    }

   @media(min-width: $size_mobile) {
    .menu-dropdown-base ul.nav-menu-principal {
        margin-left: 16px;
    }
    .menu-dropdown-base ul.nav-menu-principal li {
        margin: 0;
        padding: 0;
        text-align: center;
    }

   }

   @media(max-width: $size_desktop_small) and (min-width:$size_mobile) {
        .menu-dropdown-base ul.nav-menu-principal li {
            margin: -1.1vw;
            padding: 0 10px;
            text-align: center;
        }
    }

    @media(min-width:$size_mobile) {
        //saindo do mobile...
        .menu-dropdown-base ul.nav-menu-principal li a:hover  {
            background: $black1;
        }

        .menu-dropdown-base ul.nav-menu-principal li.active a span,
        .menu-dropdown-base ul.nav-menu-principal li.active a i {
            color: $id_green;
        }

        .menu-dropdown-base ul.nav-menu-principal li a {
            @include getSideRadius('normal', 10px);
            padding: 10px 15px;
        }

        .menu-dropdown-base {
            border-top: none;
            bottom: inherit;
            top: 60px;
            border-bottom: 1px solid $black2;
            justify-content:left;
            z-index: 11;
        }
        .menu-dropdown-base ul.nav-menu-principal li a {
            display: flex
        }
        .menu-dropdown-base ul.nav-menu-principal li a span {
            font-size: 12.8px;
            line-height: 12.8px;
            margin-left: 8px;
            margin-top: 2px;
        }
        .menu-dropdown-base ul.nav-menu-principal li.menu-notificacoes,
        .menu-dropdown-base ul.nav-menu-principal li.menu-mais,
        .menu-dropdown-base ul.nav-menu-principal li.menu-explorar {
            display: none;
        }
        .menu-account-user ul.drop-user-menu li.message-item-menu  > a,
        .menu-dropdown-base ul.nav-menu-principal li.menu-producao-textual,
        .menu-dropdown-base ul.nav-menu-principal li.menu-painel-educador,
        .menu-dropdown-base ul.nav-menu-principal li.menu-favoritos,
        .menu-dropdown-base ul.nav-menu-principal li.menu-tarefas {
            display: flex;
        }
    }
}
@include getMenu();

HTML do menu:

Início

Favoritos

Tarefas

Produções

Conquistas

Explorar

Notificações

Mais</a

Painel do Educador

Exemplo básico no codePen, só está sem os ícones, porque não precisa para isso... O que quero saber é se existe alguma forma de ajustar se for só no IPhone... eu sei que existe uma forma de identificar o notch, mas desconheço para reconhecer iphone.

Estou procurando uma solução que pode ser em CSS ou em Javascript.
Answer: Acho que encontrei a solução:
:root {
  --ion-safe-area-top: 20px;
  --ion-safe-area-bottom: 22px;
}

https://github.com/ionic-team/ionic-framework/issues/19060


Definite integral of function is zero

Question: I am attempting to solve an equation wherein $\int_{-\infty}^\infty f(x) \, dx = 0$. There obviously exist some some solutions, such as $f(x) = xe^{-x^2}$ and trivially $f(x) = 0$, but is there a general pattern apart from the function being odd? $\sin(x)$ obviously does not work, even though it's an odd function.
Comment: Well, for example you can take an odd function $f(x)$ and consider $f(x+1)$.
Answer: Given any function on the positive real line $f(x)$ such that $I_1 = \int_0^{\infty} f(x) dx \in \mathbb{R}$, and any other function on the negative real line $g(x)$ such that $J_1 = \int_{-\infty}^0 g(x) dx \in \mathbb{R}$ and $J_1 \neq 0$, define
$$h(x) = \begin{cases}
f(x) & \text{ if }x > 0\\
-\dfrac{I_1}{J_1} g(x) & \text{ if }x<0\\
h_0 & \text{ if }x=0
\end{cases}$$
The function $h(x)$ has the desired property.
Answer: The only "pattern" is that the integral of $f$ where $f$ is positive must equal in absolute value the integral of $f$ where $f$ is negative.
Answer: The condition $\int_{-\infty}^\infty f(x)\>dx=0$ is, apart from convergence issues, a very weak condition on $f$.
Fix a function $u_0$ with $u_0(x)\geq0$ for all $x\in{\mathbb R}$ and $\int_{-\infty}^\infty u_0(x)\>dx=1$, e.g., $u_0:=$ the standard normal distribution.
Let $g:\>{\mathbb R}\to{\mathbb R}$ be any function with $\int_{-\infty}^\infty \bigl|g(x)\bigr|\>dx<\infty$. Then the number $\alpha:=\int_{-\infty}^\infty g(x)\>dx$ is well defined, and the function
$$f(x):=g(x)-\alpha u_0(x)$$
satisfies the condition $\int_{-\infty}^\infty f(x)\>dx=0$.

Definite integral of function is zero


How to install certain modules only for specific site using Acquia Desktop

Question: I am using Acquia Desktop for creating multisites.
Problem is whenever I am installing a module it gets replicated in everyother site.
What i need to know is that if i want to have a module only for specific site do i need to first manually create a modules folder inside the site folder such as practice.localhost\modules (where practice.localhost is the site name) folder as the modules directory is not created by default for any of the subsite folder.? Is my approach correct
Moreover I have also heard that if we create modules for specific sites then we are going to find it difficult to export sites to FTP for making the site go online.?
Answer:
do i need to first manually create a modules folder inside the site folder such as practice.localhost\modules (where practice.localhost is the site name) folder as the modules directory is not created by default for any of the subsite folder.?

Yes, you need to create a specific modules folder for the specific site(s) you wish that module to be available for. If you want it available on, say, 10 out of 20 sites, you'll need a copy in each site's modules folder. You can remove the need for this by making it available in sites/default/modules, but obviously it will be available to all sites in the multisite.

are going to find it difficult to export sites to FTP for making the site go online.?

Completely depends on your deployment process. You'll probably want to review that process before implementing this on your live servers, but whether or not it's 'difficult' depends on what you need to do.


QTP - Checking dynamic pages

Question:

I'm trying to check if a value is contained in the innertext of a webelement but I'm having a little problem: frames seem to change at every refresh of the pages.
These are the steps I've recorded:
    Browser("SystemPage").Page("SystemP").Frame("dme2_header").Image("Gestione Anagrafiche").Click

    Browser("SystemPage").Page("SystemP").Frame("dme2_appl").WebEdit("pdrBean.pdrPod").Set parameter("POD")

    Browser("SystemPage").Page("SystemP").Frame("dme2_appl").WebButton("Cerca").Click
    Browser("SystemPage").Page("SystemP").Frame("dme2_appl_2").Image("show_files").Click
    Browser("SystemPage").Page("SystemP").Frame("dme2_appl_6").Image("Lente").Click

    cctype = Browser("SystemPage").Page("SystemP").Frame("dme2_appl_7").WebElement("arrow_down").GetROProperty("innertext")

    DataAct = Browser("SystemPage").Page("SystemP").Frame("dme2_appl_7").WebElement("arrow_down_2").GetROProperty("innertext")

    Browser("SystemPage").Page("SystemP").Frame("dme2_header").Image("Gestione Anagrafiche").Click

The frames "dme2_appl6" and "dme2_appl7" changes at every refresh of the two pages.
The question is simple: how can I rewrite these two actions to make them universal?
I've tried to do something like:
    Set objFrame = Frame("title:=dme2_appl_.")

and then
    Browser("SystemPage").Page("SystemP").objFrame.Image("Lente").Click

But QTP gives me an error in return: "property or method not supported by the object"
Answer: Please try using the below code
Browser("SystemPage").Page("SystemP").Image("Lente").Click

Avoid using the "Frame" and if you really want to use it, put regex for name property of Frame.
Go to Object Properties--> Click on the Frame object --> Mandatory Properties--> Change name property as
like iFrame_213123123 to i.*
Hope this will solve your problem.
Answer: I don't think you can use a frame object that way. When you write Page().Frame() UFT sets the frame's parent in different way than if you first create the Frame.
Think of Frame() as a function that behaves differently when called on a Page or as a free function.
Try:
 Browser("SystemPage").Page("SystemP").Frame("title:=dme2_appl_.")

Comment: Tried that too but QTP says that the frame is not in the object repository... :S
Comment: @LeonGuerrero, are you sure that you used the descriptive programming syntax (`:=`)  ?
Comment: The blank betwen the "." and the "Frame" should be removed
Comment: @TheBlastOne, It works either way but I agree it's more aesthetic this way.
Comment: Didn't know it works with the blank, too, so nevermind.

QTP - Checking dynamic pages


Difference between calling a service method in drupal 8

Question: I want to know what difference does it make when i call a service this way :
<code>$service = \Drupal::service('myservice.method');
$service->methodNameInService();
</code>
or this way (Dependency Injecton)
<code> public function __construct(MyService $myService) {
+    $this->myService = $myService;
   }

public function test() {
    // Call function from service
    $this->myService->methodNameInService();

}
</code>
Is this better for performance or is it just only the right way and has it zero effect on performance or something else?
Comment: From the class level you should use dependency injection and not the static service container. From procedural code, the static service is the only option you have.
Comment: Also, strive to type hint interfaces instead of concrete classes when possible.
Answer: Dependency Injection has several advantages when you try to create test for your code, and follow the Single Responsibility Principle.
Really, the second reason is a consequence than the first: "The code is testeable because follow the SRP"
Furthermore, IDEs can recognize better the class type (and create autocompletes, f.e.) if the class is defined using DI. In a normal IDE, $service defined in <code>$service = \Drupal::service('myservice.method');</code> has a unknown class.
In some places you cannot use DI (fe. in a .module) and you need to use the static load.


Why is maximum number of orthogonal contrasts equal to the number of groups minus one and what does mutually orthogonal mean?

Question:
I was wondering why, for $g$ groups, it is always possible to
construct $g - 1$ mutually orthogonal contrasts and $g - 1$ is the maximum number?
A counterexample I have is that for two groups with means $\mu_1$
and $\mu_2$,  $g=2$, and $\mu_1$ and $\mu_2$ themselves are two
orthogonal contrasts.
The definition of orthogonal contrasts I have learned is a set of
contrasts in which, for any distinct pair, the sum of the
cross-products of the coefficients is zero. So it is a pairwise
concept. What does "mutually orthogonal contrasts" mean, and is it
not defined pairwise?

Thanks!
Comment: In the presence of an *intercept*, you can only have $g-1$. If you exclude the intercept, you can have $g$.
Comment: What happens when you add the indicators for the two $\mu$-contrast you mentioned?
Comment: @Glen_b: Thanks! I don't understand. can you be more specific?
Answer:
What are contrasts? Contrasts are linear combinations of treatment group means $\mu_i$ used to assess for specific differences between groups in an ANOVA (omnibus test) with a positive result. These linear combinations are of the form: $\Lambda = \sum_{i}c_i\mu_i$ with the condition $\sum_{i}c_i=0$. In these equations, $c_i$ represent the contrasts coefficients. Of note, these are scalar measures. Since we deal with a sample, the estimator of $\Lambda$ uses the group (or treatment) mean, $\bar{y}$. So a contrast between groups will be of the form $\hat\Lambda_j = \sum_{i}c_{ji}\bar{y}_i$. The index i referring to the groups involved in the contrast j. These contrasts are then tested using an F-test statistic.
What are mutually orthogonal contrasts? They are contrasts that satisfy $\sum_{i}\frac{c_{ji}c_{ki}}{n_i}=0$ with $j$ and $k$ indicating the contrasts indices, and $i$ the observation or subject ($n_i$ being the number of subjects in a group, out of a total of $r$ groups). Expressed in matrix form the crossproduct of the contrast matrix will have zeros in all off-diagonal entries.

Here is a made-up example contrasting the number of bacterial colonies grown (independent variable) in multiple observations for groups exposed to different antibiotics (penicillin ('pnc'), cloramphenicol ('cloram'), metronidazole ('metro'), or simply soap, or nothing ('control')).
The contrasts allowed will enable four (r - 1) reasonable questions to be answered, including: "Are antibiotics better at suppressing bacterial growth than soap (or nothing)?" (contrast 1: C1 <- c(2,-3,2,2,-3)); "Is penicillin superior to other antibiotics?" (contrast 2: C2 <- c(2,0,-1,-1,0)); "Does cloramphenicol differ from metronidazole?" (contrast 3: C3 <- c(0,0,1,-1,0)); and, "Is soap different than the control group?" (contrast 4: C4 <- c(0,1,0,0,-1)). Notice that all contrast coefficients add to zero.
   pnc soap cloram metro control
1   15   41     25    10      41
2   12   40     23    12      38
3   ...

The contrast matrix will be:
contrastmatrix
     C1 C2 C3 C4
[1,]  2  2  0  0
[2,] -3  0  0  1
[3,]  2 -1  1  0
[4,]  2 -1 -1  0
[5,] -3  0  0 -1

And the crossproduct confirm zeros on all off-diagonal entries:
crossprod(contrastmatrix)
   C1 C2 C3 C4
C1 30  0  0  0
C2  0  6  0  0
C3  0  0  2  0
C4  0  0  0  2

Why maximum number of orthogonal contrasts equals $r-1$? Geometrically, this follows from the fact that the sum square of the treatment groups $\sum_{i} n_i (\bar{y}_i - \bar{y})^2$ of the initial ANOVA can be expressed as a function of the matrix $W$ here, and the estimate of the orthogonal contrasts are proportional to scalar multiplications of the $r-1$ eigenvectors of $W$ corresponding to $\text{eigenvalues}= 1$. The last of the $r$ eigenvalues being $0$ because the trace of $Tr(W) = r-1$, and there are $r$ total eigenvalues (aside: the sum of eigenvalues equals the trace). Being that $W$ is a symmetrical and real matrix the eigenvectors associated with these  eigenvectors to $\text{e-values} = 1$ will form an orthogonal set. Also they will all be orthogonal to the eigenvector corresponding to $\text{e-value}=0$. So the contrasts will correspond to linear combinations of the orthogonal basis of the $r-1$ dimensional space perpendicular to the evector to $\text{e-value} =0$, explaining the $r-1$ max rule.

Reference: Harry M. Schey. A Geometric Description of Ortogonal Contrasts in One-Way Analysis of Variance. The American Statistician, May  1985.


Select com 3 condiçoes e uma delas dependente de uma quarta condição

Question: Estou populando um gráfico e para isso preciso selecionar os dados de cada usuário no banco, tabela financeiro. Todavia não quero mostrar registros do campo label_chart que estejam vazios, nem campos qdade_stream com valor zero, exceto se o campo label_chart = inicio (nesse caso o campo qdade_stream pode ter valor zero).
SELECT * FROM financeiro WHERE id_usuario = 150 AND label_chart !='' AND (qdade_stream != 0 AND label_chart <>'inicio')
ORDER BY order_chart";

Da maneira que estou fazendo, a query não retorna a linha cujo label_chart=inicio, porque como o seu valor é igual a zero, a query só obedece à condição de apenas retornar qdade_stream != 0
Answer: A lógica da sua query está quase certa, só se confundiu um pouco nos operadores que vai usar. Como tem duas condições que fazer ser possível exibir resultado o ideal vai ser usar o OR, então ficaria:
SELECT *
FROM financeiro
WHERE id_usuario = 150
  AND ((label_chart != '' AND qdade_stream != 0) OR label_chart = 'inicio')
ORDER BY order_chart;

Dessa forma ele pega os registros com id_registro = 150 e com label_chart e qdade_strem diferentes de vazio ou zero OU apenas com label_chart igual à inicio sem levar em conta a qdade_stream.
Comment: Testei esse código, mas parece haver algum erro, pois nao retornou nada, o gráfico nem sequer se formou.
Comment: Não sei qual implementação do SQL você ta usando (MySQL, SQL server, ...) então não sei se pode ser problema usar o `!=` ao invés do `<>`, talvez valha a pena testar isso. Se não for isso fica dificil saber o que pode estar ocorrendo sem saber como estão seus dados.
Comment: Estou usando MySQL. Tenho 4 gráficos, só essa query que não consigo retornar o que eu preciso, como explicado no meu enunciado. Também não consigo saber o que está ocorrendo. E não entendi o que você precisa saber sobre os dados do banco, pois é uma tabela normal.


Mongoose - no '_id' property in retrieved documents

Question: I have a website written with Meteor and external nodejs server that works with meteor's mongo. I create new documents in collection tradeOffers on Meteor side and poll for new documents in this collection on external server (I use mongoose). Everything works fine except that mongoose returns documents without the '_id' property.
My code is something like this:
// Meteor
var TradeOffers = new Mongo.Collection('tradeOffers');
TradeOffers.insert({ ... });

// Mongoose
var tradeOfferSchema = new mongoose.Schema({ ... }, { collection: 'tradeOffers' });
var TradeOffer = mongoose.model('TradeOffer', tradeOfferSchema);
TradeOffer.find({}).exec(function(err, results) {
  results.forEach(function(tradeOffer) {
    console.log(tradeOffer._id); // undefined
  });
});

I noticed that documents created in Meteor have '_id' field of type 'String' and documents created with mongoose have '_id' of type 'ObjectId'. But even if that's the problem, how do I solve it? I could not find any information. Thank you in advance.
Comment: You answered it yourself `_id` is an `ObjectId` wich can't be logged like this you would need to parse it to as a String `console.log(tradeOffer._id.toString());`. Also see [this question](http://stackoverflow.com/questions/13104690/nodejs-mongodb-object-id-to-string)
Comment: @DerTieran already tried that. It says `'Cannot read property 'toString' of undefined'.`
Comment: @DerTieran if you see from a `console.log`, the thing you're trying to log either has its `toString` to return `"undefined"` or it is the said string, or it is really is `undefined` (the most likely result).
Comment: @starky have you tried to log the whole Object so `console.log(tradeOffer)` so you can see if `_id` is defined?
Comment: Have you tried to `log` the whole object? How does your schema look like? Do you have one of the `_id` and `id` options set? Can you verify that the objects have an Id in the database (e.g. with the `mongo` client).
Comment: @DerTieran It's not defined.
Comment: @PatrickJ.S. Yes, I did try log the whole object and there was no '_id' or 'id' properties. But using mongo client I can see there is '_id' field and it's a string.
Answer: Solved by adding _id: String, to schema definition.


How to extract part of URL path and send URL onClick to query parameters

Question: On my online art store I'm trying to achieve the following:

There's a "Contact me" button on the product page, I want the button to retrieve the artist's name from the URL and insert this into the button URL. URL structure of the product page: "https://store.com/product/smith-john-painting-1/".

Result at this point: clicking the "Contact me" button on this page leads the visitor to "https://store.com/contact/smith-john/"

Additionally, when the visitor visits the contact page through a product page and fills in the contact form, I want to know which product they viewed. A clean method of doing this (as I've understood from doing research) is by using query parameters. Therefore, using the example mentioned above: when the visitor views the product page and clicks the "Contact me" button, the part after the artist's name (however long that is), "painting-1", is extracted from the URL and added as query parameters as "?product=painting-1".

End result: clicking the "Contact me" button on the product page mentioned above leads the visitor to
"https://store.com/contact/smith-john/?product=painting-1"
I've only found parts of the solution, any idea on how to achieve this?
Comment: What parts of the solution have you found? How are they lacking?
Comment: Please visit [help], take [tour] to see what and [ask]. Do some research, search for related topics on SO; if you get stuck, post a [mcve] of your attempt, noting input and expected output, preferably in a [Stacksnippet](https://blog.stackoverflow.com/2014/09/introducing-runnable-javascript-css-and-html-code-snippets/)
Answer: Try this

const url = new URL("https://store.com/product/smith-john-painting-1/")
const artistUrl = url.origin

const parts = url.pathname.split("/")
const [lastName, firstName, item, number] = parts[2].split("-")
const pageUrl = `${artistUrl}/contact/${lastName}-${firstName}/?product=${item}-${number}`
console.log(pageUrl)


views paging dropdown

Question: I need something like a drop down pager for a view with many pages.
Either drop down with all pages listed, or maybe more fancy like this one here:
http://www.zeit.de/2014/18/sextourismus-ostafrika/seite-5
(Scroll down to the comments part. Hovering the comments-pager pops up a grid with page-numbers)
Is there a module for that or an easy way to build it myself? I didn't find a solution.
Answer: For now I didn't find any module for this but you can achieve this by playing around with pager CSS. Just like drop down menus. Pager also has an unordered list with ul and li. I tried it and somehow I was able to show pager as a grid on hovering it and it was working.
You have to do some more in it to achieve exactly what you want.
Here I have given you a rough idea and I think this will help you.

views paging dropdown


Find column values that are a start string of given string.

Question: I have a database table that contains URLs in a column.  I want to show certain data depending on what page the user is on, defaulting to a 'parent' page if not a direct match.  How can I find the columns where the value is part of the submitted URL?
Eg. I have www.example.com/foo/bar/baz/here.html; I would expect to see (after sorting on length of column value):

www.example.com/foo/bar/baz/here.html
www.example.com/foo/bar/baz
www.example.com/foo/bar
www.example.com/foo
www.example.com

if all those URLs are in the table of course.
Is there a built in function or would I need to create a procedure?  Googling kept getting me to LIKE and REGEXP, which is not what I need.  I figured that a single query would be much more efficient than chopping the URL and making multiple queries (the URLs could potentially contain many path components).
Comment: Some PL/SQL procedure, for sure. But it is easy to do
Answer: Simple turn around the "Like" operator:
SELECT * FROM urls WHERE "www.example.com/foo/bar/baz/here.html" LIKE CONCAT(url, "%");
http://sqlfiddle.com/#!2/ef6ee/1
Comment: Wow, _head slap_!  I assume if I wanted to allow any protocol I would just concat an additional '%' before url, yes?  Although that may catch some unintended.


SSRS - embed URL and formatting characters in parameter

Question: I'm making a form letter in SSRS 2012 that will be delivered by email.  I had it working fine but now the powers that be have requested a much more dynamic aspect to it based on the individual recipient...  Different paragraphs now need to be included/excluded based on the target.
With that, I pulled the body of the email out of SSRS and am now assembling it in SQL Server and passing it over to SSRS as a parameter (so that I don't wind up making a dozen SSRS reports to handle the need).
I have that part working too now, but hit a snag...  There were a few bullet points as well as URL's that could look nicer.  I'd like to force an indention before the bullet points and replace www.mysite.com with something prettier like "Click Here".  On the SSRS side of the fence, I currently just have a single text box (and ideally would keep it that way) which contains an expression that references my "EmailBody" parameter.
So far, I have not found the right combination of words to send to Google to see if this is possible, so I figured I'd go straight to the pros here.  I did try formatting the output in a similar manner to what an expression would look like (  ="This is the body of my email"  ) and it just passed that straight on through to the final output.
Any ideas would be appreciated!
Jason
Answer: In case it helps anyone else, I figured out the secret.
Change your text box in SSRS to expect HTML by right-clicking on the placeholder (<< EXP >>) inside the text box, selecting Placeholder Properties, and change the Markup Type to "HTML - Interpret HTML tags as styles".
After that, go back to the SQL Server side of the fence and change the text you are sending as a parameter to HTML with whatever styling properties you desire.
Answer: Sounds like you're on the right track with the HTML markup. I also wanted to suggest that you can use a data-driven subscription. Have the query generate the HTML you want. Then have that populate the body of the email. That way there's no need for any attachments. This has come in handy when I wanted to display a small table of data for viewing on a mobile device rather than having to open an Excel attachment.
Comment: Thank you Steven...  I failed to mention in my original question, but a Data Driven Subscription is exactly what I was doing.  I was passing in the body of the email as a parameter of the report's main query.  It has been working like a champ!


How to properly declare a php function as a variable in another function

Question: I'm looking to display a piece of javascript after the 6th paragraph of every post on my wordpress blog. So far, I can only get the function to work when I'm using a fixed variable:
add_filter( 'the_content', 'prefix_insert_post_ads' );

function prefix_insert_post_ads( $content ) {
    $ad_code = 'fixed variable such as
box
';

    if (is_single()) {
        return prefix_insert_after_paragraph( $ad_code, 6, $content );
    }

    return $content;
}

function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
    $closing_p = '
';
    $paragraphs = explode( $closing_p, $content );
    foreach ($paragraphs as $index => $paragraph) {

        if ( trim( $paragraph ) ) {
            $paragraphs[$index] .= $closing_p;
        }

        if ( $paragraph_id == $index + 1 ) {
            $paragraphs[$index] .= $insertion;
        }
    }

    return implode( '', $paragraphs );
}

The javascript I'm trying to add:
function ad_unit() ?>

<?php

I've tried to declare $placeholder = ad_unit(); but it keep displaying the unit at the top of the content instead of after the 6th paragraph. Somehow the prefix_insert_after paragraph function doesn't work after I add the javascript function. Any ideas?
Answer: Try it with ob_start() and ob_get_clean()
function ad_unit()
{
    ob_start();

    ?>

    <?php

    return ob_get_clean();
}

So what happens is that with ob_start() you enable output buffering. You output the HTML but buffer it, then with ob_get_clean() you get the buffered output from the output buffer.
This will be cleaner without a function (and definitely work, I don't remember what plain HTML does when put in a PHP function):
// Somewhere above the rest of your application
ob_start(); ?>

/// YOUR HTML/javascript

<?php
$advertisement = ob_get_clean();

Comment: output buffers are really great, you can capture what would get sent to the browser w/o it, instead save the buffer into a variable
Comment: WOOT. Thanks man! That did the trick. I wasn't aware how useful `ob_start();` and `ob_get _clean();` are. I read a little bit on PHP.net but damn it's really confusing.

By the way, is this a better way of calling hardcoded html/js then simply closing the php tags to include html/js?
Comment: Sometimes stuff you put in functions are not supposed to be shown where you call the function. Using the output buffer guarantees this. Even if you are absolutely 100% sure that the function will only be called where the output is supposed to be, use the output buffer. Plans change. This might be an interesting read: http://web.archive.org/web/20101216035343/http://dev-tips.com/featured/output-buffering-for-web-developers-a-beginners-guide
Answer: You need opening and closing brackets for the php function
    <?php
    function ad_unit() { ?>

    <?php }

Comment: In the code you posted you were missing open and closing brackets, so unless the function `ad_unit` goes on beyond the line:`<?php` and you have a closing bracket for it after that line than you are missing the closing bracket as well


How can I show a string in 2/3 lines with libharu on iOS?

Question: I have a string which is longer than the width of the place where it has to show up. What I want to do is show the string on 2 or 3 lines.
My code is as follows:
for (int i=0; i<claimsCount; i++)
{
    File_Claim *fileClaim = [claimsArray objectAtIndex:i];

    [self checkCreateNewPage:font:10.0];

    ///////////////////////////////////////////////////////////////////////////////////////
    // if the current category is the same as the previous one then don't write it again
    ///////////////////////////////////////////////////////////////////////////////////////
    if ([subcategory isEqualToString:fileClaim.subCategoryName])
    {
    }
    else
    {
        // hold the old category to check if it is the same
        subcategory = fileClaim.subCategoryName;
        //HPDF_Page_SetRGBFill (_currentPage, 0, 0, 1);
        posY -= PDF_SPACER_Y;
        HPDF_Page_TextOut(_currentPage, PDF_BASE_DATA_LABELS_START_X, posY, [fileClaim.subCategoryName cStringUsingEncoding:NSWindowsCP1252StringEncoding]);
    }

    //HPDF_Page_SetRGBFill (_currentPage, 0, 0, 0);
    posY -= PDF_SPACER_Y;

    HPDF_Page_TextOut(_currentPage, PDF_BASE_DATA_LABELS_START_X+15, posY, [fileClaim.name cStringUsingEncoding:NSWindowsCP1252StringEncoding]);
    HPDF_Page_TextOut(_currentPage, [self alignRightNumberX:fileClaim.unitPrice:260], posY, [[NSString stringWithFormat:@"%.2f €",fileClaim.unitPrice] cStringUsingEncoding:NSWindowsCP1252StringEncoding]);
    HPDF_Page_TextOut(_currentPage, 320, posY, [[fileClaim getCalcString] cStringUsingEncoding:NSWindowsCP1252StringEncoding]);
    HPDF_Page_TextOut(_currentPage, [self alignRightNumberX:fileClaim.totalPrice:483], posY, [[NSString stringWithFormat:@"%.2f €",fileClaim.totalPrice] cStringUsingEncoding:NSWindowsCP1252StringEncoding]);
}

And the part where I put my text:
 HPDF_Page_TextOut(_currentPage, PDF_BASE_DATA_LABELS_START_X+15, posY, [fileClaim.name cStringUsingEncoding:NSWindowsCP1252StringEncoding]);

Now this has to come on 2 or 3 lines instead of 1. And I can't figure out how to do this.
Thanks in advance,
Lewion
Answer: I've been using LibHaru for few days now, and I came across the same question.. I went into writting my own C function to deal with line breaks and multiline support ; and then today I found out that HPDF_Page_TextRect() can actually do the job for you! :)
It will automatically wrap up words on multilines in a area defined by a Rectangle and it also returns the number of characters written...


Help with the Probabilty of Rolling Two Ten-Sided Dice Multiple Times Until 100 is Reached

Question: I need some help figuring out the probability of reaching or exceeding 100 based on a number of rolls of two, ten-sided dice. Here's the scenario.
I am starting from zero. I am rolling two (fair) ten-sided dice, to generate a result between 2 and 20. After the roll, I'm recording the number rolled as the 'total' and then rolling again. I'm taking the new result and adding it the total, then rolling again and so on. I'm trying to have the total reach or exceed 100.
Example:
On my first roll, I get 12. I record 12 and roll again.
On my second roll, I get 7. I add 7 to the current total of 12 to have a new total of 19. Then I roll again.

How many rolls must I make to have a 25% chance of reaching or exceeding 100?
How many rolls must I make to have a 50% chance of reaching or exceeding 100?
How many rolls must I make to have a 75% chance of reaching or exceeding 100?
How many rolls must I make to have a 90% chance of reaching or exceeding 100?
Answer: (Scenario with 1 dice):
Denote $P(r,s)$ probability to get sum $s$ by $r$ rolls.
Denote $Q(r,s) = 1-\sum\limits_{q=1}^{s-1}P(r,q)$ $~$ probability to get sum $\ge s$ by $r$ rolls.
Obviously:
$$
P(1,1)=P(1,2)=\ldots=P(1,10)=0.1;
$$
then
$$
P(r,s) = \sum\limits_{q=s-10}^{s-1} P(r-1,q)\cdot 0.1
$$
(i.e. sum $s$ we can get of "previous" sums $s-10$, or $s-9$, ..., or $s-1$).
Step-by-step, we can fill table of probabilities $P(r,s)$.
A few conclusions:
$Q(16,100) = 1-\sum\limits_{q=1}^{99}P(16,q) \approx 0.159924$;
$Q(17,100) \approx 0.307628$;
$Q(18,100) \approx 0.483771$;
$Q(19,100) \approx 0.654096$;
$Q(20,100) \approx 0.791809$;
$Q(21,100) \approx 0.887108$;
$Q(22,100) \approx 0.944590$;
$Q(23,100) \approx 0.975252$.
Now you can choose closest values:
$25 \%$: ~ 17 rolls;
$50 \%$: ~ 18 rolls;
$75 \%$: ~ 20 rolls;
$90 \%$: ~ 21 rolls.

(Scenario with 2 dices):
As dices are independent, then all that we need is to consider even number of single rolls, and divide them by $2$.
$Q_2(8,100) =Q(16,100) \approx 0.159924 (\approx 15.99 \%);$
$Q_2(9,100) =Q(18,100)  \approx 0.483771 (\approx 48.38 \%);$
$Q_2(10,100)=Q(20,100)  \approx 0.791809 (\approx 79.18 \%);$
$Q_2(11,100)=Q(22,100)  \approx 0.944590 (\approx 94.46 \%).$