HQL com case, sum e max

Question: Estou com uma query que está dando problema, acredito que o problema ocorra por não permitir utilizar a função max, dentro da função sum, estou correto?
Como posso contornar isso? Pois preciso somar todos os valores com exceção da última row.
Segue a query:
"SELECT new project.domain.vo.MediaPagVo(" +
                    "a.nomeUsuario, " +
                    "a.cpfUsuario, " +
                    "a.cnpjUnidadeUsuario,        " +
                    "a.nomeUnidadeUsuario,        " +
                    "a.codigoGrupoUsuario,        " +
                    "a.grupo.id AS idGrupo,         " +
                    "CASE " +
                        "WHEN MAX(a.pre) - MIN(a.pre) > 0 " +
                        "THEN ((MAX(a.pre) - MIN(a.pre)) / SUM(CASE WHEN max(a.dtRequisicao) > a.dtRequisicao THEN a.valorTotal ELSE 0 END)) " +
                        "ELSE ((MAX(a.pos) - MIN(a.pos)) / SUM(CASE WHEN max(a.dtRequisicao) >= a.dtRequisicao THEN a.valorTotal ELSE 0 END)) " +
                    "END AS mediaConsumo, " +
                    "CASE " +
                        "WHEN MAX(a.pre) - MIN(a.pre) > 0 " +
                        "THEN " + Tipo.PRE.getValue() + " " +
                        "ELSE " + Tipo.POS.getValue() + " " +
                    "END AS tipoPag) " +
            "FROM " +
                    " Pagamento a " +
            "WHERE " +
                    "a.status = " + StatusPagamento.Concluido.getValue() + " AND " +
                    "a.dataRequisicao BETWEEN :inicio and :fim AND " +
                    "( :idGrupo IS NULL OR a.grupo.id = :idGrupo) " +
                   "GROUP BY " +
                    " a.nomeUsuario, a.cpfUsuario, a.cnpjUnidadeUsuario, a.nomeUnidadeUsuario, a.codigoGrupoUsuario, a.grupo.id, " +
            "HAVING (MAX(a.pos) - MIN(a.pos) > 0 OR MAX(a.pre) - MIN(a.pre) > 0) AND " +
                    "( :tipoConsumo IS NULL OR " +
                        ":tipoConsumo = " + Tipo.PRE.getValue() + " AND " +
                        "(MAX(a.pre) - MIN(a.pre) > 0) " +
                        "OR :tipoConsumo = " + Tipo.POS.getValue() + " AND " +
                        "(MAX(a.pos) - MIN(a.pos) > 0) ) ";

O erro começou a ocorrer depois que eu modifiquei este trecho, acrescentando o case dentro do sum:
"CASE WHEN MAX(a.pre) - MIN(a.pre) > 0 " +
                        "THEN ((MAX(a.pre) - MIN(a.pre)) / SUM(CASE WHEN max(a.dtRequisicao) > a.dtRequisicao THEN a.valorTotal ELSE 0 END)) " +
                        "ELSE ((MAX(a.pos) - MIN(a.pos)) / SUM(CASE WHEN max(a.dtRequisicao) >= a.dtRequisicao THEN a.valorTotal ELSE 0 END)) " +
                    "END AS mediaPag, "

O erro retornado pelo java:
Could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
Caused by: java.sql.SQLSyntaxErrorException: ORA-00937: não é uma função de grupo de grupo simples
Meu objetivo era somar todos os pagamentos daquele período, menos o último. Infelizmente, não poderia somente mexer no filtro, pois o max(a.pre), max(a.pos) podem ser do último pagamento.
Alguém tem alguma ideia?
Answer: Este erro refere-se ao próprio Oracle:

ORA-00937: não é uma função de grupo de grupo simples

Em inglês:

ORA-00937: not a single-group group function tips

Pelo que entendi, você adicionou os campos a.dtRequisicao e a.valorTotal dentro daquele SUM. O problema é que eles não estão declarados no GROUP BY e (pelo que entendo do erro) que também precisa ser declarados no seu SELECT
Sendo assim, a correção seria adicionar eles no GROUP BY:
"GROUP BY " + " a.nomeUsuario, a.cpfUsuario, a.cnpjUnidadeUsuario, a.nomeUnidadeUsuario, a.codigoGrupoUsuario, a.grupo.id, a.dtRequisicao, a.valorTotal" +

E no SELECT:
"SELECT new project.domain.vo.MediaPagVo(" +
                "a.nomeUsuario, " +
                "a.cpfUsuario, " +
                "a.cnpjUnidadeUsuario,        " +
                "a.nomeUnidadeUsuario,        " +
                "a.codigoGrupoUsuario,        " +
                "a.grupo.id AS idGrupo,         " +
                "a.dtRequisicao, a.valorTotal,         " +

Uma dica: tente não usar Train Wreck no JPQL/HQL, ainda mais repetindo ele em vários locais na mesma consulta. Exemplo: a.grupo.id. Muitas vezes o framework JPA cria consultas esquisitas por causa disto e, em alguns casos mais complexos, ocorrem até erros para gerar a consulta SQL. A solução é explicitar o JOIN:
JOIN a.grupo grupo

E usar grupo.id.
Comment: Agradeço a ajuda, mas se eu colocar `a.dtRequisicao, a.valorTotal` no `group by`, ele não irá agrupar por esses campos também, afetando o somatório que deveria somar todas os valores independente da data de requisição(com exceção da ultima)?
Comment: @FernandoBittencourt, creio que você precisaria então usar um subselect onde está o case, fazendo um JOIN com algum valor presente no GROUP BY, algo [assim](https://stackoverflow.com/a/49526079/2387977). Não consigo dar mais detalhes da solução em si porque precisaria entender todo o contexto da sua consulta (o que seria uma outra dúvida, ao meu ver).
Comment: Optei por refatorar completamente a query, já estava em um nível de complexidade difícil de tratar.
Comment: @FernandoBittencourt, sim, parecia bem complexa mesmo :)

HQL com case, sum e max


How to set Stanford-NLP simple API in french?

Question: I'm trying to use stanford-nlp in french in netbeans.
I'm using netbeans 10.0 and stanford-nlp 3.9.2.
I'm using maven and I set this dependency in my pom.
<dependency>
    <groupId>edu.stanford.nlp</groupId>
    <artifactId>stanford-corenlp</artifactId>
    <version>3.9.2</version>
    <type>jar</type>
</dependency>
<dependency>
    <groupId>edu.stanford.nlp</groupId>
    <artifactId>stanford-corenlp</artifactId>
    <version>3.9.2</version>
    <classifier>models</classifier>
</dependency>
<dependency>
    <groupId>edu.stanford.nlp</groupId>
    <artifactId>stanford-corenlp</artifactId>
    <version>3.9.2</version>
    <classifier>models-french</classifier>
</dependency

And there is an example code in java.
Document doc = new Document(props_fr,"Ceci est mon texte en français. Il contient plusieurs phrases.");
        for (Sentence sent : doc.sentences()) {
            System.out.println(sent.parse());
        }

I expect the ouput to be (using http://nlp.stanford.edu:8080/parser/):

(ROOT(SENT(NP (PRO Ceci))(VN (V est))(NP (DET mon)NC texte))(PP (P
  en)(NP (NC français)))(PUNC .)))
(ROOT(SENT(VN (CLS Il) (V contient))(NP (DET plusieurs) (NC
  phrases))(PUNC .)))

But the actual output is:

(ROOT (NP (NP (NNP Ceci) (NNP est)) (NP (NP (NN mon) (NN texte)) (PP
  (IN en) (NP (NN français)))) (. .))) (ROOT (NP (NP (NN Il)) (NP (JJ
  contient) (NNS plusieurs) (NNS phrases)) (. .)))
Answer: Did you try to load the StanfordCoreNLP-french.properties?
Properties props = new Properties();
props.load(IOUtils.readerFromString("StanfordCoreNLP-french.properties"));
StanfordCoreNLP corenlp = new StanfordCoreNLP(props);

Annotation ann = corenlp.process("Ceci est mon texte en français. Il contient plusieurs phrases.");
Document doc = new Document(props, ann);

Comment: Thanks, it work by loading the properties an adding this: ```Annotation ann = corenlp.process("Ceci est mon texte en français. Il contient plusieurs phrases.");

        Document doc = new Document(props, ann);```


Prove that $K\le G$ of finite index and $[G:K]=[G:H][H:K]$ for infinite $G$ with $H\le G$ and $K\le H$.

Question:
Let $G$ be an infinite group. Let $H$ be a subgroup of $G$ of finite index and $K$ is a subgroup of $H$ of finite index. Prove that $K$ is subgroup of $G$ of finite index and $[G:K]=[G:H][H:K].$

If $G$ is finite, then the problem is easy. But what to do for infinite $G$?
Answer: Suppose we have an element $g\in G$. Then $gK$ is contained in the coset $gH$. If $h_1,h_2\in H$, consider $a\in gh_1K$ and $b\in gh_2K$. Then $a^{-1}b\in K$ if and only if $h_1^{-1}g^{-1}gh_2=h_1^{-1}h_2\in K$. Thus the coset $gH$ is the disjoint union of cosets $ghK$ for $h\in H$, which correspond bijectively to the cosets $hK$ for $h\in H$.
There are $[G:H] $ cosets of $H$ and $[H:K] $ cosets of $K$ in $H$. Thus there are $[G:H] [H:K] $ cosets of $K$ in $G$, hence in particular it is of finite index.


How to print ASCII white space from file

Question: I try to found on google but was useless... I use pycharm and I want to print file lines with ascii white space like "\n", "\t", "\r", etc. but all I get is just the normal string like I see it with any text editor but I want to see and that characters to to know how to reproduce that text file for some personal projects.
I do not what to make them by my self so I want to shoe them on console and to just copy-paste them.
Thanks in advance.
# Local variable
fileName = r"C:\Users\...\textFile.txt"

# Create .mcmeta file
def mcmetaMaker(fileName=fileName):
    try:
        with open(file=fileName, mode="r", encoding="utf-8") as f:
            line = f.readline()

            while line:
                print("\b{}".format(line))
                line = f.readline()
    finally:
        f.close()

