Como calcular o DigestValue do XML?

Question: Ao assinar algum XML, o assinador gera a tag DigestValue contendo uma Hash.
Eu consigo gerar o digest value com um certificado digital, mas eu gostaria de gerar essa hash sem que tenha a necessidade de um certificado...
Eu vi em algumas documentações, que é necessário utilizar SHA1 e Base64, mas sempre que eu utilizo esses dois algoritmos, a hash que me retorna não é a que eu estou esperando.
Alguém sabe qual o algoritmo completo para gerar esse valor?
Cenário:

Entrada é um XML qualquer
Utilizo o algoritmo de criptografia SHA1, em seguida
Transformo o retorno da criptografia em Base64
O retorno da base64 deveria ser a hash correta, porém vem uma hash diferente.
Comment: Faltou um passo importante que é canonizar o XML. Recomendo o uso da classe [Canonicalizer](http://santuario.apache.org/Java/api/org/apache/xml/security/c14n/Canonicalizer.html) do projeto [Apache Santuario](http://santuario.apache.org/) (na verdade, eu não faria nada na mão, usaria essa biblioteca para tudo). Sobre o algoritmo basta aplicar um SHA1 para obter os bits (não a assinatura em HEX) e, em cima desses bits obter a Base64 da assinatura. A biblioteca [Apache Commons Codec](http://commons.apache.org/proper/commons-codec/) tem tudo que você precisa para a segunda parte.
Comment: Como é o código que você usa para gerar e comparar o hash? Pode postar-lo? É difícil saber o que está errado sem saber exatamente como você o fez.
Comment: Eu gostaria de saber qual o algoritmo para gerar essa hash... Vou editar a pergunta descrevendo os passos que faço.
Comment: É para codificar em SHA1 e conveter em base64 eu utilizo essas bibliotecas que você citou.
Answer: O processo de se calcular o DigestValue de um arquivo XML não se resume a calcular o hash desse arquivo, mas possui outros passos intermediários:

Colocar o documento na forma canônica, tal como apontado por @Anthony Accioly;
Aplicar quaisquer transformações especificadas em Reference/Transforms. Se não há nenhum elemento Transforms, ou o mesmo está vazio (sem sub-elementos), então nada precisa ser feito.

Certifique-se que esses passos foram corretamente adotados e, se ainda tiver problemas em conseguir um resultado correto, acrescente mais detalhes à sua pergunta de modo a podermos ajudar mais (se possível mostrando o SignedInfo que quer atingir, um link para o arquivo XML e uma descrição dos passos e ferramentas que utilizou).
Nota: minha resposta anterior (em arquivo) não se aplica aqui, pois de fato o DigestValue é um simples hash e não uma assinatura digital (portanto invariante à presença ou não de um certificado).
Comment: Huum, obrigado pela resposta. Eu falei que é um digestvalue diferente pois eu já possuo o XML contendo o digestvalue correto e eu preciso de uma função que gere esse digestValue. O DigestValue é independente do certificado, pois eu consigo gerar o digestvalue sem que eu tenha o certificado.
Comment: @fymoribe Pelo que estou lendo, você tem razão, `DigestValue` é uma coisa e `SignatureValue` é outra... Mas ainda não consegui entender exatamente o que ele é, nem qual seu propósito. Vou investigar mais um pouco, se descobrir algo atualizo minha resposta.
Comment: fymoribe, não se esqueça de aceitar a resposta ;)
Comment: Realmente faltou canonizar a string antes de fazer a criptografia, muito obrigado.

Como calcular o DigestValue do XML?


Salvar informações em um SQLite e depois subir para um JSON com webserive

Question: Eu li vários tutoriais sobre como pegar um JSON e passar as informações para um SQlite, porém como eu faço o inverso, pego os dados da aplicaçao já salvos no SQLite e depois os transfiro para um webservice com o JSON... agradeço desde já
Comment: Isso depende com a linguagem que você vai utilizar..
Comment: O mais importante a se definir é QUANDO os dados vão sair do sqlite e ir para o banco externo através do webservice.
É no clicar de um botão? É sem o usuário saber? É quando o aplicativo abre? Dependendo da resposta, você terá uma abordagem diferente.
Quanto a tecnologia: É recomendável usar uma biblioteca chamada Gson para transformar seu objeto em json. O webservice tem que ter uma classe identica a que você está enviando para que ele possa converter o json que chega na classe para, finalmente, realizar os inserts no banco externo.
Comment: Eu vou usar Java... quero q a aplicação faça sem o usuário saber, se ele estiver conectado ele atualiza se não nada muda no BD interno
Comment: Eu até já montei um BD interno usando SQLite, agora quero criar um webservice pra poder começar a passar as informações para a rede e deixar lá armazenado de forma online
Answer: Adicione a dependencia do Gson do google ao seu gradle, tem no m2Repository, você vai fazer sua pesquisa no banco normal, transformar em um objeto java normal e então é só chamar o gson assim
<code>new Gson().toJson(object).build();
</code>
Não me lembro exatamente se é assim, se for isso que você quer mesmo, recomendo dar uma olhada na documentação do Gson, é uma ótima classe, sempre uso, de tão simples eu nem lembro como faço...
Na documentação tem as anotações que você pode fazer nas suas classes para poder personalizar os json, levar ou não um campo e alterar o nome que ele vem no json...
https://github.com/google/gson/blob/master/UserGuide.md#TOC-Goals-for-Gson
Acredito que este link vai suprir as suas duvidas...


Inferring parameters for a regression with features of both multivariate probit and ordinal regression?

Question: Based on my data generated by a complex process and the problem below detailed, I have tried various approaches, to no avail.
I am trying to answer one or more of the following questions:
a) Has someone solved my problem already? Are there other clever
   approaches I could use instead (perhaps something like PLS or CCA)?
b) What is the right literature to look for previous work addressing
   my problem?
c) If this problem is novel (which I personally doubt), what is the
   right approach to solve it?
d) In my proposed approach below described, is there something
   obvious I am missing?
Here is my problem:
For $N$ individuals, with $M$ associated covariates, I observe outcomes in $J$ possible classes; thus my design matrix $X$ is of dimension $M$ x $N$ and my response matrix $Y$ is of dimension $N \times J$. For a given class $j$ there is a latent variable $U_{i,j}$ s.t. when $U_{i,j} < 0$, $Y_{i,j}=0$ and $Y_{i,j}=1$, otherwise . Up to this point, if $U \sim MVN(\beta X, \Sigma)$, I have described a standard multivariate probit regression scenario. However, if a given $U_{i,j}$ is greater than all other classes $U_{i,-j}$ and greater than some constant $c_1$, then $Y_{i,j} =t$ if $c_{t-1} < U_{i,j} < c_t$ where $t\in \{1,2,...,T-1\}$; $Y_{i,j}=T$ if $U_{i,j} > c_{T-1}$. Here the cutpoints $c_t$ are unknown. On its own, the latter half corresponds to an ordinal regression problem. However, together this problem seems to be more complex than either probit or ordinal regression.
Below is the R code to generate data from this process.
The values of $U$ are generated directly without specifying a linear relationship with $X$:
<code>library(MASS) # for mvrnorm

N <- 1e3 # num. of observations
J <- 12  # num. of classes
cuts <- c(1.5, 2, 2.25, 2.5, 2.7, 3) # T=6

S <- rWishart(n=1, Sigma=diag(J), df=20) # sample cov. mat.
U <- mvrnorm(n=N, mu=rep(0, J), Sigma=S[,,1]) # generate U
Y <- apply(U, 1, function(u) { # generate Y from U
     u <- as.numeric(scale(u)) # s.d. is 1 for identifiability
     y <- ifelse(u < 0, 0, 1)  # U's extreme enough are observed
     cond <- u > cuts[1] & u == max(u) # most extreme U's are ranked
     if(any(cond))
       y[which(cond)] <- findInterval(u[which(cond)], cuts)
     return(y)
  }
)
</code>
In my case, $N$ is approximately $3500$, $J=12$ and $M=30$, and $T=6$. The outcomes of the classes are correlated and the individuals are hierarchically related.
Here are the solutions I have tried so far:
Initially, I thought I could use JAGS to solve this problem. Before implementing the full model, I tried a hierarchical multivariate probit regression. However, JAGS seemed to take an inordinately long time to sample from the posterior.
Thus, I have since been searching through the simulated likelihood literature e.g. GHK, but found no work reproducing the model described above. Specifically, I am exploring approaches such as approximate Bayesian computation (ABC), indirect inference, and simulated method of moments.
Any help would therefore be much appreciated.
Comment: If it really only is an issue of sampling speed, then Stan might be an alternative.
Comment: By the way, just to make sure I understand your problem correctly, let me phrase it in my own words: you want to estimate an ordered probit, and the complication is that you have several outcomes, so that the ordered probit becomes a multivariate ordered probit. Does this sum up your problem? I am asking because it sounds like that to me, but it seems that there are papers out there dealing with multivariate ordered probits, so I conclude I must misinterpret sth...
Comment: Do you really need the notion of a latent class?  It is very general and may be confusing you.  Also GLMMs are notorious for having bad mixing - it really depends on how you set up the sampler.  BayesX and INLA may be better tools than jags.
Comment: What is the alternative to a latent class when dealing with ordinal data? Wouldn't I lose power by not modeling the hidden process underlying the observed data?
Comment: Only example is to model $ Pr (Y> y) $.  and make this an increasing/decreasing function of $ y $.  I think this is what is done in hazard/survival modelling.
Comment: @coffeinjunky It is almost a multivariate ordered probit. *Except* for the fact that when for some class $j$ where $U_{i,j} > U_{i,-j}$ *i.e.* greater than all other U's for an individual, then the rank is observed, but only for that given class $j$. See the lines in the simulation source code regarding the variable *cond* for clarification. The simulation is a multivariate probit before those lines.
Answer: Have you looked into the stats literature on reduced-rank vector generalized linear models? It seems you might be trying to identify the model by introducing constraints that in effect make it a hybrid of the probit and ordinal regressions, plus with a multilevel structure on the right-hand side of the equation. This document (pdf alert) on the VGAM package in R offers a relatively straightforward introduction to reduced-rank generalized models.
Comment: Thanks for the recommendation. While it looks like *rrvglm()* is along the lines of what I need, VGAM only implements a bivariate logit/probit model and it's not clear to me how I could use constraints to coax a multinomial logit model into a multivariate logit.


Global extremes of $f(x,y) = \sin(xy)$ in $A$

Question: I am trying to solve the following problem:

Find the extremes of $f(x,y) = \sin(xy)$ restricted to points of $A = \{ (x,y) \in \mathbb{R}^2: x^2+y^2 = 1\}$.

My first attempt was to use Lagrange multipliers, since the procedure of parametrizing the ellipse defined by $x^2+2y^2-1 = 0$ and composing it with $f$ seemed like a dead end.
Deriving $f$ I get that:

$fx = y \cos(xy)$
$fy = x \cos(xy)$

Naming $g(x,y) = x^2+2y^2-1$:

$gx = 2x$
$gy = 4x$