Comment: How do you import your text? Can you provide some sample code?
Answer: # Local variable
fileName = r"C:\Users\...\textFile.txt"

# Create .mcmeta file
def mcmetaMaker(fileName):
    try:
        with open(fileName, mode='rb') as f:
            line = f.readline()

            while line:
                betterline = str(line)
                print(betterline[2:len(betterline)-1])
                line = f.readline()
    finally:
        f.close()

This worked for me. The 'b' in 'rb' stands for binary mode, which doesn't change the original bytes of the string.
print(line) produces b'asdf\r\n' so I converted it to string and sliced it. Hope it doesn't run too slow this way.
Comment: Will this catch spaces and tabs, say in `b'\tas df\r\n'`
Comment: Was not so usefull because for me was not show and the the horizontals space (\t), but that "rb" was opening my eyes and I fix it manually (down is my final solved problem) =]] thank's.

Oh in fact was work and your solution. the problem was on my text file. In fact I had not horizontal space, just two spaces. Thank's again.


Get MAC address from IP in C

Question: I need to provide a function that assembles a UDP packet to send when my user provides local and remote IP:Port pairs. I have an Ethernet card API which sends a Ethernet frame for me, do I have to fill a complete Ethernet frame which contains MAC addresses, IP and UDP.
Question: Given an IPV4 address on the Internet, how to find out the MAC address the IP corresponds to so that I can fill it in the Ethernet frame header. How can I use C to lookup this from the router's ARP table. Should I send out an ARP packet to my router (I do not know how to do this either).
When I call UDP sendto(), who fills the MAC address in the ethernet frame? How does that accomplishes?
Comment: The operating system's network stack fills it in.  If you build the packets yourself (via a raw socket), then you have to emulate that part of the network stack.  As my link above shows, Linux exposes the internals of its network stack's ARP table via the proc file system.  Another API to the network stack on Linux is called [Netlink](http://en.wikipedia.org/wiki/Netlink).
Comment: There is no portable C interface for this.  For Linux, see [here](http://stackoverflow.com/questions/15407354/python-get-mac-address-of-default-gateway) for example.
Comment: @indiv When I call UDP ``sendto()``, who fills the MAC address in the ethernet frame? How does that accomplishes? Thank you a lot.
Comment: @indiv Thank you a lot. Your comment and the answer of this post helps me realize I was probably doing things in the wrong way. I will talk to senior dev and we may just fill the destination MAC by hand. Considering our use case, this is doable.
Answer: The short answer is: You can't.
The MAC address only has meaning on the local network. There is no way to ask a remote IPv4 endpoint (not on your network), what its MAC address is. If you want to send a UDP packet to a remote endpoint, use your OS socket interface to send to that IPv4 address. It will take care of the details.
Based on your comments below, if you have an interface to send Ethernet frames, then you will need to look up the MAC address of your local IPv4 gateway address (by sending an ARP request). The MAC address of the gateway is what you put in the Ethernet frame. The MAC address of the destination endpoint does not go in the Ethernet frame.
Comment: @PengZhang: The OS socket layer fills in the MAC address from the ARP table, if it exists. If not, then the socket layer sends an ARP request to the network to request the MAC address for the IPv4 address of the gateway. Then it sends the Ethernet frame containing the UDP packet using the MAC address of the gateway.
Comment: I think my question is misunderstood. I need to assemble a UDP packet. Just like the BSD socket does.
Comment: Even if you want to do that, you still don't need the MAC address of the remote endpoint. UDP packets do not contain MAC addresses, they contain IPv4 addresses.
Comment: That is the purpose of the gateway. It uses the IPv4 address to decide what to do next. If the gateway is connected directly to the destination network, then it fills in the MAC address of the destination (using an ARP request if necessary) and then sends the UDP packet to its destination. If the gateway is not directly connected to the destination network, then it sends the UDP packet up to the next gateway, which repeats the procedure.
Comment: @PengZhang:  Sounds like you want the [gateway](http://en.wikipedia.org/wiki/Gateway_address) address.  The address could be specific for a route, or if no route is specified, the default gateway.  And then you have to deal with multiple network interfaces...
Comment: @GregHewgill I just clarified my post. I need MAC to fill in the Ethernet header.
Comment: @GregHewgill When I call UDP sendto(), who fills the MAC address in the ethernet frame? How does that accomplishes?
Comment: @GregHewgill Thank you. I am confused by "Then it sends the Ethernet frame containing the UDP packet using the MAC address of the gateway.". My current code fills the MAC address of the other end and sends it successfully. The two endpoints are connected through a router. And in the network course, what I learned is filling the MAC of the destination. If I fill the MAC of the gateway, when the packet gets to the gateway, how the gateway will handle it?
Comment: @GregHewgill Thank you. Another question, if I directly and correctly fills the destination MAC address and IP, the gateway will just pass it to the next gateway, right? Could you recommend me a book on network. I studied math at school but my current project is developing over ethernet card API.
Comment: [TCP/IP Illustrated](http://www.amazon.com/TCP-Illustrated-Vol-Addison-Wesley-Professional/dp/0201633469) is the book from which I learned about the IP protocol stack. It's excellent.
Answer: Your operating system does that. How?:
Your operating system fills the macaddress for the host that you send something to or the router that is between the host.
What is the macadress when you send something in your local network
That is the host's computer macadress. How to get the macaddress from only a ipaddress?
You broadcast the ipadress to the network for macadress. Send an ARP packet to macadress FF:FF:FF:FF:FF:FF with your ipadress and wait for response. Everyone on your network will see your packet. Everybody ignores the packet except the computer with your target ip. He will response with the macaddress. Take a look at wiresharp how an ARP packet is constructed. For speed, it is important that you cache the macaddress with the ipaddress for later use.
What is the MAC address when you send/recive something outside your network
You can't get macaddresses from computers outside your network. And there is no reason to do that. If you send a packet outside your local network the MAC adress is the address of your NAT router and the ipadress outside your network. How to get the MAC address for your NAT router you just send an ARP packet with the router's IP address. In the response  contains the NAT mac address. If you have the macaddress for the router you can send a packet outside your network. The NAT router will then send your packet out over the WAN side of the router.

Get MAC address from IP in C


Which proportions are particularly high or low - compare confidence intervals, or logistic regression?

Question: I have a large database of binary decisions (accept or reject), broken down by state of the applicant, so that for each state I can calculate a proportion of positive decisions. e.g.
New York - 0.21% accepted
Washington - 0.17% accepted
California - 1.25% accepted
Oregon - 2.01% accepted
Alaska - 0.54% accepted
etc...

As you can see, the proportion accepted is sometimes very low, and therefore if I calculate confidence intervals around them (using a binary distribution to bound the intervals between 0 and 1), the interval width can be quite large.
I want a way of determining which states have a particularly high proportion or accepted decisions. As a start, I calculated the overall national proportion, with confidence intervals, and looked whether the confidence intervals of each state overlapped with the overall national confidence intervals. If they didn't I thought this would indicate that state had a proportion significantly higher or lower proportion than average.
However, I'm worried that the overall national proportion might be disproportionately influenced by certain states where a large number of decisions were made.
Also, is my approach a bit simplistic?  Should I instead use logistic regression to see whether state is a significant predictor of decision, and if so, do a post-hoc test to see which states differ? If so, what post-hoc test could I do?
Many thanks
Answer: Consider two possible approaches:

A random effects model or penalized maximum likelihood estimation.  Either of these will shrink effects towards the grand mean proportion in order to increase precision of estimates and help avoid overinterpretation.
Use the bootstrap to get a 0.95 confidence interval for the rank of each proportion across the states.  This will provide evidence for separability of the estimates, incorporating the true difficulty of the task.  If the state with the highest proportion has a rank of 50 but a confidence interval for the rank of 10-50 you are trying to split hairs.

For individual confidence intervals use the well-performing Wilson interval, which is automatically bounded in $[0,1]$ (see e.g. the R Hmisc binconf function).
Comment: Thanks. I've not used a random effects model before, but upon reading it sounds like the right thing to do. Now to figure out how to do it...


Solving integral with substitution gives wrong result

Question: I want to solve the integral:
$$ \int_{-\infty}^{\infty} \frac{x^2}{(1+|x|^3)^4} \ dx.$$
I thought I could solve that via the substitution $u=1+|x|^3$ since then one has the integral:
$$ \int_{-\infty}^{\infty} \frac{1}{3u^4} \ du.$$
But that seems to be wrong (probably the substitution does not work here since it is not differentiable at 0), and that's why this integral is 0, but it should be $\frac29$. So how do I solve this correctly?
Comment: I think your substitution is (twice) differentiable at zero, no? In any case, the problem was that $u=1+x^3$ for $x>0$ and $u=1-x^3$ for $x<0$
Answer: The function is even, so rewrite the integral as
$$\int_{-\infty}^\infty \frac{x^2}{(1+|x|^3)^4}dx = 2\int_0^\infty\frac{x^2}{(1+x^3)^4}dx$$
Now try your substitution.
Comment: Thanks, I tried this before, but without changing the lower border to $1$ after the substitution. Then it worked perfectly!
Answer: Since $x^2dx=1/3d(x^3)$ using $u=x^3$ we have
$$\int_0^\infty \dfrac{x^2}{(1+x^3)^4}=\int_0^\infty1/3\dfrac 1{(1+u)^4}du=1/3\left.\left( -1/3 \dfrac1{(1+u)^3}\right)\right|=1/9.$$
Now in your integral the function is even, so the answer is just $2\cdot 1/9=2/9$


Attribute about not allowed on element article at this point

Question: While i checked the markup of my drupal-7 site in http://validator.w3.org/check
it shows me a error:

error Details:
Attribute about not allowed on element article at this point.

I have checked my markup as well as all the functionality that are running properly. Why i am getting this error?
Comment: This is a problem with HTML. Version you are using does not allow for syntax you used at this point. The fact that it looks good and works good is not even near enough to make page valid. But pure HTML discussion is, as far as I understand, supposed to happen on stackoverflow.com, and problems with validator and certification on webmasters.stackexchange.com
Comment: Related (if not a duplicate): http://drupal.stackexchange.com/questions/72390/is-drupal-following-w3c-standards/72393#72393
Comment: To expand slightly on the previous comment, if you are using a non-custom Drupal theme (i.e. premium or contrib), I would suggest it might belong here or in the issue queue for that theme. However, you have not mentioned this so as @Mołot said, this does run the risk of being off topic. Perhaps you coul expand the question to say whether you are using a custom theme, base theme or contrib/premium theme.
Comment: I am using a sub theme of bootstrap theme.
Answer: It looks like there is a markup error somewhere whereby you have an
 tag with an about attribute (i.e.
).
I would imagine the site is working fine as the attribute will just be ignored if it's not applicable, so I'd find the page and line from the validator error and double check your markup.
You could also try running it past the newer HTML5 W3C validator at http://validator.w3.org/nu/ just in case.
Comment: Yes it is rendering from the node.tpl.php from this
Comment: Could you clarify?  That comment doesn't make sense to me.


Check for Special Characters in C

Question: I got some help on how to see if a "string" in C contains a specific character. In short:
if(*s=='x') { //Where x is some character
    //Do something
}

Now, as far as I can see, this works for letters in the English alphabet (a-z, A-Z).
However, how can I check if the current character equals a special character (such as æ, ø, or å)?
Comment: Do you know what encoding you are using for your strings? This will work for single-byte encodings (e.g., Latin1, Windows-1252 or MacRoman) and (providing `*s` is of the correct type) for `wchar` or `tchar` Unicde strings, but not for variable-length multibyte encodings such as UTF8.
Answer: Just compare to the ASCII code of the character:
if(*s==10) { //Where 10 is the ASCII code of the special character
    //Do something
}

You can find your ASCII code here: http://www.asciitable.com/
Comment: The most meaning we can eke out of "Extended ASCII" is 1) not ASCII and 2) one byte encoding, therefore <= 256 characters. That narrows it down to several dozen character sets. At least when you say "ASCII" we know exactly what it means (it's probably wrong, though).
Comment: I don't think "ASCII" is what the OP is looking for, as he is already covering that.
Comment: Character such as `æ, ø, å` are not ASCII codes.  [American Standard Code for Information Interchange](http://en.wikipedia.org/wiki/ASCII)
Comment: Sure they are æ =145  , ø = 237 , å = 134
They are Extended ASCII Codes
Comment: and, of course, 3) a superset of ASCII with identical encodings for the common characters. Still doesn't narrow it down much.
Answer: In most cases you should be using a function for this: strchr for looking for a single byte, or strstr for looking for more than a single byte.
Also, in general C does not know about characters, it only knows about bytes.  A special character may be a single byte - æ in iso8859-1 encoding is \xe6, for example - or it may be more than one byte: the same character in utf-8 encoding is the 2-byte sequence \xc3\xa6.
To search a utf-8 encoded string for æ you could use
strstr(s, "\xc3\xa6")

Answer: Compare the character to the actual value (as long as the value is between 0 and 255).
See the æ wiki page for particular values.  So

if (*s == 0xe6)

for lower case

if (*s == 0xc6)

for upper case

Check for Special Characters in C


Order style-sheet list when adding custom one via template_preprocess_page()

Question: I'm using phptemplate_preprocess_page() to add a set of style-sheets which are only needed for a certain content type.
function phptemplate_preprocess_page(&$variables) {
  if ($variables['node']->type == 'example') {
    drupal_add_css(path_to_theme() . '/css/example.css');
    $variables['styles'] = drupal_get_css();
  }
}

The problem is that my added style-sheet is added to the top of the list, which results in undesired behavior. For example, let's say that in my main theme style-sheet I define the font-size of p to be 11px, but in my example.css for this specific content type I need it to be 15px. The main style-sheet is added via the .info file of the theme.
It seems I can only think of icky ways to add my specific style-sheet at the bottom of the list, or at least below the theme default ones.
Is there any proper way to order them?
Answer: OK, of course, a few moments after adding the question I saw what was wrong. Since I did not specify the type it added my style-sheets it added it to the end of the modules. I now added the theme type and it was added at the end of the list.


Similarity of $3\times3$ matrices via Jordan canonical form

Question: Let matrices
$$A=\begin{bmatrix}
-3&3&-2\\
-7&6&-3\\
1&-1&2
\end{bmatrix},\quad
B=\begin{bmatrix}
0&1&-1\\
-4&4&-2\\
-2&1&1
\end{bmatrix},\quad
C=\begin{bmatrix}
0&-1&-1\\
-3&-1&-2\\
7&5&6
\end{bmatrix},\quad
D=\begin{bmatrix}
0&1&2\\
0&1&1\\
0&0&2
\end{bmatrix}
$$
My goal is to determine which of them are similar to each other. First, we observe that
$$\det(A)=\det(B)=\det(C)=4\neq\det(D)=0$$
Thus, $D$ cannot be similar to any of $A,B,C$. $\det(\lambda I-A)=0$ and similarly for $B,C$. Denote $\sigma(X)=\operatorname{spectrum of matrix }X$. With a slight abuse of notation, to denote that $\lambda_2=2$ has algebraic multiplicity of $2$, I found
$$\sigma(A)=\sigma(B)=\sigma(C)=\{\lambda_1=1,\lambda_2=2,\lambda_2=2\}$$
This means that all of them have the same Jordan Canonical Form which is (up to permutations of the diagonal Jordan blocks)
$$
J_A=J_B=J_C=\begin{bmatrix}
\lambda_1&0&0\\
0&\lambda_2&1\\
0&0&\lambda_2
\end{bmatrix}
=
\begin{bmatrix}
1&0&0\\
0&2&1\\
0&0&2
\end{bmatrix}
$$
Hence, $A,B,C$ are similar.
Is this justification correct? If yes, is there any faster way/trick to get to this result? Finding the eigenvalues by solving a 3-rd degree equation took me some time.
Comment: well, $B$ diagonalizes  the minimal polynomial is not the same as the characteristic polynomial. $x^2 - 3 x + 2$ Just check $B^2 - 3 B + 2I$
Comment: No, it is not: a n eigenvalue can have multiplicity $2$, yet be diagonalisable. This is the case if and only if the *geometric multiplicity*  (i.e. the dimension of the corresponding eigenspace) is equal to the *algebraic multiplicity*.
Answer: $B$ diagonalizes
$$
\frac{1}{2}
\left(
\begin{array}{rrr}
4 & -2 & 2 \\
-4 & 3 & -2 \\
-2 & 1 & 0 \\
\end{array}
\right)
\left(
\begin{array}{rrr}
1 & 1 & -1 \\
2 & 2 & 0 \\
1 & 0 & 2 \\
\end{array}
\right) = I
$$
$$
\frac{1}{2}
\left(
\begin{array}{rrr}
4 & -2 & 2 \\
-4 & 3 & -2 \\
-2 & 1 & 0 \\
\end{array}
\right)
\left(
\begin{array}{rrr}
0 & 1 & -1 \\
-4 & 4 & -2 \\
-2 & 1 & 1 \\
\end{array}
\right)
\left(
\begin{array}{rrr}
1 & 1 & -1 \\
2 & 2 & 0 \\
1 & 0 & 2 \\
\end{array}
\right) =
\left(
\begin{array}{rrr}
1 & 0 & 0 \\
0 & 2 & 0 \\
0 & 0 & 2 \\
\end{array}
\right)
$$
Regardless, this was going to require a fair amount of work by hand. I am not so much a fan of doing things quickly as of doing things well and including alternate methods that may indicate errors. In this case, one may confirm that $B^2 - 3 B + 2 I = 0.$ For $A$ and $C$ the minimal polynomial agrees with the characteristic polynomial, which means that each eigenvalue occurs in a single Jordan block, and since $2$ has higher multiplicity this means they do not diagonalize. In contrast, for $B$ we see that $2$ must occur in more than one Jordan block. In fact, there are two, each dimension one, meaning there is a basis of two eigenvectors for eigenvalue $2.$ I have typed in one way  to diagonalize $B.$ The matrix on the right has columns that are all eigenvectors


Multivariate probability density - Help with an integral

Question: I'd like some help solving this problem about multivariate probability densities.

Let the random variables X and Y have the joint density f(x,y) = 1/y
  for 0 < x < y < 1 and 0 otherwise. Find P(X+Y > 0.5).

My problem is that any way I know of to set up the double integral, I get an integral of 1/y (or, switching to variables s and t, 1/t) with a lower bound of integration of 0, but such an integral doesn't converge. If I didn't know that the answer was 0.6534, I would assume that the lower bound of integration in the vertical direction should be x, but that produces a result that includes ln x, not a constant.
I emailed my professor asking for help, but her response was not helpful to me. Maybe it will be to you. She said, "you missed the condition for the density to be positive, so you have to integrate over a different area. And to make things simpler, calculate P(X+Y<0.5) and subtract from 1."
I understand why it's often easier to find a complementary probability and subtract that from 1, but here I don't see how it would help because I don't know how to make the lower bound of integration in the vertical direction anything other than 0 or x. I must be trying to integrate over the wrong region.
The region that I think is correct is the region of the unit square above the line x+y=0.5. That is, a trapezoid with vertices (0, 0.5), (0, 1), (1, 1), (1, 0), and (0.5, 0).
How would you define the region differently, or how would you integrate differently? Thanks so much for your help.
UPDATE: I figured out that I did indeed have the wrong region of integration. When my professor said I missed the condition for the density to be positive, she was implying that I needed to enforce the condition that Y > X. So I needed to add the line y=x to my graph and restrict the integration to the area above it (but still below y=1, obviously).
Thus, the region of integration became the quadrilateral with vertices (0, 1/2), (0, 1), (1, 1), and (1/4, 1/4). The only way I know how to do integration requires dividing this region into two sub-regions. To divide them horizontally, with dx on the outside and dy on the inside, these are the two double integrals (for the left and right sub-regions, respectively):
$
P(X+Y>0.5) = \int_0^.25 \int_{0.5-x}^1 \frac{1}{y}\,dy\,dx + \int_{0.25}^1 \int_x^1 \frac{1}{y}\,dy\,dx
$
The left integral equals 0.25, and the right integral equals 0.75 + 0.25(ln 0.25), for a total of 1 + 0.25(ln 0.25) = 0.6534.
Comment: I divided the trapezoidal region into two regions: a top rectangular region from y=0.5 to y=1, and a bottom trapezoidal region from y=0 to y=0.5. The top rectangle gives me no problems. For the bottom trapezoidal region, I did the x-direction (switching to variable s) on the inside and the y-direction (variable t) on the outside. The inner integral was from 0.5 - y (the line x+y=0.5) to 1, and the integrand was 1/t ds. The outer integral was from 0 to 0.5, with an integrand of (1+2y)/2t dt.
Comment: Here, I tried to code it in LaTex. It looks almost just like this:

$\int_0^{0.5}\int_{0.5-y}^{1} \frac{1}{t} \;ds\;dt$
Comment: [Draw a picture](http://stats.stackexchange.com/questions/72276).  Another illustrated example is at http://stats.stackexchange.com/a/95725.
Answer: The use of multiple integrals requires keeping track of all constraints. A neat approach works through indicators functions, using as many as needed. The probability $\mathbb{P}(X+Y > 0.5)$ can be represented as
\begin{align*}\underbrace{\iint_{[0,1]^2}}_{\substack{\text{maximum range}\\\text{for $x$ and $y$}}} \mathbb{I}_{x+y>0.5}\,\mathbb{I}_{0<x<y<1}\,\frac{1}{y}\text{d}x\text{d}y&=\underbrace{\overbrace{\int_0^1\,\int_0^y}^{\substack{\text{outer limits:}\\\text{range of $y$}}}}_{\substack{\text{inner limits:}\\\text{conditional}\\\text{range of $x$}}} \mathbb{I}_{x+y>0.5}\,\frac{1}{y}\text{d}x\text{d}y\\
&=\int_0^1\,\int_0^y \mathbb{I}_{x>0.5-y}\,\frac{1}{y}\text{d}x\text{d}y\\
&=\int_0^1\,\int_{\max(0,0.5-y)}^y \underbrace{\mathbb{I}_{y>0.5-y}\,}_{\substack{\text{as $x<y$}\\\text{and $x>0.5-y$}}}\frac{1}{y}\text{d}x\text{d}y
\end{align*}
and
\begin{align*}\int_0^1\,\int_{\max(0,0.5-y)}^y \mathbb{I}_{y>0.5-y}\,\frac{1}{y}\text{d}x\text{d}y&=\int_0^{0.5}\mathbb{I}_{y>0.25}\,\int_{0.5-y}^y \frac{1}{y}\text{d}x\text{d}y+\overbrace{\int_{0.5}^1\,\int_{0}^y}^{\substack{\text{no constraint on}\\\text{$y$ when $y>0.5$}}} \frac{1}{y}\text{d}x\text{d}y\\
&=\int_{0.25}^{0.5}\,\int_{0.5-y}^y \frac{1}{y}\text{d}x\text{d}y+\int_{0.5}^1\,\int_{0}^y \frac{1}{y}\text{d}x\text{d}y
\end{align*}
From there you should be able to conclude about the value of this probability, $1-\log(\sqrt{2})$.
Comment: Thank you. I've never heard of indicator functions before, but that roughly makes sense.
Comment: @xian, No, thank you. I did want to update my post indicating that I had the region of integration wrong and suggesting a more "basic" way to solve it (without indicator functions), but I wasn't sure if that was frowned upon if someone else has already given a correct and complete answer.


Software needed to change a church hymn for organ to a string. Can it be done?

Question: I am looking for software that can convert a MIDI file in organ to a string or trumpet etc. automatically. Is there such a program?
Any help is appreciated.
Comment: Any MIDI sequencer should be able to do this.
Comment: Voted to reopen. I as far as I can see, this question already "describes the required function and setting in which the equipment will be used, and asks what the OP should look for to achieve that". There's no suggestion they're looking for particular recommendations; as per CL's comment, they may just need to know what a "sequencer" *is*.
Answer: Most MIDI sequencers will be able to do this. Generally, I would expect that you will need to do something like this:

load or import the MIDI file into the MIDI sequencer
play the MIDI file and see if it plays as you would expect in its original state. You might have to alter the sequencer's output or MIDI mapping settings to make sure it is playing through an appropriate MIDI synthesizer, such as (on Windows) "Microsoft GS wavetable synth" - or, of course, something better!
Change the voice settings of the tracks for which you want to change the sound. Your sequencer may help you by telling you which numbers correspond to which voices, or this list may help: https://www.midi.org/specifications-old/item/gm-level-1-sound-set
Save or export the file as a General MIDI file

The file should now have different "program change" data at the start, which will cause the notes to play as a different sound.


Problema com loop for em JavaScript

Question: Quero que o loop abaixo for mostre todos os números pares que sejam menores ou iguais a ele, mas só consigo fazer com que ele mostre o último número. Se eu digito 40 e ele retorna só 2.

    <input type="number" id="num1" placeholder="Informe o primeiro número: ">
    <button onclick = "pares()">Numeros Pares</button>

Answer: A primeira expressão do for está gerando um valor booleano, portanto não serve como inicializador. A inicialização deve considerar se o número digitado é par ou não, sendo ímpar deve diminuir 1 da variável para torná-la par e facilitar as contas.
Outro problema é que está substituindo o valor na div, então só o último permanece, tem que ir adicionando cada resultado.

function pares() {
    var num1 = parseInt(document.getElementById("num1").value)
    for (num1 -= num1 % 2; num1 > 0; num1 -= 2) document.getElementById("resp").innerHTML += num1 + "
";
}
<input type="number" id="num1" placeholder="Informe o primeiro número: ">
<button onclick = "pares()">Numeros Pares</button>

Coloquei no GitHub para referência futura.

Problema com loop for em JavaScript


PuTTY alternatives to work faster and more efficiently - Windows

Question: Using putty as my ssh client for my different servers.
I am far from that level that everything is in the spine which means I quite often need to Google for information on how I perform various actions.
My knowledge is pretty good so I usually know what I want to do and what it means, but to wear it all inside and out of the head will take several years, it is more or less like learning a new language.
As I sit here with putty, I think that there must be smarter alternative to this. Using putty is a bit like code in notepad, it works but it is certainly nowhere near the most efficient and smartest solution, so instead I use Aptana etc and can work x5 faster.
Are there any alternatives to putty that can help me to work faster and more efficiently?
Running windows and my servers run mostly CentOS and Debian
Answer: Use a Linux desktop.
Every time I attempt to do something with PuTTY I am utterly frustrated by the constraints imposed on me, both by PuTTY and by Windows. If you have to manage Linux boxes, doing so from a Linux box gives you much more opportunity for better integration. The mouse works as expected, for instance, while it doesn't in Windows. Transferring files is more straightforward. And so on...
Comment: @HopelessN00b is a solution but not a good solution, I know about this kind of things but i wanted to know if there is a better solution out there !
Comment: I have a Windows desktop, with a Linux desktop running in VMware Workstation, and Dexpot for Linux-style virtual desktops. So I switch between Windows and Linux desktops with a single mouse gesture or keystroke. It isn't that hard.
Comment: Problem is that am working on Windows and changing to linxus is not an option. Need windows for many other thing's. Dual boot is not either an option, often am doing things on windows and need to do some fix on one of the servers, so closing everything down to reboot to linux would not work.

So the 2 options left is running it on a Virtual machine or remote connect to a Linux machine and from that remote connect to target machine, not really optimal either.

Would really wish there was a solution that did not require compromises
Comment: @MathiasÅsberg Get a second machine?  One box running Windows, one box running Linux.  Problem solved.
Answer: Try SuperPutty!  It really depends on what you mean by "help me to work faster and more efficiently." In what sense?
Comment: I use SuperPutty. Then on the various servers I manage I writes various bash scripts which I use to do the common tasks for the server.
Comment: In every possible way, Like pre setup commands or the function to build and save my own. Think about putty as notepad, then i want something like Aptana
Comment: If you're missing IDE-like features such as completion, see [An Introduction to Programmable Completion](http://tldp.org/LDP/abs/html/tabexpansion.html) in the Advanced Bash Scripting Guide, and its references. Beyond that, you need to think about scripting (bash or other shells, Perl/Python/Ruby) and some kind of configuration management tool (Puppet, Chef, etc.).


Set a property of an object in a Expect.Call

Question: It's kind of hard to explain what I'm searching for but my example should clarify it.
I have next code:
var schedule = ScheduleUtil.CreateScheduleDto(user, user);
Expect.Call(() => _scheduleRepository.Save(schedule));

Now, what I want to do is when this Save call is made, the schedule.id property should be set to another value (1 for instance).
I do not want to mock schedule. Can this be done? The Save method doesn't return a value, so that's not a possiblity, but I do want the object schedule to be modified.
UPDATE: Maybe a small example will clarify what I exactly want.
Say there's a class with a method Save:
public void Create(Entity entity)
{
    //entity is saved to database
    //entity.id is updated with the created id in database
}
So, before the create, entity.id is -1, after the create it is > 0.
Now, there's a service that uses this Create. Code contracts on this service method say that before it is called, the entity must have an id equal to -1, after it is called it must have an id > 0 (preconditions and postconditions).
So, what I need is something like this:
var entity = new Entity(); //id == -1
Expect.Call(() => _instance.Create(entity);
//Now the entity.id should be a random number > 0. This is what I need, to have Rhino Mocks update the id of entity to a given integer. Is this possible?
Answer: No.  If you're not mocking the _scheduleRepository, Rhino Mocks doesn't know about it.  Why don't you want to mock the _scheduleRepository?
EDIT: Ok, now I see what you want to do.  Use the "WhenCalled" extension method to define code to be executed when Rhino.Mocks intercepts the call.  Something like this should work:
_scheduleRepository.Expect(s => s.Save(schedule)).WhenCalled(a => ((Schedule) a.Arguments[0]).Id = 1);

Comment: I am mocking the _scheduleRepository. But when I call the Save(schedule), I also want Rhino Mocks to change the id of the schedule.
Comment: I added a small example to clarify what I need.
Comment: @Lieven If you can mock the "_instance" variable and the "Create" method is virtual, you can use the expectation I show above to set the entity's Id to anything you want.  It's not clear to me why this wouldn't work.
Comment: Ah, I'm terribly sorry, I hadn't seen your EDIT. Thx. Off course this is exactly what I was looking for.


Prove that the graph is connected

Question: I was wondering if someone can help me understand how prove that this graph is connected.
Given a graph with n vertices, prove that if the degree of each vertex is at least $(n − 1)/2$ then the graph is connected.
So far I know that about connected graphs:
An undirected graph is called connected if there is a path between
every pair of distinct vertices of the graph
The distance between two vertices in a graph is the length of
the shortest path between them.
The diameter of a graph is the distance between the two vertices
that are farthest apart.
Comment: Possible duplicate of http://math.stackexchange.com/questions/927151/proving-graph-connectedness-given-the-minimum-degree-of-all-vertices
Comment: @BhaskarVashishth I checked that out, it didn't help me, but thanks.
Comment: Note that, if $n$ is even, the graph is not just connected but, by Dirac's theorem, it has a Hamiltonian cycle.
Answer: Call the $n$-vertex graph $G$. Choose any two vertices $u,v \in V(G)$. We want to find a $(u,v)$-path. Now if $u = v$ or $uv \in E(G)$, then we are done. So we may assume that $u \neq v$ and $uv \notin E(G)$. We will prove the stronger claim that there is some path of the form $u \to w \to v$ for some $w \in V(G)$.
Consider the neighbourhoods of each endpoint:
\begin{align*}
A &= \{a \in V(G) \mid ua \in E(G)\} \\
B &= \{b \in V(G) \mid vb \in E(G)\}
\end{align*}
It suffices to show that these neighbourhoods overlap (if they do, then we can just pick any $w \in A \cap B$ and we are done). Indeed, observe that:
\begin{align*}
|A \cap B|
&= |A| + |B| - |A \cup B| \\
&= \deg(u) + \deg(v) - |A \cup B| \\
&\geq \frac{n - 1}{2} + \frac{n - 1}{2} - (n - 2) \\
&= 1
\end{align*}
Hence, we conclude that $A\cap B \neq \varnothing$, as desired. $~~\blacksquare$
Comment: The only formula I used here was the set theoretic inclusion-exclusion formula for counting stuff in unions/intersections. The main trick used here was to associate "degrees" with "neighbourhoods" and to think about how we could force a **common neighbour**. This is a standard graph theory trick.
Comment: thanks! so what are standard formulas that I should I know when I approach questions likes these?
Comment: This looks very complicated. Is something wrong with David's/my answer?
Comment: @StefanPochmann It is precisely the same argument. My approach is direct, whereas yours and David's is by contradiction.
Comment: Brilliant answer. On a slightly related note, are there properties that allow one to prove a component of a graph? (Say graph G(V,E), and we want to show that a subset S of V and Q of E form a component of G? Assuming of course that S and Q do represent a connected graph)
Comment: In order to associate "degree of vertex" with the "neighbourhood of its vertices", aren't we assuming that the graph is simple (i.e no double edges)? In general $|A| \leq \deg(u)$.
Answer: Proof:
If each degree is at least that, then each component has at least one vertex and $\frac{n-1}{2}$ others, so at least $\frac{n-1}{2}+1=\frac{n+1}{2}$ vertices. Two components would have at least twice as many vertices, which is n+1, more than the graph has.
(I realize this is the same as David's, but I don't like unnecessary variables so I feel it's still worth posting.)
Edit: Different wording, appropriate for the OP's stated terminology/knowledge:
Alternative proof:
Take any two vertices. Each has at least $\frac{n-1}{2}$ neighbors. If there were no path between our two vertices, then the two neighborhoods must be separate and we'd have at least $2\cdot(1+\frac{n-1}{2})=n+1$ vertices, more than the graph has.
Answer: suppose the graph has at least two distinct connected components, $C_1$ and $C_2$. denote by $c_1,c_2$ two vertices, one in each component.
$C_1$ has the vertex $c_1$ and at least $\frac{n-1}2$ other vertices, one for each edge incident to $c_1$, a total of at least $\frac{n+1}2$. likewise $C_2$ must have at least $\frac{n+1}2$ vertices.
the graph must therefore have at least
$$
\frac{n+1}2 + \frac{n+1}2 = n+1
$$
 vertices, contradicting the assumption
Answer: I think this can be done by induction on the number of vertices: this is trivially true for $n=1,2$. Assume true for $n=k$, i.e., every graph on $k$ vertices where each vertex has degree $\geq (k-1)/2 ; k>2 $ ,is path-connected.
Now consider a graph $S_{k+1}$ on $k+1 $ vertices. Isolate any subgraph $S_k$ with $k$ vertices, and define $v_{k+1}:= S_{k+1}-S_k$, i.e., $v_{k+1}$ is just the vertex of $S_k$ thatis not in $S_{k+1}$ (EDIT : ignore edges out of/into $v_{k+1})$ . By induction, $S_k$ is path-connected. We know $Deg(v_{k+1}) \geq (k+1-1)/2=k/2 $. But now we just need
$Deg(v_{k+1}) \geq 1 $ . Now join $v_{k+1}$ with any $v_j ; j \neq k+1$, which gives you, by path-connectedness of $S_k$ a path between $v_{k+1}$ and $v_j$;
$k+1 \neq j$.
EDIT   Alternatively, consider a path-connected graph on $k-1$ vertices, with $Deg(v_j) \geq (k-1)/2$ . Throw in a new vertex $v_{k+1}$ and draw  and edge between $v_{k+1}$ and every other edge, and you have a path-connected graph with $Deg(v_j)=(k-1)/2+1 =(k+1)/2 \geq k/2$
Comment: "Isolate any subgraph $S_k$ with $k$ vertices [...]. By induction, $S_k$ is path-connected."
Comment: Because every vertex in $S_k$ has degree at least $k/2$, satisfying the induction hypothesis, i.e., it is a graph on $k$ vertices and at least $(k-1)/2$ edges. What is wrong with that?
Comment: My comment was indeed wrong, I apologise. But why is the minimal degree in $S_k$ at least $(k-1)/2$? I only see $(k+1-1)/2 -1 =(k-1)/2 - 1/2$.
Comment: Indeed I can have a graph on $3$ vertices with each vertex of degree $1$ and remove a vertex so that the remaining graph is not connected.
Comment: No problem. Let me double check.
Comment: Sorry, I have to head out now, I will be back later and will try to tighten p; if I cannot, I will delete. Did you see the bottom edited paragraph?
Comment: And I made another mistake, I should not try to do maths today. I meant a graph with two vertices of degree one and one of degree two. But still.
Comment: You can always cover the cases for n=1,2,3 separately, since these are simple. Still, I will try to write a more general response.

Prove that the graph is connected


What guidelines would a World Cup official follow when deciding whether to book a player for hitting another when contesting a ball in the air?

Question: During the U.S.'s World Cup match against Ghana today, I was surprised to see that the player who kicked Clint Dempsey in the face while contesting a ball in the air wasn't booked. I've seen bookings given for accidental elbows (or "accidental" elbows) and this seemed worse: you're clearly endangering the other player by raising your foot so high. Is this a case of the referee judging that the hit was accidental?
Of course if none of the officials see the hit happen nothing will be called, but in the case of today's game I don't think that's the case; the hit occurred very close to the ball. But even if the official didn't see, what if he had?
Answer: When deciding on what action to take when a player kicks, trips, pushes, strikes, charges, jumps at, or generally just tackles an opponent, the referee must consider whether it is careless, reckless, committed using excessive force, or alternatively, none of the above. p. 36 of the 2014/15 FIFA Laws of The Game
On page 117 of the 2014/15 FIFA Laws of The Game:

"Careless" means that the player has shown a lack of attention or consideration when making a challenge or that he acted without precaution.

Only a direct free kick / penalty kick is awarded if the action is careless.

"Reckless" means that the player has acted with complete disregard to the danger to, or consequences for, his opponent.

A direct free kick / penalty kick is awarded if the action is reckless, and the player is also cautioned for unsporting behaviour. p. 123 of the 2014/15 FIFA Laws of The Game

"Using excessive force" means that the player has far exceeded the necessary use of force and is in danger of injuring his opponent.

A direct free kick / penalty kick is awarded if the action is excessively forceful, and the player is sent-off for serious foul play if it is performed whilst challenging for the ball. If not challenging for the ball, the player is sent-off for violent conduct. p. 126-128 of the 2014/15 FIFA Laws of The Game
If a player kicks, trips, pushes, strikes, charges, jumps at, or tackles an opponent in a manner that is not careless, reckless, or excessively forceful no offence has been committed and play continues.
As Sean pointed out, whether or not the action is accidental has no bearing on the decision that should be made.
https://www.youtube.com/watch?v=nRVIoQwzF54
Judging the particular incident, Boye was pushed by Dempsey first (notice the arm on the chest), which led to Boye being off balance. However, swinging your leg high into an opponent's nose, while you and your opponent are in the air, and you are off balance sounds to me like it is at least reckless, and possibly excessively forceful. I would have no complaint with Boye being either sent-off or cautioned for this challenge.
Answer: To answer the question simply; the player should have received a booking for this infringement.  It is a clear dangerous play and the accidental nature does not change this. As you view matches over the course of the competition you will witness many interpretations of the laws of the game.  The human element plays heavily on these matches. Some referees are better than others while others get distracted and even swayed.  I hope that helps some.


How to build drupal-twitter bot like the one on drupal.org

Question: I'm really impressed by this bot:  drupal8changes which gets changes from http://drupal.org/list-changes/drupal and posts it on to Twitter. I think it might be something like, when a new node is created of D8Changes content-type, then post it on to twitter. Isn't it awesome? I want to know how that could be implemented? Not just limited to twitter, but for Facebook, Google+ etc.
Answer: You can achieve this by using Twitter & Oauth module. You will have to create a twitter app & use Consumer key, Consumer secret to connect to your twitter account.
You will have to choose a content type for tweet & yeah don't forget to enabled import option on twitter account.


Erro - teste de Fisher no R

Question: Tenho tentado realizar um teste de Fisher com pares de variáveis de um banco que tem 823 casos. Estou usando o pacote gmodels. Entretanto, aparece o seguinte erro:
Error in fisher.test(t, alternative = "two.sided") :
  FEXACT error 7(location). LDSTP=18510 is too small for this problem,
  (pastp=17.2051, ipn_0:=ipoin[itp=71]=329, stp[ipn_0]=14.8098).
Increase workspace or consider using 'simulate.p.value=TRUE'
Além disso: Warning message:
In chisq.test(t, correct = FALSE, ...) :
  Chi-squared approximation may be incorrect

Já tentei contornar usando a função > memory.limit(25000) e  >fisher.test(input_table, workspace = 2e8), mas sem sucesso.Também tentei usar a função sugerida no erro (>simulate.p.value=TRUE), porém não deu certo. Alguma ideia sobre como poderia resolver? Ou seria um problema da memória do próprio computador?
Obrigada!
Answer: O problema é que o teste de Fisher calcula fatoriais e a função fatorial cresce muito depressa. Com 823 casos, terá um denominador em que entra
factorial(823)
#[1] Inf

Para realizar testes das variáveis duas a duas, pode usar combn.
# só correr os testes para estas colunas
cols <- 3:20

set.seed(1234)
res_list <- combn(dados[cols], 2, FUN = \(x) {
  fisher.test(x[[1]], x[[2]], simulate.p.value = TRUE)
}, simplify = FALSE)

# para se saber quais as variáveis testadas
names(res_list) <- combn(names(dados[cols]), 2, FUN = paste, collapse = "_")

# o número de combinações das variáveis duas a duas é
# igual ao comprimento da lista de resultados
choose(ncol(dados[cols]), 2)
#> [1] 153
length(res_list)
#> [1] 153

Created on 2022-03-14 by the reprex package (v2.0.1)
Cada membro da lista res_list é um objeto tal como descrito em help("fisher.test"), secção Value.
str(res_list[[1]])
#> List of 4
#>  $ p.value    : num 0.713
#>  $ alternative: chr "two.sided"
#>  $ method     : chr "Fisher's Exact Test for Count Data with simulated p-value\n\t (based on 2000 replicates)"
#>  $ data.name  : chr "x[[1]] and x[[2]]"
#>  - attr(*, "class")= chr "htest"

Created on 2022-03-14 by the reprex package (v2.0.1)
Para ver os resultados pode-se usar o operador de extração [[ e para extrair todos os p-values, usa-se um ciclo sapply.
res_list[[1]]
#>
#>  Fisher's Exact Test for Count Data with simulated p-value (based on
#>  2000 replicates)
#>
#> data:  x[[1]] and x[[2]]
#> p-value = 0.7126
#> alternative hypothesis: two.sided

pvals <- sapply(res_list, `[[`, 'p.value')
head(pvals)
#>      V3_V4      V3_V5      V3_V6      V3_V7      V3_V8      V3_V9
#> 0.71264368 0.04947526 0.21889055 0.96501749 0.73513243 0.96601699

Created on 2022-03-14 by the reprex package (v2.0.1)

Dados de teste
set.seed(2022)
dados <- replicate(20, {
  n <- sample(2:10, 1)
  p <- runif(n)
  repeat({
    s <- sample(letters[1:n], 823, replace = TRUE, prob = p/sum(p))
    if(length(unique(s)) >= 2L) break
  })
  s
})
dados <- as.data.frame(dados)

Created on 2022-03-14 by the reprex package (v2.0.1)

Erro - teste de Fisher no R


Validar CPF com Ajax e em seguida enviar o formulário

Question: Boa Noite, Pessoal.
Estou precisando de ajuda, estou tentando fazer uma validação e em seguida enviar o fomulário, o que eu preciso basicamente é:
Quando o usuário digitar o CPF no formulário, quero fazer uma verificação no banco de dados, caso o cpf não esteja cadastrado, o formulário e enviado, caso contrário e mostrado uma mensagem na mesma página.
            <form method="post" action="pesquisa.php" id="formulario">

                CPF:
                <input type="text" class="form-control" id="cpf" name="cpf"  maxlength="14" placeholder="Digite o seu CPF" required>

                Idade:
                <input type="text" class="form-control" id="idade" name="idade" placeholder="Digite sua Idade" required>

                    <input type="radio" name="sexo" id="sexo" value="M"> Masculino

                    <input type="radio" name="sexo" id="sexo" value="F"> Feminino

            <button type="submit" class="btn  btn-info" id="enviar">Iniciar Pesquisa</button>
            <input type="hidden" value="false" id="validado" name="validado">
        </form>

O Javascript está assim:
$("#formulario").submit(function(e){
var cpf = $("#cpf").val();

if(validarCPF(cpf)){
    buscarCPF(cpf);
}else{
    e.preventDefault();
    $("#cpf").val('');
    $("#cpf").focus();
    return false;
}
});
function buscarCPF(cpf){
var req;

cpf = cpf.replace(/[^\d]+/g, '');

if(window.XMLHttpRequest) {
   req = new XMLHttpRequest();
}
else if(window.ActiveXObject) {
   req = new ActiveXObject("Microsoft.XMLHTTP");
}

var url = "busca.php?cpf="+cpf;
req.open("Get", url, true);

req.onreadystatechange = function() {

    if(req.readyState == 1) {
        document.getElementById('resultado').innerHTML = 'Buscando CPF...';
    }

    if(req.readyState == 4 && req.status == 200) {
        var resposta = req.responseText;
        if(resposta != ""){
            document.getElementById('resultado').innerHTML = "
CPF Já Cadastrado!
";
        }
    }
}
req.send(null);

}
O Problema e que não sei como que eu faço pro submit só executar caso não seja retornado nenhum dado na pesquisa, tentei utilizar if, porem pelo que eu andei lendo a pesquisa no banco é feita de forma assicrona, então o formulário e enviado, tem como submeter o form apenas depois de efetuar a pesquisa no banco?
Answer: Da forma que está fazendo, precisa dar um nome ao formulário:
<form method="post" action="pesquisa.php" id="formulario" name="formulario">

Colocar o e.preventDefault(); fora do if:
$("#formulario").submit(function(e){
   e.preventDefault();
..

E colocar um else no retorno do Ajax para submeter o formulário::
if(resposta != ""){
   document.getElementById('resultado').innerHTML = "
CPF Já Cadastrado!
";
}else{
   document.formulario.submit();
}

Comment: Perfeito, deu certinho. Muito Obrigado!


Wifi repeater 3com 7760

Question: I have a problem with a wifi repeater that I am configuring (3Com Wireless 7760)
Here some pictures of my installation of the device: https://i.stack.imgur.com/foRcB.jpg
According to the manual of the device, connect with a network cable and connect to the LAN, should you turn on your power button, but I don't see any lights in any of the 4 devices that I have. The devices are new and im surprised that none of the 4 work.
I found the following books, but I can not understand. I imagine that at least the power button light should be on:
www.conectavilanova.com/descargas/manuales/AP(3com)_V1_0709.pdf
www.manualowl.com/m/3Com/7760/Manual/296999
Any idea?
Comment: Could you edit your question to include the pictures as inline images? Because external links tend to go dead.
Comment: i tried but i need for reputation. Sorry :(
Answer: You need a PoE (Power over Ethernet) capable switch. The Netgear thing that I see there most probably is not PoE capable. You can also use a PoE injector, you would go from Switch -> PoE Injector -> Patch Panel
Comment: I use a PoE and power led turns on :'D http://i.imgur.com/DQWDnz6.jpg How can i detect the device in my net? I dont see any ip with port 80 on
Comment: That's something you Need to consult the documentation for the device. Often it has 192.168.0.1 or something by Default, or there is a "Management Application" which can detect and configure the device

Wifi repeater 3com 7760


sweetAlert is not showing up

Question: The code so far:
<!DOCTYPE html>

        <title>Project 506</title>

        <link rel="stylesheet" href="sweetalert.css" type="text/css" />

Message Boxes

        <input type="button" id="first" value="Just a Notification" />
        <input type="button" id="second" value="Successfully Completed!" />
        <input type="button" id="third" value="Something Went Wrong!" />

I'm not clear on why the sweetAlert animation still doesn't pop up when I click on the first button. I've tried moving the lines of

sweetAlert is not showing up


How to convert timezone name to shortname in ruby

Question: Is there a way to convert timezones like "America/Los_Angeles" to timezone shortname "PDT" in ruby?
Answer: The abbreviations are typically contextual - so "PDT" only applies while daylight saving time is in operation.
Judging by the documentation, if you format a Time with strftime and use a format string of %Z, you should get the time zone abbreviation.
Personally I dislike using the abbreviations, given that they're ambiguous and can cause a lot of confusion. (I've seen people using "PST" year-round, for example, referring to "7/20/2012 9:00 PST" for example - a date/time which makes no sense.) That's a different matter though :)
Comment: If it only works in daylight saving time then it will not fulfil my application requirement. Thanks!
Comment: It might be worth noting that this method will return the abbreviation but won't differentiate between the conflicting abbreviations in Australia. For example, Adelaide is in Australian "CST" timezone which conflicts with the "CST" used in North America, which can trip you up depending on the technology stack used (PostgreSQL is one).
Comment: @douglasr: Indeed - hence the "given that they're ambiguous" bit.
Comment: @JonSkeet: I totally missed that sentence somehow. Sorry about that.
Answer: More explicit answer:
Time.now.in_time_zone("America/Los_Angeles").strftime('%Z')

Comment: Fails in following scenario
2.2.2 :059 > Time.now.in_time_zone("Indiana (East)").strftime('%Z')
=> "EDT"
2.2.2 :060 > Time.now.in_time_zone("Eastern Time (US & Canada)").strftime('%Z')
=> "EDT"
Comment: Strange.  Are you sure that isn't a bug with Rails?
Comment: I cant say if its a bug or not. Whats happening is its failing in case of day light saving. So its also debatable that its a fail or not. Ruby uses utc_offset to tell us what timezone it is. I would say its a fail or not is based on what USA uses as a standard. If they use EDT for Indiana (East) during day light saving then its not a bug but if they use EST both during day light saving and normal days then its a fail.


Multiple treatments to the same subject

Question: I have a sample where there are two treatments on the same subjects, with the 2nd treatment happening at a later point in time. What will be a proper matching and/or difference-in-difference (DiD) analysis be here?
The setting:
Two groups of subjects: treated group vs control group.
Panel data: 24 months.
Treatment:
-- in the 6th month, treated groups received treatment $A$
-- in the 18th month, treated groups received treatment $B$
DiD approach to quantify treatment $A$:

prior to the 6th month, two groups were comparable and similar in their dependent variable (common trends)
between the 6th and the 18th month,

$Y_{it}=\beta\bullet(treat_i*after_t)+\alpha\bullet X_{it}+FE_t+FE_i$
where $treat_i$ is 1 if subject i is in the treated group and $after_t$ is 1 if period t is after the 6th. The two fixed effects (FEs) are the period and subject fixed effects. The estimate of $\beta$ identifies the effect of treatment $A$ on the dependent variable $Y$.
My question is, after the 18th month, treatment $B$ was introduced on subjects in the treatment group. How can the effect of treatment $B$ be identified? Note that prior to the implementation of treatment $A$ ($t<6$), the two groups had similar trends in $Y$, that however did not hold anymore in the periods leading up to treatment $B$ ($t<18$), because of treatment $A$.
Thanks!
Comment: Is the first treatment still in place when the second treatment occurs? Do the exact same subjects receive both treatments? Can anyone opt out?
Comment: Thanks Thomas. The treatments are forced so no one can opt out (e.g., a policy change in a state). When the second treatment came, the first treatment was gone at the same time.
Comment: So there's absolutely no overlap between A and B?
Comment: Yes. There is no overlap. But the problem is due to treatment A, some market conditions had changed, and the two groups became incomparable (both DV and the X changed), right before when treatment B was in. I'm wondering in this scenario, can I just write two treatment indications (treat*afterA) + (treat*afterB) in the DiD? Or should I match the two groups on their covariates and make sure that the two groups had similar trends in the outcome variable, prior to treatment B?
Answer:
My question is, after the 18th month, treatment $B$ also came to the subjects in the treated group. How can the effect of treatment $B$ be identified?

According to my reading of your question, the same subjects received two exposures with adjacent post-periods. Further, it is my understanding that they represent entirely different treatments, though you did not explicitly say what $A$ and $B$ represent in your study. The onset of the first exposure is in the sixth month; this treatment hits all subjects in the treatment group at the same time. Immediately before the onset of the second exposure, the first is withdrawn. Thus, the treatment group is, technically, in a perpetually treated condition—though subjects receive two different types of treatment over time. Since each "after" period is well-defined, then you can actually write this as the interaction of a treatment dummy with two post-treatment indicators. The classical equation with two treatment regimes is as follows:
$$
y_{it} = \gamma T_i + \lambda A_{1t} + \lambda A_{2t} + \delta_1 (T_i \times A_{1t}) + \delta_2 (T_i \times A_{2t}) + \alpha X_{it} + u_{it},
$$
where $T_i$ is equal unity for treated subjects, 0 otherwise. $A_{1t}$ turns in months 6–18, 0 otherwise. $A_{1t}$ turns in months 19–24, 0 otherwise. To simplify this approach, create one column with the three epochs appropriately labeled. Multiply your treatment dummy with a 'factorized' version of this and you got yourself a separate estimate for each post-period.
In settings with multiple treatments, I am partial to dummy variable notation. The following is the more general difference-in-differences estimator:
$$
y_{it} = \delta_1 D^{1}_{it} + \delta_2 D^{2}_{it} + \alpha X_{it} + \gamma_i + \lambda_t + u_{it},
$$
where $D^{1}_{it} = T_i \times A_{1t}$ and $D^{2}_{it} = T_i \times A_{2t}$. Note we instantiate each interaction term—manually. The parameters $\gamma_i$ and $\lambda_t$ denote fixed effects for subjects and months, respectively.
The problem here is the adjacency of treatments $A$ and $B$. Note how the removal of treatment $A$ and the institution of treatment $B$ is immediate. The variable $D^{2}_{it}$ is estimating a second treatment effect. How will you disentangle the effects of $A$ and $B$? Note how we have three epochs, which results in two contrasts. The pre- versus post-period for treatment $A$ and the pre versus post-period for treatment $B$. The periods before the sixth month serve as the pre-period for the second intervention. Note, it is permissible to use the second epoch (i.e., months 6–18) as the pre-period (i.e., reference epoch) for treatment $B$. Is just matters how we code our post-treatment variable. But treatment $A$ may have offset parallel trends before the onset of treatment $B$, which will bias your estimate of $\delta_2$. Again, this assumes you want to a clean estimate for treatment $B$.
This equation is useful if you wanted to track the effects of one intervention as it switches 'on' and 'off' over time. In your setting, the same subjects experience sequential treatments. Are you concerned about any strong lingering effects after treatment $A$ is removed? Suppose treated subjects experience a reduction in average outcomes following treatment $B$ relative to control subjects. Is this the actual effect of treatment $B$, or is it simply subjects rebounding from their previous treatment? This is something you should consider.
Since market conditions did in fact change following the introduction of treatment $A$, then the first treatment is actually a time-varying confounder. We could adjust for a previous intervention, but you'd be assuming the periods before the sixth month serve as a counterfactual for later treatments (i.e., treatment $B$). Matching on pre-intervention outcomes is a safe choice. Maybe a subset of subjects were more likely to be eligible for the second intervention, rather than both. In the end, you want two distinct treatment groups: one eligible for $A$ and a second eligible for $B$.

Multiple treatments to the same subject


How to safely share a file descriptor between two processes?

Question: This is a follow-up question, UNIX-focused, to my previous question here.
I was wondering whether a file descriptor open by a process, could safely be used in forked processes.
I've run a few tests by running several hundreds processes at the same time, all writing continuously to the same file descriptor. I found out that:

when fwrite() calls are up to 8192 bytes, all calls are perfectly serialized and the file is OK.
when fwrite() calls are more than 8192 bytes, the string is split into 8192 byte chunks that get randomly written to the file, which ends up corrupted.

I tried to use flock(), without success as every process tries to lock/unlock the same file descriptor, which does not make sense. The outcome is the same.
Is there a way to safely share the file descriptor between all the processes, and get all fwrite() calls properly serialized?
Comment: Related: http://stackoverflow.com/questions/14417806/are-posix-read-and-write-system-calls-atomic
Answer: The first thing you need to pay attention to is stdio buffers. Because you are using stdio (fwrite()) and not system calls directlr (write()), you don't know when the data will actually get flushed to the file. To bypass this issue, you will have to flush stdio buffers inside your critical section each time before you release the lock:
take the lock
fwrite(foo, ...);
fflush(thefile);
release the lock

...or you can switch to using write() directly.
Now, on to the main issue: how to lock the file so that only one process at a time has exclusive access to the file.
You may or may not be able to use flock(). It depends on how the different processes obtained file descriptors to the same file. flock() locks are associated with an open file table entry. Because fork() and dup() create new file descriptors that refer to the same file table entry, they are the same object from flock()'s point of view and so you can't use flock() in this case. If, on the other hand, each process opened its own copy of the file with open() directly, then you can use flock().
fcntl()-style locking does not suffer from this problem (it suffers from a different type of problem instead!). fcntl() locks are per-process, so it doesn't matter how the processes obtained file descriptors to the same file.
So I suggest you try with fcntl()-style locking:
struct flock ll;

/* lock */
ll.l_start = ll.l_len = ll.l_whence = 0; /* lock the whole file */
ll.l_type = F_WRLCK; /* exclusive lock */
fcntl(fd, F_SETLKW /* or F_SETLK */, &ll);

/* unlock */
ll.l_type = F_UNLCK;
fcntl(fd, F_SETLKW /* or F_SETLK */, &ll);

Comment: Thanks, can you please expand on what problems `fcntl()` suffers from?
Comment: The main problem with `fcntl()`'s per-process locking is that if two different parts of the same process operate on the same file (say, 2 different libraries that the main application uses but which don't know about each other) then they will conflict with each other. Since the lock is per-process, unlocking the file using *one* file descriptor releases the lock from the point of view of all *other* file descriptors refering to the same file too. See for example http://www.perlmonks.org/bare/?node_id=392435
Comment: Ok, that makes sense! Alternatively, is it possible to know on a given system the max length at which `fwrite()` (or `write()`) calls are atomic (1023 in my case)? This is only for a file logger, so writes are expected to be quite small anyway, but it would be nice to know programmatically whether a given `write()` will be atomic or not given its length.
Comment: See http://stackoverflow.com/questions/14417806/are-posix-read-and-write-system-calls-atomic for details on that. Summary: if you are writing to pipes, the max size for atomic writes is `PIPE_BUF`, and if you are writing to anything else than pipes, then the writes are NEVER atomic.
Comment: Yes I've read this link, but the weird thing is that although I'm not writing to pipes, my experience shows that the writes *are* atomic up to 1023 bytes. Any explanation welcome!
Comment: Sorry, it was actually `8192` bytes, not `1023`. That was a mistake in my code that checked the output file. I've updated my question to reflect that.
Comment: No, your experience shows that the writes happen to be atomic under the specific conditions you happen to be testing under (including system load, scheduler configuration, operating system version, C library version, phase of the moon) but this doesn't tell you anything about what the system guarantees will be atomic.
Answer: The way you are using the file descriptor is perfectly safe.  The writes are not synchronized, so the output is perhaps not what you expect, but there is nothing "unsafe" about that.  If you are asking "how to synchronize writes to a common file descriptor", then the answer is obvious: use a synchronization mechanism.  In the case you describe in which one file descriptor is shared amongst multiple processes, perhaps the easiest thing to do is to pass a token on a second pipe.  Have a pipe that is shared amongst all the processes and write a single character into it.  When a process wants to write to the first fd, it attempts to read a character from the pipe.  When the read is successful, proceed with the write (make sure to flush) and then write a character back into the pipe.  When any process is in the critical section (ie, it has read but not yet written the token), any other process will block on the read until the other process completes its write, as long as you don't forget to flush!  This is a fairly expensive operation, since it requires each process to keep two additional file descriptors open and the upper bound on the number of available file descriptors is fairly low, typically on the order of 1024, but it is often very effective.
Comment: Very interesting explanation, thanks. That being said, I'm only using the shared file descriptor to write to a log, one line at a time. So it's very unlikely that I need a locking mechanism at all, provided that I stay under these 8192 bytes. Do you know where this number (that I got empirically) is coming from?
Comment: `writes` are guaranteed to be atomic up to a certain value (PIPE_BUF) depending on the system.  Very likely, in your case, that value is 8192.  It is possible that the actual value is smaller (512 and 4096 are common).  Check the value of PIPE_BUF. Search for "atomic" in  http://pubs.opengroup.org/onlinepubs/009695399/functions/write.html
Comment: In his answer and comments below, @Celada says that PIP_BUF only applies to pipes. Why does it apply when I'm writing to a file then?
Comment: Celada is correct; the standard only guarantees atomicity for pipes.  Very likely, the implementation uses similar mechanisms for regular files and you are getting atomic writes as a side effect, but this is not behavior that can be relied on.


Are the diminished chords not that common in modern popular music?

Question: It seems like the diminished chord (vii° in major, ii° in minor) is not used as much in modern popular music compared to classical music and the remaining chords of the diatonic scale.  Is it actually rare?
Comment: There's a diminished chord hiding in every dominant seventh chord. (The third, fifth, and seventh together form a diminished chord.) Plenty of rock music and blues and related genres have I7 and/or IV7 chords in addition to the V7 chord, where it's expected.
Comment: also Locrian, the only mode with a diminished tonic chord is also used less than the others modes.
Comment: Twotone and ska make much use of diminished chords.
Answer: Given that in any key there are basically (diatonically) three major chords, three minor chords and only one diminished, and that diminished doesn't stand alone, or constitute a key on its own, statistically, there's a one in seven chance of any random diminished chord being used, whereas a three in seven (nearly 50:50 ) of a chord being major or minor.
Most songs seem to get away with not using what is quite an unusual chord - in several ways - as there are plenty of other options which will suffice. However, a lot of showtunes use diminisheds, and they can be made to fit into quite a few existing tunes with no great effort - and can sound good as replacements.
Answer: I guess it depends on what exactly you mean by 'modern popular music'. Generic pop music has a general formula that it rarely deviates from. Jazz has lots of seventh chords and that could easily count as modern popular music, a number of these chords are diminished.
It will all depend on the effect you want to create, the diminished chord has an uneasy feel to it. rather pretty but you are going to want to have to use that effect.
Here is an example of a song that I'm pretty sure ends on a diminished chord, used rather beautifully. It does have its place.
Comment: @MaikaSakuranomiya - it is indeed. However, a half-diminished chord can't be a diminished chord, so that part of this answer's incorrect. And for a piece in Dm, a Dm6 chord is better to end on than Bm7b5. with or without A in this case!
Comment: @user45266 - a half-dim chord does have the word 'dim' in it - so yes, it is considered as such..! C6 contains the same notes as Am7. You can hardly say that they're both major or they're both minor, by the same logic. Just a thought.
Comment: That final chord is not a diminished chord, but a **Dm6**. Close, but there is no b5. The voicing in the recording does not contain the 5th at all, but a diminished 5th does not sound right here. Nice recording, though.
Comment: Song's in Dm, and that last chord is, as David says, Dm6. Full chord spelled D F A B. D dim would be D F Ab Cb.I think I can hear an A - unless it's a harmonic.
Comment: Dm6 is the first inversion of the B half dim (Bm7b5) chord.
Comment: @Tim I've always considered a half-diminished seventh chord to be a *kind* of diminished chord; it falls under the diminished set of chord qualities. Kind of paradoxical, then, that a minor sixth chord which is enharmonic to the former is not a diminished chord! :)
Answer: The half-diminished (or m7b5) is usually suggested as the diatonic chord on the 7th degree in major keys and the 2nd degree in minor keys, and is fairly common in most styles of music.


Xamarin: Resource.Designer.cs doesn't update when I make changes

Question: I got a problem with my Resource.Designer.cs. I spent well over an hour on google trying to find a solution, but I can't find a fix for my problem.
When I add a button or a text field in the Main.axml editor thing, it doesn't update the Resource.Designer.cs file. So when I write "var label = FindViewById(Resource.Id.textView1);" it shows a red line under the "textView1" because there is nothing about it in the Resource.Designer.cs file.
Even worse:
When I open a blank file and name it as "App1" (the default it was) and add all the things to get the same as in this tutorial, it can't detect the Resource.Layout.Main, since it generates the names wrong.
Screenshot of MainActivity.cs: http://puu.sh/tqsNr/8ac98a5b08.png
Screenshot of Resource.Designer.cs: http://puu.sh/tqsOv/dd1de7328f.png
This is because the namespace in MainActivity is "App1", and it generates the namespace name in Resource.Designer as "application".
How can I fix this? I have very limited time because I have to use this for a school project.
Comment: Could you please check the `RootNameSpace` tag value of  `YourProjectName.csproj` file?
Comment: @ElvisXia-MSFT Not soon after I posted my question, and before your reply I found out that the default names of the namespace were different. This was indeed the problem for my second problem.
Comment: There are many possibly workarounds for issues like these. What have you tried yourself? As the question is stated right now, you are likely to receive many different answers, as the question is too broad.
Comment: Have you tried deleting this file, reopening Xamarin Studio/VS and rebuilding Android project over?
Do you have any compilation problems when you build your Android project?
Answer: This happened to me, and I figured it was a Xamarin bug.  But in this case, it was because I had left a --> in my strings.xml file after I had removed some comments.  I saw the compile warning deep in the error list.
Answer: To fix it, try adding a new <code>.axml</code> file to project. Worked for me (you can delete the file after it works).


Problem with useEffect and navbar active on scroll "To fix, cancel all subscriptions"

Question: I'm trying to make active anchors in navbar navigation on scroll. Everything is working until I don't change page and return back to home page, then when I scroll page I get an error from useEffect hook " Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function. " How I should cancel all subscriptions ?
useEffect code :
const [headerText, setHeader] = useState(false);
let mount = false;
useEffect(() => {
  if (!mount) {
    scrollActiveNav();
    scrollStickyNav((header) => {
      setHeader(header);
    });
  }
  return () => {
    mount = true;
  };
}, []);

Sticky navbar function :
const scrollStickyNav = (cb) => {
  const scrollSticky = window.addEventListener("scroll", () => {
    const header = document.getElementById("navbar");
    if (window.pageYOffset >= 80) {
      header.classList.add("navbar-sticky");
      header.classList.remove("absolute");
      cb(true);
    } else {
      header.classList.remove("navbar-sticky");
      header.classList.add("absolute");
      cb(false);
    }
  });
  return window.removeEventListener("scroll", scrollSticky);
}

Acitve link anchor in navabar function:
const scrollActiveNav = () => {
  const activeNav = window.addEventListener('DOMContentLoaded', () => {
    const options = {
      threshold: 0.5
    };
    const observer = new IntersectionObserver(entries => {
      entries.forEach(entry => {
        const id = entry.target.id;
        if (entry.isIntersecting && entry.intersectionRatio > 0.5) {
          document.querySelector(`.navbar-nav li a[href="${id}"]`).classList.add('active');
        } else {
          document.querySelector(`.navbar-nav li a[href="${id}"]`).classList.remove('active');
        }
      });
    }, options);
    document.querySelectorAll('section[id]').forEach((section) => {
      observer.observe(section);
    });
  });
  return window.removeEventListener("DOMContentLoaded", activeNav);
}

Comment: There are a few things going wrong here, 1st your not removing any events, your using `window.removeEventListener` wrong,  you have to make sure the event function you remove is the same as the one you added.   Also the place you want to remove them is were you currently have `mount = true;`, that is kind of ironic, as that's when it's unmounted.. :)
Comment: @Keith So when i return window.removeEventListener("DOMContentLoaded", activeNav); is not working can you explain why ? with mount = true I just wrote for the test.
Comment: Because -> `const activeNav = window.addEventListener`  ,  activeNav will be `undefined`..  More details on how to use `addEventListener` here -> https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
Comment: @Keith Right thank you
Answer: Try change this line let mount = false; for this const mount = useRef(false).
const [headerText, setHeader] = useState(false);
let mount = useRef(false);

useEffect(() => {
  if (!mount.current) {
    scrollActiveNav();
    scrollStickyNav((header) => {
      setHeader(header);
    });
    mount.current = true;
  }
}, []);

Comment: Not working, the same "Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function."
Comment: Did you try to remove the event listener window.addEventListener("scroll"..., when component is destroyed?
Comment: When I remove  scrollStickyNav((header) => {
      setHeader(header);
    }); is not error so i think problem is with useState or this function
Answer: Did you try to do something like this?
useEffect(() => {
 scrollActiveNav();
 const activeNav = window.addEventListener('DOMContentLoaded', () => {
    const options = {
      threshold: 0.5
    };
    const observer = new IntersectionObserver(entries => {
      entries.forEach(entry => {
        const id = entry.target.id;
        if (entry.isIntersecting && entry.intersectionRatio > 0.5) {
          document.querySelector(`.navbar-nav li a[href="${id}"]`).classList.add('active');
        } else {
          document.querySelector(`.navbar-nav li a[href="${id}"]`).classList.remove('active');
        }
      });
    }, options);
    document.querySelectorAll('section[id]').forEach((section) => {
      observer.observe(section);
    });
  });

  return () => {
    window.removeEventListener("DOMContentLoaded", activeNav);
  };
}, []);