Then:
\begin{cases}
y \cos(xy) = \lambda 2x\\
x \cos(xy) = \lambda 4y \\
x^2+2y^2-1 = 0
\end{cases} for some $\lambda \in \mathbb{R}$.
But I can't find solutions to that system, the terms get way too complicated.
Is there any other way I can start to find the extremes? A change of variables at some point perhaps? Or that system should yield solutions?
Thanks a lot.
Answer: When you multiply first equation by $x$, second by $y$ and add first and second side by side you get:
$$2xy\cos(xy)=\lambda(2x^2+4y^2)$$
Next by third equation $\lambda(2x^2+4y^2)=2\lambda$, so:
$$2xy\cos(xy)=2\lambda$$
Now there are two cases $\lambda=0$ or $\lambda\neq 0$. For $\lambda \neq 0$ by first equation:
$$y\cos(xy)=x^2y\cos(xy)$$
Dividing both sides by $y \cos(xy)$ you get:
$$1=x^2$$
The same way you get that $2y^2=1$.Can you finish this solution (case $\lambda=0$ is standard)?
Comment: I like your solution, but couldn't dividing by $y cos(xy)$ generate more conflict cases?
Comment: When $\lambda \neq 0$ then $y\cos(xy) \neq 0$, because $xy\cos(xy)=\lambda$.
Comment: Right. Thanks a lot, agha!
Answer: for $x$ and $y$ not equal to zero we obtain $\cos(xy)=\frac{2\lambda x}{y}$ and $\cos(xy)=\frac{2 \lambda y}{x}$ thus we get
$\frac{ \lambda x}{y}=\frac{\lambda y}{x}$
Answer: You've all been very helpful.
So taking it from there:
$x^2 = 2y^2$
$\frac{x^2}{2} = y^2$
$y = \pm \frac{x}{\sqrt{2}}$
Then, replacing in the third equation:
$x^2 + (\frac{x}{\sqrt{2}})^2 = 1$
$x^2 + \frac{x^2}{2} = 1$
$x^2 = \frac{2}{3}$
$x = \pm \sqrt{\frac{2}{3}} \Rightarrow y = \pm \frac{\sqrt{3}}{3}$
In both points $f$ equals to $\sin(\frac{\sqrt{2}}{3}) > 0$
Then, looking at the ellipse:

$x=0 \Rightarrow  y = \frac{1}{\sqrt{2}}$
$y=0 \Rightarrow  x = 1$

And $f(x,0) = f(0,y) = 0$, so $f$ has global minima at $(0,\frac{1}{\sqrt{2}})$ and $(1,0)$; and global maxima at $(\frac{\sqrt{2}}{3},\frac{\sqrt{3}}{3})$ and $(-\frac{\sqrt{2}}{3},-\frac{\sqrt{3}}{3})$.


Can someone provide an example of Thor::HiddenTask usage?

Question: I've just started using Thor. I've been looking around the documentation and can't find any code examples of making a task hidden. What I want is something like this,
desc "configure", "Do the configuration"
def configure
  # configuration
end

desc "import", "Import the stuff"
  invoke :configure
  # import the stuff
end

But I don't want configure to show up in the list of tasks. It's kind of... private, you know? Can someone give me an example of this?
In lib/thor/task.rb there is a subclass of Task called HiddenTask. Can anyone provide an example of how that subclass is used, and of how its method hidden? gets called? Thanks!
EDIT: Both of the answers below accomplish the goal mentioned in my question, but neither of them are an example of Thor:HiddenTask usage. I think I'm going to un-accept the answer to this question. They are both good answers, and the first one I actually used to achieve the desired behavior, but I would really like to see an example of a HiddenTask so that the answer corresponds to the question nicely.
Thanks!
Answer: In thor/spec/fixtures/script.thor you can find such usage:
desc "hidden TYPE", "this is hidden", :hide => true
def hidden(type)
  [type]
end

Answer: This is a little late but maybe this can help. Put your private methods in a "no_task" block like:
no_task do
  def my_private_method
    # Do something here
  end
end

Comment: This is the solution that I used to make my sweet app work, but it isn't an example of HiddenTask. This answer was originally marked as the accepted answer.


NetApp OnTap: Reference by IP or Cluster Name?

Question: I have a new NetApp Ontap cluster, and I'm trying to figure out how to document procedures for using it within my organization.  It has a cluster name (netapp-cm, creative, I know), and I've allocated an administrative IP address.  The monitoring tools we're using seems to use the IP address as the primary key for identifying the cluster, but that seems wrong to me, as IP addresses are more or less arbitrary these days in a world full of NAT and DHCP.
When NetApp OnTap monitoring tools display multiple clusters, what do they primarily use to identify each cluster: the cluster's IP address, or the assigned cluster name?
Comment: If your **SAN** has an IP address that changes, that's a problem.  But yes, typically an IP address wouldn't be used... DNS name would.
Comment: If this question doesn't get reopened, and the answers below don't satisfy you, you might try asking on [the netapp administrators' mailing list](http://www.teaparty.net/mailman/listinfo/toasters) (disclaimer: I admin the list).
Comment: Glad to see that a question from a true net.legend was re-opened!
Answer: For something like a monitoring tool, using DNS is fine and arguably preferred.  That said, I'm not a NetApp expert, but if its anything like most storage, there's a cluster IP. and node IP's.  I would direct your monitoring at both the cluster and individual nodes so you have a complete picture of the health status.
One other note, as for mounting storage, THAT i would argue should be done via IP.  There's a likely hood that DNS may not be available in certain cases , and you wouldn't want a dependency on that for storage connectivity. Example being, what if your DNS server is located on the NetApp.
Answer: I'd say use the cluster and node names and resolve them in DNS. DNS is an infrastructure service, and if it's unreliable then you have much bigger problems. (If your DNS has a dependency on your NetApp kit, then that might be an exception, but I'd suggest you don't want such a dependency to exist in the first place).
I would, however, recommend including the IP of your admin server(s) in the hosts file on your filers. And then use the name for ssh.access and httpd.admin.access (you can use a netgroup for this as well, which is handy if you're already using netgroups).
And put the IP of the RLMs for your filers into your management station hosts file.


Radical expression for $\tan 14.4^\circ$

Question: Given that
$\displaystyle\cos 20^\circ=\frac{\sqrt[3]{\frac{1-i\sqrt{3}}{2}}+\sqrt[3]{\frac{1+i\sqrt{3}}{2}}}{2}$
and
$\displaystyle\sin 20^\circ=\frac{i\left(\sqrt[3]{\frac{1-i\sqrt{3}}{2}}-\sqrt[3]{\frac{1+i\sqrt{3}}{2}}\right)}{2}$
It turns out that there is a nice radical expression for $\tan 20^\circ$:
$\displaystyle\tan 20^\circ=\sqrt{11-\left(1-i\sqrt{3}\right)\sqrt[3]{148+4i\sqrt{3}}-\left(1+i\sqrt{3}\right)\sqrt[3]{148-4i\sqrt{3}}}$.
My question is, how did one get from the first two expressions to the third? It's pretty straightforward to find the minimal polynomial for $\cos 20^\circ$ from the triple-angle formulas, which is $8x^3-6x-1=0$. In other words, where did the three "new" numbers ($11$ and $37\pm i\sqrt{3}$) in the expression come from?
Now a similar situation arises for $\tan 14.4^\circ$:
$\displaystyle\cos 14.4^\circ=\frac{\sqrt[5]{\frac{-1+\sqrt{5}-i\sqrt{10+2\sqrt{5}}}{4}}+\sqrt[5]{\frac{-1+\sqrt{5}+i\sqrt{10+2\sqrt{5}}}{4}}}{2}$
and likewise for $\sin 14.4^\circ$.
My gut instinct is that $\tan 14.4^\circ$ can be written as
$\tan 14.4^\circ=\sqrt{a-\left(-1+\sqrt{5}-i\sqrt{10+2\sqrt{5}}\right)\sqrt[5]{b+ci}-\left(-1+\sqrt{5}+i\sqrt{10+2\sqrt{5}}\right)\sqrt[5]{b-ci}}$
for some algebraic $a, b,$ and $c.$
My question is, what are the values of a, b, and c? And I'm betting that my "gut instinct" on $\tan 14.4^\circ$ is wrong, so if anyone could help me derive the radical expression for $\tan 14.4^\circ$, that would be great.
Comment: Try using:$$\tan(x)=\pm\frac{\sqrt{1-\cos^2(x)}}{\cos(x)}$$ because you already know $\cos(x),x=14.4^\circ$.
Answer: Try using:$$\tan(x)=\pm\frac{\sqrt{1-\cos^2(x)}}{\cos(x)}$$ because you already know $\cos(x),x=14.4^\circ$.
$$\cos 14.4^\circ=\frac{\sqrt[5]{\frac{-1+\sqrt{5}-i\sqrt{10+2\sqrt{5}}}{4}}+\sqrt[5]{\frac{-1+\sqrt{5}+i\sqrt{10+2\sqrt{5}}}{4}}}{2}$$
Therefore
$$\tan(14.4)=\tan\frac{2\pi}{25}= \frac{\sqrt{1-\bigg(\frac{\sqrt[5]{\frac{-1+\sqrt{5}-i\sqrt{10+2\sqrt{5}}}{4}}+\sqrt[5]{\frac{-1+\sqrt{5}+i\sqrt{10+2\sqrt{5}}}{4}}}{2}}\bigg)^2}{\frac{\sqrt[5]{\frac{-1+\sqrt{5}-i\sqrt{10+2\sqrt{5}}}{4}}+\sqrt[5]{\frac{-1+\sqrt{5}+i\sqrt{10+2\sqrt{5}}}{4}}}{2}} =  \frac{\sqrt{1-\bigg(\frac{\sqrt[5]{\frac{-1+\sqrt{5}-i\sqrt{10+2\sqrt{5}}}{4}}+\sqrt[5]{\frac{-1+\sqrt{5}+i\sqrt{10+2\sqrt{5}}}{4}}}{2}}\bigg)^2}{\sqrt[5]{-1+\sqrt{5}-i\sqrt{10+2\sqrt{5}}}+\sqrt[5]{-1+\sqrt{5}+i\sqrt{10+2\sqrt{5}}}}  $$
Good luck simplifying this. Here is proof of the answer. Please correct me and give me feedback!


Bootstrap vs Standard Estimation

Question: Suppose I have an estimate (say an OLS coefficient), I can obtain its standard error using the standard OLS formula. I can also use nonparametric bootstrap and compute the standard error. My question is: should these two ways always give (almost) the same answer? If not, what are possible reasons for the difference?
(Note that there could be heteroscedasticity or autocorrelation in the regression error term but I am ignoring them both in the OLS estimation or in performing bootstrap).
Answer: The confidence level of 'standard' t-tests in OLS depends on normality assumptions or asymptotic arguments. If the residuals or dependent variable are (surely) normally distributed, the t statistic is surely t-distributed, hence you have perfect $\alpha$ level control in the test. If the variates are not normally distributed, the argument still holds asymptotically in large samples as long as the dependent variable is continuous and residuals are independent and identically distributed.
Bootstrapped test statistics are always then useful if we do not trust the distributional assumptions underlying standard test procedures or if the sample size is too small to allow an asymptotic argument. The big advantage of the bootstrap is that it then leads to conclusions with accurate confidence, while standard tests may fail (in the sense of rejecting too liberal or conservative).

Bootstrap vs Standard Estimation


How does one indicate time for a melody without a consistent meter?

Question: I wrote a melody. I have trouble figuring out which time signature it belongs to. I tried different rhythms, this rhythm sounds the best. It is safe to say, this is the rhythm of this melody. But this rhythm does not fit any time signature. I put accent marks on the accented notes. 3/4 pattern is strong, weak, weak. 4/4 pattern is strong, weak, less strong, weak. In both time signatures, the accented notes don't always fall on the strong beats. The only solution is to change the rhythm to match the strong beats, but that is no longer the correct rhythm for the melody.
How can I indicate meter for this melody?
(Please forget the fact that I wrote it in 3/4 time signature. Because I have to choose a time signature to start with.)
Comment: @ToddWilcox The spirit of the close reason is that we don't want questions about the time signature of a YouTube video. It is not intended to apply to clearly notated music. And the fundamental question is how to notate music in which a single, consistent time signature doesn't apply. This is both applicable and useful to future askers. Editing the question to clarify its purpose would be more helpful than closing it. I suspect it's a duplicate, but I haven't found an original to reference against.
Comment: Given the transposed motif between Bars 2-4 and Bars 6-8, keeping the time signature as 3/4 actually *does* seem like a sensible option. (...One of multiple options, though, which is why I don't feel confident enough to answer.) Keeping the time signature as 3/4 would be in line with how syncopated dances like furiants are notated.
Comment: Why the close votes? It's a practical problem that can and does occur in music.
Comment: Voted to reopen. This question involves neither "transcribing or finding a song" and does involve analysis of a "well-defined subsection, including a concrete reference".
Comment: "…including identifying … time signatures…" Seems really clear to me. Also "rarely useful to future readers". Figuring out this particular bit of music for the asker does not add to a body of knowledge that is generally useful in understanding music theory or practice. An equally good close reason IMHO is "opinion based". This falls under "how should I write music" which is one of the most personal and subjective things I think we can do as musicians.
Comment: @Aaron My understanding is that editing a question to clarify its purpose is the sole purview of the asker. I've personally been told not to edit other people's questions to make them on-topic. Beyond that, we'll have to agree to disagree on the spirit of the close reason. Also, accents and downbeats are not the same. There's tons of music where the accents specifically oppose the meter - who are we to say whether this should be notated with accents in opposition to meter or whether meter should change to serve the accents? It's a matter of taste/opinion.
Comment: @ToddWilcox I've been given the opposite impression of editing — that it was encouraged, including clarifying OP questions. This looks like a job for Meta....
Comment: @Aaron The question as it is is unanswerable. Accents and meter can be a subtle thing and if OP cannot notate their music, we don't know what the music is to be notated. Then any answer might be wrong and mislead the OP, or other future readers of the site.
Comment: @user1079505 I'm not sure I understand the problem. OP has clearly notated the music and placed accents on the "downbeats".
Comment: @Dekkadeci Your comment seems like a good answer, should the question be reopened. Other possibilities are covered in other answers, and your option would be a good complement.
Comment: @Aaron Given the OP has clearly some issues with understanding meter and accents I'm not certain that the notes they marked with accents are downbeats. This may or may not be a correct assumption. In my opinion without hearing the music properly performed it's impossible to guess.
Answer: Time signatures are meant for music that has a regular pattern of accents.
Some music does not have a regular pattern of accents.  There are two possible solutions to this.
One is the one Stravinsky used for The Rite of Spring, which is to write everything in a basically arbitrary time signature (he used 2/4) and write in all the accents.
The other, probably a bit more common, is illustrated for example by several of the movements in Messaien's Quartet for the End of Time.  There is no time signature and every measure has a different number of beats, with the beaming and where the bar lines are indicating what the strong and weak beats are.  If the time signature changes but not constantly, one can also have changing time signatures.
(There is a reason why Stravinsky chose to put everything in 2/4 - The Rite of Spring is a ballet and the constant time signature is easier for the dancers, as they keep dancing in 2/4 even though the accents shift.)
Comment: My copy of The Rite of Spring has plenty of time signature changes
Comment: @ElementsinSpace: Yes there are time signature changes, but not nearly as many as there would be if the bar lines were to follow the accents.  For example, in the section "The Augurs of Spring; Dances of the Young Girls", the accents keep shifting but it is all written in 2/4
Answer: In addition to @AlexanderWoo's suggestions, it's also possible to change time signatures within a piece.
As a starting point, let's assume all the marked accents are "beat 1". A literal transcription, then, would be
X: 1
T: Melody time signature
T: Example 1
K: A minor
L: 1/4
M: 2/4
E' A | [M: 3/4] B/2C'/2 D' C' | B C' A | [M: 1/4] B/2G/2 | [M: 3/4] A3 |
[M: 2/4] A D | [M: 3/4] E/2F/2 G F | E F D | E/2F/2 G E | [M: 4/4] A4 |]

Another possibility emerges if a syncopation is permitted in the fourth measure and if the last note can be of arbitrary length. In that case, a pattern of 2+3+3+4 emerges.
X: 1
T: Melody time signature
T: Example 2
K: A minor
L: 1/4
M: 2/4
E' A | [M: 3/4] B/2C'/2 D' C' | B C' A | [M: 4/4] B/2G/2 !>!A3 |
[M: 2/4] A D | [M: 3/4] E/2F/2 G F | E F D | [M: 4/4] E/2F/2 G E !fermata!A |]

This could also be written in the following way.1
X: 1
T: Melody time signature
T: Example 3
K: A minor
L: 1/4
M: 2+3+3+4/4
E' A | B/2C'/2 D' C' | B C' A | B/2G/2 !>!A3 |
A D | E/2F/2 G F | E F D | E/2F/2 G E !fermata!A |]

A time signature of 5+3+4/4 would also work, if the 2/4 accent is primary and the following 3/4 accent is secondary.
Closer to @AndrewWoo's suggestions, a larger number of beats could be specified, with dotted bar lines used to indicate the strong-weak pulse divisions.

1 A bug in ABCjs, the code used to create these examples, causes the lower number in the time signature to be written at the left. It should be centered.
Comment: Thanks for the answer. If this is the solution, then how do listeners follow the music with constant changing time signatures?
Comment: @YiMing Listeners hear the pulse of music whether or not they recognize it as regular or not. The music examples Alexander Woo gave would be good to listen to as a way to begin to understand how it works.


How do I minimize this Boolean expression?

Question: How do I minimize the following expression $$W'\cdot X'+ X'\cdot Y' + W'\cdot Z' + Y \cdot Z$$
where $\cdot$ stands for Logical AND, $'$ stands for Negation and $+$ stands for Logical OR.
Comment: by minimizing you mean finding a logically equivalent "shortest" possible expression?
Comment: Draw a [Karnaugh map](https://en.wikipedia.org/wiki/Karnaugh_map) to find a minimum set of terms.
Comment: Yes, you may also call it a valid shortest possible expression.
Comment: +Axel, I'm not familiar with K-maps (maybe the professor will talk about it in the next lecture), Is there a way to minimize it other than the k-map?
Comment: @Zaraki this is already minimized. It has a minimal canonical form as sum of products. K-map won't help. If you don't mind the form to be canonical, you can save an AND by factorying out $W'$ from the first and third terms.
Comment: @trying Actually, it can be simplified more; see my Answer... a K-map should show that too.
Comment: @Bram28 great +1. Yes, K-map shows it too.
Answer: $$W'\cdot X'+ X'\cdot Y' + W'\cdot Z' + Y \cdot Z = \text{ (Adjacency)}$$
$$W'\cdot X' \cdot Y + W'\cdot X' \cdot Y' + X'\cdot Y' + W'\cdot Z' + Y \cdot Z = \text{ (Adjacency)}$$
$$W'\cdot X' \cdot Y \cdot Z + W'\cdot X' \cdot Y \cdot Z' + W'\cdot X' \cdot Y' \cdot Z + X'\cdot Y' + W'\cdot Z' + Y \cdot Z = \text{ (Absorption x 3)}$$
$$X'\cdot Y' + W'\cdot Z' + Y \cdot Z $$
Just to be clear, in the last step:
$X' \cdot Y'$ absorbs $W'\cdot X' \cdot Y'$
$W'\cdot Z'$ absorbs $W'\cdot X' \cdot Y \cdot Z'$
$Y \cdot Z$ absorbs $W'\cdot X' \cdot Y \cdot Z$
You can also use the Consensus Theorem:
$$P \cdot Q + Q' \cdot R + P \cdot R = P \cdot Q + Q' \cdot R$$
Applied to your statement:
$$W'\cdot X'+ X'\cdot Y' + \color{green}{W'\cdot Z' + Y \cdot Z} = \text{ (Consensus)}$$
$$\color{green}{W'\cdot X'+ X'\cdot Y'} + W'\cdot Z' + Y \cdot Z + \color{green}{W' \cdot Y}= \text{ (Consensus)}$$
$$X'\cdot Y' + \color{green}{W'\cdot Z' + Y \cdot Z + W' \cdot Y}= \text{ (Consensus)}$$
$$X'\cdot Y' + W'\cdot Z' + Y \cdot Z$$


iPhone App - JSONKit objectFromJSONString returns null

Question: Hi I have an iPhone app that uses ASIFormDataRequest to post a variable to a php file. The php file then returns a set of tuples from my remote database in the form of an associative array.
I use objectFromJSONString to deserialise the json data (using the JSONKit framework), but pon printing out the data, I get null. Here is my code:
+(NSDictionary*)getQuestions:(NSString*)sectionId from: (NSString*) url{
    NSDictionary *questions;
    NSURL *link = [NSURL URLWithString:url];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:link];
    [request setPostValue:sectionId forKey:@"section"];
    NSError *error = [request error];
    [request setDelegate:self];
[request setDidFinishSelector:@selector(requestFinished:)];
    [request startAsynchronous];

    if (!error) {
        //NSString *response = [request responseString];
        //store them in the dictionary
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
        NSString *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        questions = [json objectFromJSONString];
        NSLog(@"%@",questions); //prints null
        [json release];
        [request release];
    }else{
        //UIAlertView to warn users there was an error
    }

    return questions;
}

//doesn't work
- (void)requestFinished:(ASIHTTPRequest *)request
{
    //NSString *response = [request responseString];
    NSLog(@"hello"); //never prints
}

@end
@implementation dbQuestionGetterViewController
@synthesize questions;

-(void)viewDidLoad{
    //code to initialise view
    NSDictionary* arr = [dbConnector getQuestions:@"2" from:@"http://dev.speechlink.co.uk/David/get_questions.php"];
    self.questions = arr;
    [super viewDidLoad];
}
@end

I have tried using an ASIHTTPRequest calback delegate (didFinishSelector)
UPDATE:
Here is the link to the php. When you click it you can see it's outputting JSON properly:
http://dev.speechlink.co.uk/David/get_questionstest.php
Here is the php:
<?php

//connect to database

$dbh = mysql_connect ("localhost", "abc", "123") or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db("PDS", $dbh);

$query = mysql_query("SELECT * FROM Questions WHERE sectionId = 1") or die("Error: " . mysql_error());;

$rows = array();
while($r = mysql_fetch_assoc($query)) {
  $rows[] = $r;
}
//echo '{"questions":'.json_encode($rows).'}';
echo json_encode($rows);
mysql_close();

?>

Answer: It will return nil if the string you're passing in isn't valid JSON.
There's two things that might be happening :
(1) You're not parsing the server's response properly - try outputting the json string to see what you think it is i.e.
NSString *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@", json);

(2) The server is not sending correct JSON - try opening the URL in a browser and making sure that it's correctly formed.
Comment: ok I got it working - the problem was that I was trying to access the data too early.
Comment: i opened the url and it is correctly formed...check for yourself, it's above
Comment: if you loko at the link you will see that there are extra '[]' encapsulating the JSON code..could this be the problem?
Comment: OK, so what do you get when you do `NSLog(@"%@", json);` ?


Graphs where changing any edge increases the clique or independence number

Question: Take the cycle on $5$ vertices, $C_5$. The clique and independence number of this graph are both $2$. If we add any edge to $C_5$ we get a triangle. Meanwhile, if we remove any edge we get a triangle in the complement.
So whatever edge we change, we get either an increase (from $2$ to $3$) of the clique number, or of the independence number. Is $C_5$ the only graph with this property, or are there others?
Comment: Interesting question. Trivially, any complete graph can only be changed by removing an edge and thus changing the independence number. (Similarly in complement, an edgeless graph)
Answer: Nice question! No, this isn't the only nontrivial example. Take $p=13$ and construct the graph whose vertices are the residue classes mod $p$, with an edge between any two whose difference is a quadratic residue. This is well-defined (because $p\equiv 1\pmod 4$, $x-y$ is a quadratic residue if and only if $y-x$ is).

The graph is edge-transitive, since $x\mapsto a^2x+b$ is an automorphism for any $a,b\in \mathbb Z_p$ with $a\neq 0.$ It is also self-complementary (multiply by any quadratic non-residue). Thus it suffices to show that adding some edge (say $0$-$2$) increases the clique number. The clique number is $3$: the only vertices which form a triangle with $0$-$1$ are $10$ and $4$, and these four vertices don't form a clique, so $0$-$1$ isn't in a clique of size $4$ (and by transitivity neither is any other edge). But if $0$-$2$ is added then $12$-$0$-$2$-$3$ is a clique of size $4$.
It may well be that this construction works for any prime $p\equiv 1\pmod 4,$ but I can't see how to prove that.
Comment: Forgot to point out: $C_5$ is the same construction for $p=5$.
Answer: Here are a few graphs with your property.
Let $\alpha(G),\ \omega(G),$ and $n(G)$ denote the independence number, the clique number, and the order of a (finite) graph $G.$
The Ramsey number $R(s,t)$ is defined by the property that $R(s,t)-1$ is the maximum possible order of a graph $G$ with $\alpha(G)\lt s$ and $\omega(G)\lt t.$ Thus, by definition (and by Ramsey's theorem which tells us that $R(s,t)$ exists), there is a graph $G_{s,t}$ (not necessarily unique) such that $\alpha(G_{s,t})=s-1,\ \omega(G_{s,t})=t-1,$ and $n(G_{s,t})=R(s,t)-1.$ In some cases such a graph $G_{s,t}$ will have your property:

Lemma. If $R(s,t)=R(s-1,t)+R(s,t-1),$ then $G_{s,t}$ has the property that removing any edge will increase the independence number, while adding any edge will increase the clique number.
Proof. The graph $G=G_{s,t}$ is regular of degree $R(s,t-1)-1.$ Adding an edge $uv$ will create a vertex $v$ of degree $R(s,t-1).$ Since $\alpha(G+uv)\le\alpha(G)\lt s,$ it follows that $v$ is in a $t$-clique of $G+uv,$ and so $\omega(G+uv)\ge t\gt\omega(G).$ Similarly, removing an edge will increase the independence number.

It's a basic lemma in Ramsey theory that the inequality $R(s,t)\le R(s-1,t)+R(s,t-1)$ always holds; it seems that the inequality is usually strict, but the equality cases give us graphs with your property.
Examples:
$R(3,3)=6=3+3=R(2,3)+R(3,2);\ G_{3,3}=C_5.$
$R(n+1,2)=n+1=R(n,2)+R(n+1,1);\ G_{n+1,2}=K_n.$
$R(2,n+1)=n+1=R(2,n)+R(1,n+1);\ G_{2,n+1}=\overline{K_n}.$
$R(3,5)=14=5+9=R(2,5)+R(3,4);$ for $G_{3,5}$ we can take $C_{13}$ and add all chords of length $5.$
$R(4,4)=18=9+9=R(3,4)+R(4,3);$ see this question or any textbook on Ramsey theory.


Is there an option to connect to the VPN before logging in using the SonicWall VPN Client?

Question: I read that there is an option in Windows XP and with the Cisco VPN client to logon to the VPN before logging into the machine; is it possible to connect to the VPN using the SonicWall VPN client prior to logging into a Windows 7 machine?
Answer: There is not. The only way to accomplish this would be to set this ability globally for all VPN clients which is not a good idea as it relies on cached credentials. That said, if you really, really want to do this (again, not recommended!):

VPN > Settings > WAN GroupVPN > Configure
Click the Client tab
Change the "Cache XAUTH User Name and Password Client" dropdown from
  "Never" to "Always"

Instructions copied from here.
Comment: What about logging in as a local user, connecting to the VPN, and then leaving the VPN logged in, switching users and logging in as your domain user?  It appeared to work when I tried it.
Comment: Yes, that works fine.
Comment: In the General tab of the VPN client, there's a checkbox at the bottom for it.
Comment: And really you only have to do that if the password doesn't get cached or if they can't remember the cached password.
Comment: In the client you can also specify logon scripts it should run, so that may help alleviate some of the pain with the VPN as well.
Comment: Hmm, where are those specified?
Answer: If you're using the SonicWall NetExtender (SSL VPN) client, then yes - you can connect to VPN before logging on to the domain.
After the NetExtender client is installed, you should see an additional icon appear on the logon screen, at the bottom right - I think it's next to the left of the power icon.  Enter your login details as usual, then instead of clicking the arrow next to your details, click the VPN button at the bottom right.  It will prompt you for the server name, username, password and domain for your VPN.  Fill that in, click connect and then it'll connect via VPN before it authenticates your logon.


Problems with binding to service in Android

Question: I have created a service, called LocalService, and I want to bind to it so that it can perform some action and give the result back to the calling client. I've been trying to get the example of the android dev site to work but eclipse gives a compile time error on this method:
void doBindService() {
    // Establish a connection with the service. We use an explicit
    // class name because we want a specific service implementation that
    // we know will be running in our own process (and thus won't be
    // supporting component replacement by other applications).
    bindService(new Intent(Binding.this, LocalService.class), mConnection, Context.BIND_AUTO_CREATE);
    mIsBound = true;
}

There is a red line under "Binding.this" and eclipse gives me: Binding cannot be resolved to a type. What can I do?
Answer: Just remove Binding, code should look like this:
bindService(new Intent(this, LocalService.class), mConnection, Context.BIND_AUTO_CREATE);

First parameter of Intent constructor is Context. Code above will work if you calling it from your Activity class (any instance of Activity is a Context also). If not, you can always use application context
Answer: It looks like Binding is simply class name you put doBindService() in (most likely Activity?). If your class is named otherwise either rename it to Binding or replace all Binding.this with MyClass.this or just this.


como pintar uma data vencida com css

Question:
tenho um table que mostra os vencimentos, como posso deixar a fonte vermelha ou o fundo vermelho se estiver vencido?  usando css
minha table é montada da seguinte forma

                                    <input type="checkbox" icheck ng-change="sellall()" ng-model="table1.selectAll" class="check_all" table-check-all>
                                    AÇÕES
                                    EMISSÃO
                                    VENCIMENTO
                                    PESSOA
                                    VALOR
                                    PAGO
                                    SALDO

                                    Selecionado:{{valSelecionado | currency : ''}}
                                    Pago: {{valJaPago | currency : ''}}
                                    Saldo: {{valBaixar | currency : ''}}

                                    {{totalSelect | currency: ''}}
                                    {{totalPago | currency: ''}}
                                    {{totalSelect - totalPago| currency: ''}}

                                    <input type="checkbox" icheck ng-model="tabela[$index]" ng-change="addRem($index, tabela, item)" class="check_row" table-check-row>

                                        
                                        mode_edit
                                        file_download
                                        chrome_reader_mode

                                    {{item.dt_emissao}}
                                    {{item.dt_vencto}}
                                    {{item.PessoaModel.razao | limitTo : 30 : 0}}  30">...
                                    {{item.valor | currency: ''}}
                                    {{item.vlr_pago | currency: ''}}
                                    {{item.saldo | currency: ''}}

*** tenho um campo que quando esta vencido o valor dele é "sim"
Comment: O ideal será aplicar um estilo no momento que a tabela estiver sendo montada, para não precisar percorrer toda ela depois. Ela é carregada por ajax? Compartilhe conosco os trechos relevantes de código de como a tabela é criada.
Comment: Com html e css não tem como verificar, você precisa usar javascript. Coloque as tags adequadas na sua pergunta.
Comment: você não pode usar `js`??
Comment: eu uso angular, carrego a table usando ng-repeat com o json que vem do backend, poderia uasr js sim **Nao axei opção de editar o post
Comment: `class="dt-vencida-color"` já existia antes da resposta do Mateus ser dada?
Comment: nao, esqueci de tirar, nao funcionou, pois nao valida a data
Comment: Você disse que possui um campo que armazena se a data está vencida ou não. Que campo é esse?
Comment: sim, é um campo que vem do back com o valor "sim" ou "nao" para vencido, poderia usar ele para definir a cor, só nao sei como usar, se uso com ng-show, ou ng-if, ou por css
Comment: Use o `ng-class` para adicionar a classe CSS se o valor deste campo for sim.
Comment: @alessandremartins É possível para você adicionar uma classe nesta linha? `{{item.dt_vencto}}`. Se sim, minha resposta irá validar e funcionar.
Comment: é sim Leon, vou testar, para usar o ng-class, vou precisar usar tb o ng-if ?
Comment: @alessandremartins Da forma que fiz o meu exemplo, você precisa seguir apenas o que está lá. O uso do `datejs` é importante para poder validar as datas, apenas.
Comment: @LeonFreire, não deu certo, estou usando um template admin, se nao importar o date e o jquery nao funciona, mas quando importo, da um monte de conflito.
Comment: @alessandremartins Hmmm... Da parte de conflitos, eu teria que ver como foi instalado e o que pode estar conflitando.
Answer: Segue um exemplo utilizando classes.

.dt-vencida-color{
  color: red;
}

.dt-vencida-background{
  background: red;
}

      Mateus
      25/06/2017

      Mateus
      25/06/2017

Comment: E como o código vai saber que a data está vencida? Não é pessoal @MateusVeloso, é ético explicar o motivo de um voto negativo. Responder apenas com base no título sem usar comentários deixa sujeito à isso, é minha opinião.
Comment: Não responde a pergunta. O objetivo é checar se está vencido para aplicar o estilo.
Comment: Você leu direitinho a pergunta ? ele nao pediu uma função para verificar se a data está vencida ou não.
Comment: Até porque não tem nem informação de quando a data vai estar vencida ou como a tabela é alimentada
Comment: **se** *estiver vencido*. Pra isso temos a área de comentários. Se a dúvida fosse de como aplicar um estilo qualquer, provavelmente será duplicada.
Comment: A dúvida é como aplicar o estilo, 'como pintar uma data vencida com css'
Comment: Já leu sobre votos negativos ? Antes de votar poderia ter comentado antes. Até a próxima
Answer: Seguindo fielmente apenas a informação que você passou (suas opções ficaram meio em aberto), acredito que você possa adaptar o datejs ao seu site.
Retire dos exemplos as informações mais importantes. Para seu HTML, adicione:

e adiciona a classa data onde informei.
Utilize o JS:
var dia = Date.today();

$(document).ready(function() {
  $('.data').each(function() {
    var dueDate = $(this).text();
    var due = Date.parse(dueDate);
    var compare = Date.compare(due, dia);

    if (compare == -1) {
      $(this).addClass("expirado");
    }
  });
});

E por fim o CSS:
table {
  border-top: 1px solid black;
  border-bottom: 1px solid black;
  background: aliceblue;
}

table td {
  width: 10%;
}

.expirado {
  color: red;
}

EDIT:
Vi que editou a pergunta e agora mostra a sua tabela. O meu exemplo abaixo funciona apenas se a  com a data de vencimento tiver a class data que eu sugeriria que adicionasse. Isso é possível? No caso de não ser, substitua o .data por td:nth-child(2) e veja se te atende. No seu caso específico, você também pode utilizar ele assim de forma mais completa: table#myTable tr > td:nth-child(2)

Deixo abaixo um exemplo que criei usando o Datejs:
Exemplo:
Com .data

var dia = Date.today();

$(document).ready(function() {
  $('.data').each(function() {
    var dueDate = $(this).text();
    var due = Date.parse(dueDate);
    var compare = Date.compare(due, dia);

    if (compare == -1) {
      $(this).addClass("expirado");
    }
  });
});
body {
  margin: 0;
  text-align: center;
}

table {
  border-top: 1px solid black;
  border-bottom: 1px solid black;
  background: aliceblue;
}

table td {
  width: 10%;
}

.expirado {
  color: red;
}

      28/06/2017
      14/06/2017
      ADEMIR
      500,00
      0,00
      500,00

      28/06/2017
      30/06/2017
      EXEMPLO 1
      500,00
      0,00
      500,00

      28/06/2017
      01/01/2017
      EXEMPLO 2
      500,00
      0,00
      500,00

      28/06/2017
      02/01/2018
      EXEMPLO 3
      500,00
      0,00
      500,00

      28/06/2017
      15/07/2017
      EXEMPLO 4
      500,00
      0,00
      500,00

      28/06/2017
      28/02/2012
      EXEMPLO 5
      500,00
      0,00
      500,00

      28/06/2017
      23/05/2020
      EXEMPLO 6
      500,00
      0,00
      500,00

Comment: @AndersonCarlosWoss De repente é mais simples pra quem entende de Angular, que não é meu caso. Hahaha...
Comment: Por quê não usar o Angular direto para implementar a lógica? Bem mais simples, não?
Answer: Você está utilizando Angular, então use-o para implementar a lógica necessária. Você disse que possui uma coluna que tem valor Sim/Não indicando se a data está vencida, então basta você adicionar uma classe CSS ao elemento que possuir essa coluna igual a sim. No elemento, adicione:
ng-class="{'dt-vencida': item.vencido=='sim'}"

Se o valor de vencido for "sim", então a classe dt-vencida é adicionada ao elemento. No CSS, defina a classe com color: red, por exemplo.
Veja um exemplo funcional abaixo:

angular
  .module('myApp', [])
  .controller('myController', myController);

myController.$inject = ['$scope'];

function myController($scope) {
  $scope.itens = [
    {name: "Item 1", vencido: "não"},
    {name: "Item 2", vencido: "sim"},
    {name: "Item 3", vencido: "não"}
  ];
}
.dt-vencida {
  color: red;
}

    {{item.name}}

Apenas o item 2 da lista possui o valor vencido='sim', então somente ele possuirá a classe dt-vencida e, portanto, só ele ficará na cor vermelha.
Comment: @LeonFreire Angular é só *front-end*. A lista de itens ali eu criei manualmente a fim de exemplificar, mas o valor de `$scope.itens` seria o retorno de uma requisição AJAX, por exemplo. O servidor, independente da linguagem, irá fazer a validação e definir o valor de `vencido` como `sim`, se estiver vencido, ou `não`. A cláusula `ng-class` do Angular apenas permite você adicionar uma classe ao elemento se determinada condição for satisfeita. Neste exemplo, a classe `dt-vencida` é adicionada se a condição `item.vencido=='sim'` for satisfeita.
Comment: Com esse exemplo, ele valida a data ou só funciona se ele tiver previamente definido se está expirado ou não?
Comment: @LeonFreire Deve estar pré-definido. Como o autor disse que tal valor existe, é possível considerar que a validação é feita no servidor.
Comment: Entendi. Então no caso do angular, existira essa validação sendo feita já pelo servidor e esse código iria capturar essa validação e inserir a classe? Vou ter que estudar esse Angular.
Comment: @AndersonCarlosWoss, resolvido, angular é mágico, pra quem sabe usar. Obrigado

como pintar uma data vencida com css


returning text from a function

Question: This is the code that is working but not the way i need it too, ill explain it after.
getRegisterFiles('regster1')
function getRegisterFiles(name) {
    var request = $.ajax({
        url: "/../files/Users/"+name+".ctp",
        type: "GET",
        dataType: "html"
    });
    request.fail(function(jqXHR, textStatus) {
        $('#pageLoading p').html('We have experienced a problem. Please try again later.');
        return false;
    });
    request.success(function(msg) {
        placeData(msg);
    });
}
function placeData(registerData) {
    $('#pageWrap').html(registerData);
}

So the code above gets a .ctp file and then displays it on screen.
What i need it to do
Instead of having the placeData(msg) in the success part i want to return the contents of 'msg' to a variable that will initiate the function like so,
register = getRegisterFiles('register1');

I have tried using,
return msg;

but it doesn't work... If i use return msg and then 'alert' it it comes up as undefined.
I have no idea what todo next so any ideas will be greatly welcomed. Sorry if its a complete newb mistake.
EDIT ---
This is the code i have tried, i hope it helps to show you what i'm trying to do.
var registerStep1 = null;
var registerStep2 = null;
function getRegisterFiles(name) {
    var request = $.ajax({
        url: "/../files/Users/"+name+".ctp",
        type: "GET",
        dataType: "html",
        error: function(jqXHR, textStatus) {
            $('#pageLoading p').html('We have experienced a problem. Please try again later.');
            return false;
        },
        success: function(msg) {
                return msg;
        }
    });
}
registerStep1 = getRegisterFiles('registerStep1');
registerStep2 = getRegisterFiles('registerStep2');
var tempInterval = setInterval(function() {

    if(registerStep1 != null && registerStep1 != false) {
        if(registerStep2 != null && registerStep2 != false) {
            clearInterval(tempInterval);
            placeData(registerStep1);
        }
    }
}, 100);
function placeData(registerData) {
    var tempTimer = 0;
    tempTimer = setInterval(function() {
        if(controlTimeUp != false) {
            $('#pageWrap').html(registerData);
            methodToFixLayout();
            $('#pageWrap').fadeIn("slow");
            $('#pageLoading').css("display","none")
            clearInterval(tempTimer);
        }
    }, 10)
}

Comment: That could well be it - I haven't used cake specifically but many of those frameworks implement base-url rewriting techniques. This may be one of those. Someone else on here can probably say for sure
Comment: `/..` is not valid at the start of a path since `/` means the root and `..` means up a level. You might've meant `./..`? but that can be simplified to `..`
Comment: @Basic - Thanks, i thought that too, but is works the first way i mentioned. Not sure if the fact i'm using cakephp changes anything?
Answer: You're doing it correctly.  An AJAX call can not return a value to the caller.  This is due to AJAX being Asynchronous.  (This is what the first 'A' in AJAX stands for).  The call to getRegisterFiles('register1') returns immediately.  It does not block and wait for the response from the server.  Thus it can't return any value that relates to the response from the server.
Here is another StackOverflow question pertaining to the asynchronous nature of AJAX requests:  Are AJAX calls not blocking and what is their lifespan?
Updated to add more explanation:
To observe these examples, install the FireBug extension for Firefox or use Chrome.  Open FireBug or the Developer Tools, respectively, and watch the console tab.
Here I took your code and added many log messages to reveal the order in which execution occurs.
console.log('Defining function getRegisterFiles()');
function getRegisterFiles(name) {
    console.log('enter: getRegisterFiles()');
    var request = $.ajax({
        url: "/../files/Users/"+name+".ctp",
        type: "GET",
        dataType: "html"
    });
    console.log("configuring failure handler");
    request.fail(function(jqXHR, textStatus) {
        console.log('enter: failure callback function');
        $('#pageLoading p').html('We have experienced a problem. Please try again later.');
        console.log('exiting: failure callback function');
        return false;
    });
    console.log("configuring success handler");
    request.success(function(msg) {
        console.log('enter: success callback function');
        placeData(msg);
        console.log('exiting: success callback function');
        return msg;
    });
    console.log('exiting: getRegisterFiles()');
    return "This is the return value of getRegisterFiles()";
}

console.log("defining placeData() function');
function placeData(registerData) {
    console.log('enter: placeData();  registerData="+registerData);
    $('#pageWrap').html(registerData);
    console.log('exiting: placeData()');
}

console.log("calling getRegisterFiles()');

var result = getRegisterFiles('regster1')
console.log("getRegisterFiles() finished;  result="+result);

The sequence of log messages should make the order of execution more clear.  When you call getRegisterFiles() you configure some parameters and initiate a request.  The function then returns.  You don't have any response from the server yet, so you can't act on it yet.  This is visible in the log message that contains "getRegisterFiles() finished".  Some time later a response is received from the server.  At this time, jQuery calls the function you registered as the success handler.  Although you technically can return a value from the function, since jQuery called it the return value is returned to jQuery where it is simply ignored.
Here is another variation where, as per your comment, assignment is used:
var dataFromTheServer = "An initial value";

console.log('Defining function getRegisterFiles()');
function getRegisterFiles(name) {
    console.log('enter: getRegisterFiles()');
    var request = $.ajax({
        url: "/../files/Users/"+name+".ctp",
        type: "GET",
        dataType: "html"
    });
    console.log("configuring failure handler");
    request.fail(function(jqXHR, textStatus) {
        console.log('enter: failure callback function');
        $('#pageLoading p').html('We have experienced a problem. Please try again later.');
        console.log('exiting: failure callback function');
        return false;
    });
    console.log("configuring success handler");
    request.success(function(msg) {
        console.log('enter: success callback function');
        dataFromTheServer = msg;
        console.log('exiting: success callback function');
    });
    console.log('exiting: getRegisterFiles()');
    return "This is the return value of getRegisterFiles()";
}

console.log("defining placeData() function');
function placeData(registerData) {
    console.log('enter: placeData();  registerData="+registerData);
    $('#pageWrap').html(registerData);
    console.log('exiting: placeData()');
}

console.log("calling getRegisterFiles()');

getRegisterFiles('regster1')
console.log("getRegisterFiles() finished;  dataFromTheServer="+dataFromTheServer);
placeData(dataFromTheServer);

The reason this does not work as intended is because placeData() is called (long) before the server responds to the request and so the assignment has not yet occured.  Eventually, when the response is received, the assignment does occur but since no functions are called at that time, nothing is done with that value.
Additionally, I would advise against using the assignment to a global name technique.  Using local variables is easier to debug, easier to verify correctness, and easier to reuse the code as the software project is modified to meet changing needs than using global variables.
Comment: Thanks for the reply - How would i go about doing it the other way? I don't understand why calling the function from inside the success part works but if i try and assign a variable to the data recieved it doesn't
Comment: I updated my answer to further explain the asynchronous nature and how that affects the use of assignment in the callback function.
Answer: Where are you trying the return?  It has to be in scope:
request.success(function(msg) {
    placeData(msg);
    return msg;
});

Should work, if it is outside of there, it is undefined.
Second, if that does not, I don't know if you are using another plugin, but maybe you should handle your success/failure like this?
function getRegisterFiles(name) {
    var request = $.ajax({
        url: "/../files/Users/"+name+".ctp",
        type: "GET",
        dataType: "html",
        error: function(jqXHR, textStatus) {
            $('#pageLoading p').html('We have experienced a problem. Please try again later.');
            return false;
        },
        success: function(msg) {
            return msg;
        }
    });
}

That is how it is defined here: http://api.jquery.com/jQuery.ajax/
Comment: Thanks, I've changed the code to thw way you suggested. The return msg is returning the data to the same place as the other function is, i.e its the same scope but it doesn;t work

returning text from a function


Conditioning on an extra independent random variable

Question: Suppose that $A,B,C$ are random variables such that $A$ is independent from $C$.
Does it hold that
$$
\mathbb{E}[A \mid \sigma(B)] = \mathbb{E}[A \mid \sigma(B,C)]?
$$
I tried to go to the conditional expectation wikipedia page https://en.wikipedia.org/wiki/Conditional_expectation and use the basic properties, but I was not succesful.
Answer: It's not true in general.
You can consider an example where $A$ is independent of $B$, and also $A$ is independent of $C$, but where $A$ is determined by $(B,C)$.
For example, let $B$ and $C$ be i.i.d. each taking values $0,1$ with probability $1/2$ each, and let $A=(B+C) \bmod 2$. Then $A$ also takes values $0,1$ w.p. $1/2$ each, and you get the pairwise independence properties mentioned above.
So $\mathbb{E}[A|\sigma(B)]=\mathbb{E}[A]=1/2$ with probability $1$, but $\mathbb{E}[A|\sigma(B,C)]=A\in\{0,1\}$ with probability $1$.


Solving an equation involving $e^{-x^2/2}$

Question: How do I solve this question
$$ e^{-x^2/2} = 2.25 $$
I am stuck on this question but have tried to split the exponential function
$$ e^{x^2} \cdot e^{-1/2} = 2.25 $$
$$ e^{x^2} + e^{-1/2} = 2.25 $$
Am I on the right track? If not, how do I go on from there?
I understand that if I $\ln$ the equation I would get an error since I can't square root a negative number.
Comment: $e^{ab} \neq e^ae^b$
Comment: Take the logarithm first.
Comment: First of all, we have $e^{-x^2/2}\leq1$ for all *real* $x$, and so, any solution to your equation necessarily lies in $\mathbb{C}\setminus\mathbb{R}$. Next, in general $e^{ab}\neq e^{a}e^{b}$ and $e^a e^b \neq e^a + e^b$. Finally, I changed the title to be more suggesting and reformulated some of the equations. Hope this is to your liking.
Answer: Since $x^2\geq0$, we have $-x^2/2\leq0$, and it follows (by monotonicity of $e^t$) that $e^{-x^2/2}\leq1<2.25$.
There is no real solution to this equation.


log4j and Weblogic Server : Logs not getting generated

Question: I have multiple ears,For certain Ears I want log4j details to be picked from Weblogic level and for certain application I have application level log4j.xml bundled with ear.

Copied wllog4j.jar and Log4j-x.x.x.jar to Server classpath
Added the following JAVA_OPTION in

startWebLogic.sh -Dlog4j.Configuration=Mylog4j.xml

and add the "Mylog4j.xml" in the Server Classpath
as :
<code>    SAVE_JAVA_OPTIONS="${JAVA_OPTIONS}" -Dlog4j.Configuration=Mylog4j.xml
    SAVE_CLASSPATH="${CLASSPATH}:/apps/myfiles/MyLog4j.xml"
</code>

For application which have application level log4j.xml ,I have mentioned prefer-application-packages in weblogic-application.xml
<code><prefer-application-packages>
<package-name>org.apache.log4j.*</package-name>
</prefer-application-packages>
</code>

But the logs are not getting generated for those application which has there log4j.xml
Also,Just for info : Applications are using slf4j/commons-logging and log4j
Please suggest !!!
Answer: The issue was related to classloading : Below line in weblogic-applicaton.xml does the trick.
<code>    <prefer-application-packages>
     <package-name>org.apache.log4j.*</package-name>
     <package-name>org.apache.*</package-name>
     <package-name>org.slf4j.*</package-name>
    </prefer-application-packages>
</code>
Answer: Follow below steps
1) copy log4j.jar and wllog4j.jar in server lib folder
2) copy your log4j.xml in server domain folder
3) change setDomaninEnv.xml to point to your log4j.xml file ex: LOG4J_CONFIG_FILE="${DOMAIN_HOME}/log4j.xml"
Comment: Will this definitely solve the issue? Sounds more like a comment to me!


Is it feature or human doing this?

Question: I recently had one strange experience.
I and 2 more users had answered a question and all of sudden all answers were down voted.
filter product collection by a comma-separated attribute
I then noticed that someone had marked as duplicate.
I then doubt that it might be feature that, if someone marks a qst as duplicate then all answers penalised.
My Question
I personally don't think this is a feature, but if it is then how can a user find out whether it is duplicate before answering it?
Answer: It's definitely human.
There is no trigger (that I know of) that would downvote the answers to a question that is subject to closing, because that does not make sense.
There are a lot of other questions marked as duplicate and this does not happen.
And to answer your question...how can you find out if it's a duplicate or not?... at the top of the page on the right side, there is a search functionality. Use it.
You can also google it. The questions from the stackexchange network are nicely indexed by Google.

Is it feature or human doing this?


how do I run a ruby script with an event machine listener on heroku?

Question: I have a script which uses a gem that has eventmachine which listens for an API call (it's the slack-api gem).
On my dev environment, I just run bundle exec ruby ruby_slack.rb and the console shows that it is listening. When the API call hits, then I see the stdout.
How do I have this same behavior in heroku?
I created a Procfile which has: web: bundle exec ruby slack.rb but I think it's just waiting for a request from the web app to run it.
I want this to run (and keep running) listening for events.
Thanks.
Comment: Did you try setting it up as a Rack application?
Comment: I don't know how to do that. I can google it. What does this enable me to do?
Comment: Rack acts as a web server interface to your application written in ruby. http://stackoverflow.com/questions/2256569/what-is-rack-middleware. btw, is there any way you can show what your application looks like?
Comment: How would I show it?  There's no web interface. Is just waits for an API call in a do loop. It uses a real time API that messages and it looks like event machine picks it up and then runs it. How do I enable rack in Heroku?  Looks like I could use a config.ru file but wanted to see if there were a similar example of a persistent listener.
Answer: You need a web server that responds on the port that Heroku asks it to respond and a thread for websocket processing. For example with Sinatra:
require 'sinatra/base'

module MyBot
  class Web < Sinatra::Base
    get '/' do
      'Hello world.'
    end
  end
end

Thread.new do
  # run your Slack RealTime bot here
end

run MyBot::Web

This is captured in this tutorial. Also generally try slack-ruby-bot which does all the heavy lifting for you.


Are the early versions of the Java Language Specification and VM specification available online?

Question: Oracle has the latest versions of the java specs at http://docs.oracle.com/javase/specs/ but I was unable to find the older versions. Are these archived anywhere?
Comment: The link cites both the most recent and penultimate versions; as Java SE 5.0 was a sort of watershed, how far back do you need to go?
Comment: I wanted all of them for comparison. Java SE5 corresponds to the JLS 3rd edition and 2nd edition VM spec. So there were just few earlier versions.
Comment: As @Guillaume pointed out, the archive's do not contain the specs but only the jdk, jre. The jdk documentation only contains the api javadoc.
Answer: If you are still interested - I just had the same problem and found the old specs using the waybackmachine , for instance, the JLS 1st edition is here:
http://web.archive.org/web/20041208124545/http://java.sun.com/docs/books/jls/first_edition/html/index.html
Downloading the PDF versions failed, but I can display the online HTML versions.
Answer: Yes, take a look in the Oracle Java Archive. You should be able to find everything you need there.
Comment: Those only contains JRE and JDK, not the JLS.


PHP Armazenar Imagem em variável

Question: É possível armazenar uma imagem em uma variável PHP (pega-lá por método "POST") e depois utiliza-lá para chamar a imagem em outros lugares? Assim como é feito com Strings vindas de input do HTML.
Comment: O que é esta imagem? Um arquivo enviado através do *input* `file`? Pode salvar a imagem em disco no servidor e armazenar apenas o caminho desta na variável? E que "outros lugares" seriam estes?
Comment: @AndersonCarlosWoss, acho que ele quer gravar no banco, e depois solicitar com uma URL mesmo
Comment: Na verdade era guardar em uma variável mesmo, o arquivo vem de um input do tipo file em um formulário, todas as informações vem do formulário para o PHP e ai gero um PDF, queria saber se dava para fazer isso com a imagem que vem do upload para que ela apareça no PDF.
Answer: Crie um input type="hidden" guarde o caminho da imagem no value, assim:
<input type="hidden" name="img" value="caminho_da_imagem" />

E se quiser usar futuramente no site, pode guarda-la numa variavel $_SESSION e usá-la assim:
<img src="<?=$_SESSION['img']; ?>" />

Espero que seja isto que pretende.

PHP Armazenar Imagem em variável


uninstalling and re-installing apache/php and other services

Question: I'm posting today to find out whether it is possible to install-uninstall services such as Apache from a memory stick using command prompt.
I am using xampp  for my LAMP Stack for windows.

Question 1
The reason for this, is that I travel frequently to and from various different locations. for the purpose of traveling light; my boss has requested that I take a company regulated memorystick which will be used to install/uninstall the Apache services using a pre-built batch script.
I will have access to the elevated prividgles on the computers I will be staying at. but a majority of these machines might not have the needed requirements for me to sucessfully develop.
So I was wondering if just having a folder in my tree with the exe/libraries?

Question 2
I have this batch script. The problem is, that regardless of the primary input. it automatically goes to :Install.. What is going wrong?
@ECHO OFF
@ECHO Service Management

@echo Please Select an Option

@echo 1) Install Apache and other set services
@echo 2) Uninstall Services
SET /p option = Please Select:

IF "%option%" == "1" GOTO Install
IF "%option%" == "2" GOTO Uninstall
IF "%option%" gtr "2" GOTO Error
:Install
SET /p path=Enter Path Of MemoryStick (letter only):
@echo Install
PAUSE
EXIT
:Uninstall
SET /p path=Enter Path Of MemoryStick (letter only):
@echo Uninstall
PAUSE
EXIT
:Error
@echo Error. Please Re-run
PAUSE
EXIT

Comment: How are you going to configure where your scripts are handled?
Answer: Solution. Assign your memorystick to a letter which is not usually used. Z:\ for example. Nothing will use it, unless set.
You do not need your Command prompt. You can easily copy over the necessary folders/files.. For example:

C:\xampp\apache
C:\xampp\php

over to your memory stick. Make the changes to the necessary configuration files within the Apache directory. In this case it would be:

Z:\apache\conf\httpd.conf

Move everything which says C:\xampp\htdocs to a different directory on your memory  stick. For example. Say if you wanted to use the directory WebScripts
Take this example:
#
# DocumentRoot: The directory out of which you will serve your
# documents. By default, all requests are taken from this directory, but
# symbolic links and aliases may be used to point to other locations.
#
DocumentRoot "Z:/WebScripts"

Line 191 on a stock httpd.conf
<Directory "Z:/WebScripts">
    #
    # Possible values for the Options directive are "None", "All",
    # or any combination of:
    #   Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
    #
    # Note that "MultiViews" must be named *explicitly* --- "Options All"
    # doesn't give it to you.

Line 221 on a stock httpd.conf
Create that directory within your Z:\ root. If this does not exist then you will encounter errors with installing the service from your memorystick.
Installing Apache Services
in your apache directory (Z:\Apache) you will find apache_installservice.bat and apache_uninstallservice.bat  run these with administration rights.
The services will be created and will run through the exe located at: Z:\Apache\bin\httpd.exe
which will gather all your configuration files and run an apache service with PHP Support.


Progressive measurability of a specific set related to Brownian motion

Question: Let $\{W_t: t \in R_+\} $ be a standard Brownian motion process on a given probability space.
I am interested in assessing the progressive measurability of the following set:
$Z(\omega) := \{t: W_t(\omega) \not= 0\}.$
I can see that the set $Z(\omega) $ is open and that I can therefore write it as a countable union of open sets (which would be basically the excursion time intervals between the times the process hits 0). However, I cannot seem to produce a rigorous argument to prove that the set above is progressive.
I think this example is due to Meyer or Dellacherie and Meyer and it is meant to supply an example of a process that is progressive and not optional. I have known it for some time, but now I would like to fill all the steps.
Thank you.
Comment: But what do you mean by progressive measurability of a (random) set $Z(\omega) \subset (0,\infty)$?
Comment: Could you write the definition of progressive measurability?
Comment: Hello David, progressive measurability is a special case of product measurability (a subset indeed). It requires the notion of filtration.                                                       Given a filtered space $(\Omega, {\cal F} , \mathbb{F}=\{{\cal F}_t: t \in R_+\}, P) $ a stochastic process $X_t(\omega) \equiv X(t, \omega) $ is progressive measurable if it is product measurable with respect to the $\sigma$-algebra ${\cal B}([0, t])\otimes {\cal F}_t $. It is a special case (a subset actually) of the class of product measurable, i.e., ${\cal{B}(R)\otimes {\cal F}$-measurable events.
Comment: Well I mean that it is measurable with respect to the product $\sigma$-algebra $\cal{B}([0, t])\otimes {\cal F}_t $ as a function from $[0, t]\times\Omega \mapsto R. $ You can think of it as trying to prove that $Y(t, \omega) := 1_{\{s \in R: W_s(\omega) \not 0\}} $ is measurable with respect to that $\sigma$-algebra.
Comment: I understand that, for example, if you are given the process $Y_t = 1_{\{W_t > 0\}} $ then you can create a sequence of processes such as $Y_{n,t} = (W_t \wedge 1)_+^{1/n}. $ Now $Y_{n, t} $ is continuous and adapted (for the standard filtration) and therefore progressively measurable. Then, since $\lim_n Y_{n,t} = Y_t $ we are done. So, I wonder if I could treat the example I am asking about in the same way, considering the case of $W_t < 0 $ and $W_t>0, $ separately... It gets a little fuzzy for me.
Comment: @Mauric: The set in question is actually optional (in fact, it is predictable).
Answer: This follows from two quite standard results.

All continuous and adapted processes are predictable.
All predictable processes are progressively measurable.

So $W$, and hence $Z=W^{-1}(\mathbb{R}\setminus\{0\})$, is progressively measurable. However, as predictable processes are also optional, the set in question is optional. It, therefore, does not provide an example of a progressively measurable set which is not optional.
For an example of a set which is progressively measurable but not optional, take the set of left limit points of the connected components of $Z$. That is, take the set of points $(t,\omega)\in([0,\infty)\times\Omega)\setminus Z$ for which $(t,t+\epsilon)\times\{\omega\}\subset Z$ for some $\epsilon\gt0$ (depending on $t$ and $\omega$). It can be seen that this is progressively measurable but not optional from the optional projection theorem. In fact, the optional projection of its indicator function is $0$.
Answer: Let $T>0$ and define $$Y(t,\omega) := 1_{Z(\omega)}(t) = \begin{cases} 1 & W_t(\omega) \neq 0 \\ 0 & W_t(\omega) = 0 \end{cases}$$ for $t \in [0,T]$, $\omega \in \Omega$. Then
$$[Y=0] = \{(t,\omega); t \leq T, W_t(\omega) = 0\} = [W=0] \cap ([0,T] \times \Omega)$$
Since the Brownian motion $W$ is progressively measurable, we conclude that
$$[Y=0] \in \mathcal{B}[0,T] \otimes \mathcal{F}_T$$
By definition, $Y$ does only attain the values $0$ and $1$, thus
$$Y:([0,T] \times \Omega,\mathcal{B}[0,T] \otimes \mathcal{F}_T) \to (\mathbb{R},\mathcal{B}(\mathbb{R}))$$ is measurable.
Notation $$[W=0] := \{(t,\omega) \in [0,\infty) \times \Omega; W(t,\omega)=0\}$$
Comment: Thank you Saz. You managed to make my argument rigorous. And thank you to George Lowther for his insightful reply which actually tackle the problem without even doing any "calculation".


Finding the fixed points of an autonomous vector field

Question: I'm trying to find the fixed points of the following autonomous vector field:
\begin{align*} \dot x & = \mu x - y -x(x^2+y^2)^3 \\
\dot y & = x+\mu y-y(x^2+y^2)^3 \qquad (x.y) \in \mathbb{R}^2 \end{align*}
It is clear to me that $(0,0)$ is a fixed point but I'm not sure about how to find the others.
Comment: Well, I am not surprised by the difficulty: you are after the roots of a 2-variable polynomial of degree 6.  Try to understand the geometry of the vector field (e.g., graph it) and the contribution of each summand in the right-hand sides; e.g., look also at the field: $\dot{x} = -x(x^2+y^2)^3, \; \dot{y} = -y(x^2+y^2)^3$.  This one has no zeros except at the origin.  Examine the other summands, too.  How does the field change under the transformation $(x, y) \mapsto (-y, x)$?
Answer: Convert the system to polar coordinates.


Como achar o caminho entre dois markers em Android?

Question: Possuo dois Markers colocados no mapa. Gostaria de inserir uma rota entre eles. Como posso fazer isto?

//No metodo onde implemento os markers tenho o seguninte codigo
//Tenho a baixo o primeiro Maker implementado

Marker m_person = mMap.addMarker(new MarkerOptions().position(new LatLng(Float.parseFloat(cristao_latitude), Float.parseFloat(cristao_longitude))).title("Tua Ultima Localização\n"+gestao_datas.dia(time)+","+gestao_datas.mes_nome(time)).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE)));
m_person.showInfoWindow();

//Agora tenho o segundo matker implementado
Marker marker= mMap.addMarker(new MarkerOptions().position(new LatLng(Float.parseFloat(latitude), Float.parseFloat(longitude))).title(nome));

marker.showInfoWindow();
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(Float.parseFloat(latitude), Float.parseFloat(longitude)), 10));

Comment: Qual é o seu problema?
Comment: Quero traçar um caminho entre os dois markers
Comment: o meu problema e obter um caminho entre os dois markers
Answer: Se você quer traçar  uma rota entre eles use a Polyline.
O Google tem API para isso, segue os links para estudos:
https://developers.google.com/android/reference/com/google/android/gms/maps/model/Polyline
https://developers.google.com/maps/documentation/android/shapes
Answer: Obrigado acabei conseguindo implentar com os links dados a cima, usando Polyline e api da google.
Tive que criar duas classes a primeira foi para ter as coordernadas e atravez de AsynkTask e a internet e buscar alguams coordenadas para depois marcar usando o Polyline
*GMapV2Direction (Configura dos metodos que vao buscar as coordenadas)
*GetDirectionsAsyncTask(Classe que usa ASynkTask, usando metodos da classe anterior)
*MapsActivity( Classe do Mapa)
//Inico da clase GMapV2Direction

package gabrielfm.com.findyouchurch.Dados;
import java.io.InputStream;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.google.android.gms.maps.model.LatLng;

import android.util.Log;

public class GMapV2Direction {
    public final static String MODE_DRIVING = "driving";
    public final static String MODE_WALKING = "walking";

    public GMapV2Direction() {
    }

    public Document getDocument(LatLng start, LatLng end, String mode) {
        String url = "http://maps.googleapis.com/maps/api/directions/xml?"
                + "origin=" + start.latitude + "," + start.longitude
                + "&destination=" + end.latitude + "," + end.longitude
                + "&sensor=false&units=metric&mode=driving";
        Log.d("url", url);
        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpContext localContext = new BasicHttpContext();
            HttpPost httpPost = new HttpPost(url);
            HttpResponse response = httpClient.execute(httpPost, localContext);
            InputStream in = response.getEntity().getContent();
            DocumentBuilder builder = DocumentBuilderFactory.newInstance()
                    .newDocumentBuilder();
            Document doc = builder.parse(in);
            return doc;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String getDurationText(Document doc) {
        try {

            NodeList nl1 = doc.getElementsByTagName("duration");
            Node node1 = nl1.item(0);
            NodeList nl2 = node1.getChildNodes();
            Node node2 = nl2.item(getNodeIndex(nl2, "text"));
            Log.i("DurationText", node2.getTextContent());
            return node2.getTextContent();
        } catch (Exception e) {
            return "0";
        }
    }

    public int getDurationValue(Document doc) {
        try {
            NodeList nl1 = doc.getElementsByTagName("duration");
            Node node1 = nl1.item(0);
            NodeList nl2 = node1.getChildNodes();
            Node node2 = nl2.item(getNodeIndex(nl2, "value"));
            Log.i("DurationValue", node2.getTextContent());
            return Integer.parseInt(node2.getTextContent());
        } catch (Exception e) {
            return -1;
        }
    }

    public String getDistanceText(Document doc) {
  /*
   * while (en.hasMoreElements()) { type type = (type) en.nextElement();
   *
   * }
   */

        try {
            NodeList nl1;
            nl1 = doc.getElementsByTagName("distance");

            Node node1 = nl1.item(nl1.getLength() - 1);
            NodeList nl2 = null;
            nl2 = node1.getChildNodes();
            Node node2 = nl2.item(getNodeIndex(nl2, "value"));
            Log.d("DistanceText", node2.getTextContent());
            return node2.getTextContent();
        } catch (Exception e) {
            return "-1";
        }

  /*
   * NodeList nl1; if(doc.getElementsByTagName("distance")!=null){ nl1=
   * doc.getElementsByTagName("distance");
   *
   * Node node1 = nl1.item(nl1.getLength() - 1); NodeList nl2 = null; if
   * (node1.getChildNodes() != null) { nl2 = node1.getChildNodes(); Node
   * node2 = nl2.item(getNodeIndex(nl2, "value")); Log.d("DistanceText",
   * node2.getTextContent()); return node2.getTextContent(); } else return
   * "-1";} else return "-1";
   */
    }

    public int getDistanceValue(Document doc) {
        try {
            NodeList nl1 = doc.getElementsByTagName("distance");
            Node node1 = null;
            node1 = nl1.item(nl1.getLength() - 1);
            NodeList nl2 = node1.getChildNodes();
            Node node2 = nl2.item(getNodeIndex(nl2, "value"));
            Log.i("DistanceValue", node2.getTextContent());
            return Integer.parseInt(node2.getTextContent());
        } catch (Exception e) {
            return -1;
        }
  /*
   * NodeList nl1 = doc.getElementsByTagName("distance"); Node node1 =
   * null; if (nl1.getLength() > 0) node1 = nl1.item(nl1.getLength() - 1);
   * if (node1 != null) { NodeList nl2 = node1.getChildNodes(); Node node2
   * = nl2.item(getNodeIndex(nl2, "value")); Log.i("DistanceValue",
   * node2.getTextContent()); return
   * Integer.parseInt(node2.getTextContent()); } else return 0;
   */
    }

    public String getStartAddress(Document doc) {
        try {
            NodeList nl1 = doc.getElementsByTagName("start_address");
            Node node1 = nl1.item(0);
            Log.i("StartAddress", node1.getTextContent());
            return node1.getTextContent();
        } catch (Exception e) {
            return "-1";
        }

    }

    public String getEndAddress(Document doc) {
        try {
            NodeList nl1 = doc.getElementsByTagName("end_address");
            Node node1 = nl1.item(0);
            Log.i("StartAddress", node1.getTextContent());
            return node1.getTextContent();
        } catch (Exception e) {
            return "-1";
        }
    }

    public String getCopyRights(Document doc) {
        try {
            NodeList nl1 = doc.getElementsByTagName("copyrights");
            Node node1 = nl1.item(0);
            Log.i("CopyRights", node1.getTextContent());
            return node1.getTextContent();
        } catch (Exception e) {
            return "-1";
        }

    }

    public ArrayList<LatLng> getDirection(Document doc) {
        NodeList nl1, nl2, nl3;
        ArrayList<LatLng> listGeopoints = new ArrayList<LatLng>();
        nl1 = doc.getElementsByTagName("step");
        if (nl1.getLength() > 0) {
            for (int i = 0; i < nl1.getLength(); i++) {
                Node node1 = nl1.item(i);
                nl2 = node1.getChildNodes();

                Node locationNode = nl2
                        .item(getNodeIndex(nl2, "start_location"));
                nl3 = locationNode.getChildNodes();
                Node latNode = nl3.item(getNodeIndex(nl3, "lat"));
                double lat = Double.parseDouble(latNode.getTextContent());
                Node lngNode = nl3.item(getNodeIndex(nl3, "lng"));
                double lng = Double.parseDouble(lngNode.getTextContent());
                listGeopoints.add(new LatLng(lat, lng));

                locationNode = nl2.item(getNodeIndex(nl2, "polyline"));
                nl3 = locationNode.getChildNodes();
                latNode = nl3.item(getNodeIndex(nl3, "points"));
                ArrayList<LatLng> arr = decodePoly(latNode.getTextContent());
                for (int j = 0; j < arr.size(); j++) {
                    listGeopoints.add(new LatLng(arr.get(j).latitude, arr
                            .get(j).longitude));
                }

                locationNode = nl2.item(getNodeIndex(nl2, "end_location"));
                nl3 = locationNode.getChildNodes();
                latNode = nl3.item(getNodeIndex(nl3, "lat"));
                lat = Double.parseDouble(latNode.getTextContent());
                lngNode = nl3.item(getNodeIndex(nl3, "lng"));
                lng = Double.parseDouble(lngNode.getTextContent());
                listGeopoints.add(new LatLng(lat, lng));
            }
        }

        return listGeopoints;
    }

    private int getNodeIndex(NodeList nl, String nodename) {
        for (int i = 0; i < nl.getLength(); i++) {
            if (nl.item(i).getNodeName().equals(nodename))
                return i;
        }
        return -1;
    }

    private ArrayList<LatLng> decodePoly(String encoded) {
        ArrayList<LatLng> poly = new ArrayList<LatLng>();
        int index = 0, len = encoded.length();
        int lat = 0, lng = 0;
        while (index < len) {
            int b, shift = 0, result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lat += dlat;
            shift = 0;
            result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lng += dlng;

            LatLng position = new LatLng(lat / 1E5, lng / 1E5);
            poly.add(position);
        }
        return poly;
    }
}

//Inico da clase GMapV2Direction

package gabrielfm.com.findyouchurch.Dados;

import java.util.ArrayList;
import java.util.Map;

import org.w3c.dom.Document;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.ActionBarActivity;
import android.widget.Toast;

import com.google.android.gms.maps.model.LatLng;

import gabrielfm.com.findyouchurch.Activitys.MapsActivity;

public class GetDirectionsAsyncTask extends AsyncTask<Map<String, String>, Object, ArrayList>
{
    public static final String USER_CURRENT_LAT = "user_current_lat";
    public static final String USER_CURRENT_LONG = "user_current_long";
    public static final String DESTINATION_LAT = "destination_lat";
    public static final String DESTINATION_LONG = "destination_long";
    public static final String DIRECTIONS_MODE = "directions_mode";
    private ActionBarActivity activity;
    private Exception exception;
    private ProgressDialog progressDialog;

    public GetDirectionsAsyncTask(ActionBarActivity activity)
    {
        super();
        this.activity = activity;
    }

    public void onPreExecute()
    {
        progressDialog = new ProgressDialog(activity);
        progressDialog.setMessage("Calculating directions");
        progressDialog.show();
    }

    @Override
    public void onPostExecute(ArrayList result)
    {
        progressDialog.dismiss();
        if (exception == null)
        {

            MapsActivity m=(MapsActivity)activity;
           // map M = (map)activity;
            m.handleGetDirectionsResult(result);
        }
        else
        {
            processException();
        }
    }

    @Override
    protected ArrayList doInBackground(Map<String, String>... params)
    {
        Map<String, String> paramMap = params[0];
        try
        {
            LatLng fromPosition = new LatLng(Double.valueOf(paramMap.get(USER_CURRENT_LAT)) , Double.valueOf(paramMap.get(USER_CURRENT_LONG)));
            LatLng toPosition = new LatLng(Double.valueOf(paramMap.get(DESTINATION_LAT)) , Double.valueOf(paramMap.get(DESTINATION_LONG)));
            GMapV2Direction md = new GMapV2Direction();
            Document doc = md.getDocument(fromPosition, toPosition, paramMap.get(DIRECTIONS_MODE));
            ArrayList directionPoints = md.getDirection(doc);
            return directionPoints;
        }
        catch (Exception e)
        {
            exception = e;
            return null;
        }
    }

    private void processException()
    {
        // Toast.makeText(activity, activity.getString(R.string.error_when_retrieving_data), 3000).show();
    }
}

//Inicio a classe que difine o mapa a usar etc..

package gabrielfm.com.findyouchurch.Activitys;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Path;
import android.os.AsyncTask;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.text.Html;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.Circle;
import com.google.android.gms.maps.model.CircleOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;

import org.w3c.dom.Document;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import gabrielfm.com.findyouchurch.BD.Database_Congregacao;
import gabrielfm.com.findyouchurch.Dados.GMapV2Direction;
import gabrielfm.com.findyouchurch.Dados.Gestao_Datas;
import gabrielfm.com.findyouchurch.Dados.GetDirectionsAsyncTask;
import gabrielfm.com.findyouchurch.R;

public class MapsActivity extends ActionBarActivity {

 LatLng start;
     LatLng and;
    private GoogleMap mMap;
    private Double latitude;
    GMapV2Direction md;
String titulo;
    private Double longitude;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);

    titulo=MapsActivity.this.getIntent().getStringExtra("titulo");

        getSupportActionBar().setTitle((Html.fromHtml("" + (titulo) + "")));

    //    setUpMapIfNeeded();

    }

    @Override
    protected void onResume() {
        super.onResume();
        setUpMapIfNeeded();
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_todos_mapas, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

 private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the map.
        if (mMap == null) {
            // Try to obtain the map from the SupportMapFragment.
            mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                    .getMap();
            // Check if we were successful in obtaining the map.
            if (mMap != null) {
                setUpMap();
            }
        }
    }

    private void setUpMap() {
        Gestao_Datas gestao_datas=new Gestao_Datas(getApplicationContext());

        String latitude=MapsActivity.this.getIntent().getStringExtra("latitude");
        String longitude=MapsActivity.this.getIntent().getStringExtra("longitude");
        String nome=MapsActivity.this.getIntent().getStringExtra("nome_congregacao");
        String cristao_latitude=MapsActivity.this.getIntent().getStringExtra("cristao");
        String cristao_longitude=MapsActivity.this.getIntent().getStringExtra("cristaoo");
        String time=MapsActivity.this.getIntent().getStringExtra("time");

//Cotido de circular
   //     CircleOptions circleOptions = new CircleOptions()
   //             .center(new LatLng(Float.parseFloat(cristao_latitude), Float.parseFloat(cristao_longitude)))
   //             .radius(1000); // In meters

// Get back the mutable Circle
//        Circle circle = mMap.addCircle(circleOptions);
//circle.setStrokeColor(Color.GREEN);
//        circle.setStrokeWidth(1);
start=new LatLng(Float.valueOf(cristao_latitude),Float.valueOf(cristao_longitude));
and=new LatLng(Float.valueOf(latitude),Float.valueOf(longitude));

        Marker m_person = mMap.addMarker(new MarkerOptions().position(new LatLng(Float.parseFloat(cristao_latitude), Float.parseFloat(cristao_longitude))).title("Tua Ultima Localização\n" + gestao_datas.dia(time) + "," + gestao_datas.mes_nome(time)).icon(BitmapDescriptorFactory.fromResource(R.drawable.walking_100)));
        // Marker marker=mMap.addMarker(new MarkerOptions().position(new LatLng(lt,lon)).title(nome_congregacao).icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_action_place)));

        m_person.showInfoWindow();
        Marker marker= mMap.addMarker(new MarkerOptions().position(new LatLng(Float.parseFloat(latitude), Float.parseFloat(longitude))).title(nome));

        marker.showInfoWindow();
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(Float.parseFloat(latitude), Float.parseFloat(longitude)),14));

        /*
        Polyline line = mMap.addPolyline(new PolylineOptions()
                .add(new LatLng(Float.parseFloat(cristao_latitude), Float.parseFloat(cristao_longitude)), new LatLng(Float.parseFloat(latitude), Float.parseFloat(longitude)))
                .width(5)

                .color(Color.WHITE)
                .geodesic(true));

*/

       findDirections(start.latitude,
                start.longitude,
                and.latitude, and.longitude, GMapV2Direction.MODE_DRIVING);

        }

    private class showRoute extends AsyncTask<Void, Void, Document> {
        Document doc;
        public  Polyline linha; PolylineOptions rectLine;
        public showRoute() {
            // TODO Auto-generated constructor stub
        }
        @Override
        protected void onPreExecute() {

            super.onPreExecute();
        }
        @Override
        protected Document doInBackground(Void... params) {
            Log.d("mapa", "do in background direction");
            if(linha!=null){
                linha.remove();
                Log.d("mapa", "remove poliline");
            }
            doc = md.getDocument(start, and,GMapV2Direction.MODE_DRIVING);
            ArrayList<LatLng> directionPoint = md.getDirection(doc);
            rectLine = new PolylineOptions().width(3).color(Color.RED);
            for (int i = 0; i < directionPoint.size(); i++) {
                rectLine.add(directionPoint.get(i));
            }
            return null;
        }

        @Override
        protected void onPostExecute(Document result) {
            linha = mMap.addPolyline(rectLine);

        }

    }

    public void findDirections(double fromPositionDoubleLat, double fromPositionDoubleLong, double toPositionDoubleLat, double toPositionDoubleLong, String mode)
    {
        Map<String, String> map = new HashMap<String, String>();
        map.put(GetDirectionsAsyncTask.USER_CURRENT_LAT, String.valueOf(fromPositionDoubleLat));
        map.put(GetDirectionsAsyncTask.USER_CURRENT_LONG, String.valueOf(fromPositionDoubleLong));
        map.put(GetDirectionsAsyncTask.DESTINATION_LAT, String.valueOf(toPositionDoubleLat));
        map.put(GetDirectionsAsyncTask.DESTINATION_LONG, String.valueOf(toPositionDoubleLong));
        map.put(GetDirectionsAsyncTask.DIRECTIONS_MODE, mode);

        GetDirectionsAsyncTask asyncTask = new GetDirectionsAsyncTask(this);
        asyncTask.execute(map);
    }

    public void handleGetDirectionsResult(ArrayList directionPoints)
    {
        Polyline newPolyline;
        GoogleMap mMap = ((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map)).getMap();

        PolylineOptions rectLine = new PolylineOptions().width(3).color(Color.BLUE);
        for(int i = 0 ; i < directionPoints.size() ; i++)
        {
            rectLine.add((LatLng)directionPoints.get(i));
        }
        newPolyline = mMap.addPolyline(rectLine);
    }

}

//srenn