Is the theory of the rational ordered field countably categorical?

Question: Consider the structure $(\mathbb{Q},+,-,\times,0,1,<).$ Now certainly, by Lowenheim-Skolem, we can't have a set of sentences in first-order logic whose models are precisely that structure and any structure isomorphic to it. But what if we require the model to be countable? That is, if a countably infinite ordered field satisfies the theory of the rational ordered field, is it isomorphic to the rational ordered field?
Edit: Also, if the answer is no, can someone exhibit an ordered field not isomorphic to $\mathbb{Q}$ which satisfies its complete theory?
Comment: @ThomasAndrews https://math.stackexchange.com/a/3830598/7062
Comment: The answers given below answer the question quite completely, I think, but just as an aside: the integers are definable in the (pure) field of rationals (this is a nontrivial theorem due to Julia Robinson). It follows that so are the natural numbers (which are the sums of squares of four integers). Thus, it is interdefinable with the arithmetic, and as such, is about as wild as it gets.
Comment: I'm not sure why $\mathbb Q(\pi)$ is not a model.
Comment: Nice. @AlexKruckman
Answer: By compactness, $\mathbb{Q}$ has a non-Archimedean elementary extension $\mathcal{A}$. Of course $\mathcal{A}$ may be uncountable, but we can get around that: let $a\in\mathcal{A}$ be an infinite element, and apply downward Lowenheim-Skolem to get a countable $\mathcal{B}\preccurlyeq\mathcal{A}$ with $a\in \mathcal{B}$.
Since $\mathcal{B}\preccurlyeq\mathcal{A}\equiv\mathbb{Q}$ we have $\mathcal{B}\equiv\mathbb{Q}$. But by choice of $a$, $\mathcal{B}$ must be non-Archimedean - and so not isomorphic to $\mathbb{Q}$.

EDIT: Whoops, I was really wrong initially - here's a correct statement:
It turns out in fact that there's a very useful general principle available to us: if $T$ is a (complete, countable language) theory which interprets a non-$\aleph_0$-categorical theory, then $T$ itself is not $\aleph_0$-categorical. So we can prove non-categoricity just by finding "bad configurations." This is a consequence of the Ryll-Nardzewski theorem, that a (countable complete) first-order theory is $\aleph_0$-categorical iff it has finitely many $n$-types for each $n$. See Alex Kruckman's comment below.
Comment: @CameronBuie It's the standard notation for [elementary equivalence](https://en.wikipedia.org/wiki/Elementary_equivalence).
Comment: @AlexKruckman The OP had earlier asked a question whose answer involved the definability of $\mathbb{Z}$ in $\mathbb{Q}$. With this in mind, the counterexample *would have* indicated that that definability result + non-$\aleph_0$-categoricity of $\mathbb{Z}$ (which I think the OP already asked about even earlier?) would not be enough to settle the $\mathbb{Q}$-case. But I was wrong anyways, so ...
Comment: That makes more sense, but what does $\mathcal{A}\equiv\Bbb Q$ indicate? Since $\mathcal{A}$ may be uncountable, it doesn't indicate equipotence, and since $\mathcal{A}$ is non-Archimedean, it doesn't indicate isomorphism.
Comment: +1: Gotcha. Nice approach! I don't quite get the counterexample, yet, but it intrigues me! :-)
Comment: Hi Noah - I don't think your counterexample does what you want. $\mathrm{Th}(\mathcal{X})$ isn't countably categorical because the "distance $n$" relations are definable for all $n$, contradicting Ryll-Nardzewski. The extra models will come from the fact that you can't control how many "new" $\mathbb{Z}$-chains are related to each rational  $q$ (but not to any $p<q$).
Comment: On the other hand, it *is* possible to prove that if $T$ is a countably categorical theory in a countable language and $T'$ is a complete theory interpretable in $T$, then $T'$ is countably categorical. It's an immediate consequence of Ryll-Nardzewski: If $T'$ has infinitely many inequivalent formulas in $n$ free variables for some $n$, then $T$ does too.
Comment: @AlexKruckman Argh, you're quite right! Fixing ...
Comment: @CameronBuie I was wrong, see Alex's comment (and my imminent edit).
Comment: Anyway, what did the counterexample have to do with the original question?
Answer: Your question admits a very strong negative answer: No infinite integral domain has a countably categorical theory.
Further, you can take "infinite integral domain" to mean any infinite structure $R$ in a countable language $L$ containing the language of rings, such that the reduct of $R$ to the language of rings is an integral domain. So, for example, this applies to the ordered field $\mathbb{Q}$.
Let $R$ be an infinite integral domain. For every $n$, the polynomial $x^n - 1$ has at most $n$ roots in $R$, so since $R$ is infinite, there is no finite upper bound on the  multiplicative orders of non-zero elements of $R$. Then the formulas $y = x^n$ are pairwise inequivalent for all $n$ (given $m < n$, if $a\in R$ is a non-zero element of multiplicative order greater than $n$, and $b = a^n$, then $R\models b = a^n$, but $R\not\models b = a^m$). By the Ryll-Nardzewski theorem, $\text{Th}(R)$ is not countably categorical.


Need to assign different values to letters and non-letters in a sentence

Question: Need to assign a value 1-26 to letters of the alphabet (i.e., a = 1, b = 2, etc.) and -1 to anything else in a sentence and then add up the values.
Currently have:
from string import ascii_lowercase

s = "Isn't it amazing?"
s = s.lower() #upper case version should have the same value as lower

letters = {letter: str(i) for i, letter in enumerate(ascii_lowercase, start=1)}
answer = [letters[char] for char in s if char in letters elif char not in letters -1]

for i in range(0, len(answer)):
    answer[i] = int(answer[i])
sum(answer)

Desired return for sentence s is 158. Is there a way to use else in list comprehension?
Answer: Dictionary provides a specific function for your use case: dict.get, from the documentation:

Return the value for key if key is in the dictionary, else default. If
  default is not given, it defaults to None, so that this method never
  raises a KeyError.

Code
from string import ascii_lowercase

s = "Isn't it amazing?"
s = s.lower()  # upper case version should have the same value as lower

letters = {letter: i for i, letter in enumerate(ascii_lowercase, start=1)}
answer = [letters.get(char, -1) for char in s]

print(sum(answer))

Output
158

Also, notice that if plan to use the integer value of the enumerate you don't need to transform it into a string. If you insist in using a ternary operator, you could do it like this:
answer = [letters[char] if char in letters else -1 for char in s]

Answer: Your else is in the wrong position. Also, ord is the usual way to translate a character to a number (subtract the value for 'a', adding one, to get 1-based numbers).
from string import ascii_lowercase

s = "Isn't it amazing?"
s = s.lower() #upper case version should have the same value as lower
vals = [ord(ch)-ord('a')+1  if ch in ascii_lowercase else -1 for ch in s ]
answer = sum(vals)
print(answer)

Answer: you can 1st convert the string into bytes and use the ascii byte value like below
s = "Isn't it amazing?"
s = s.lower()
sum([(b-96) if b>=97 and b<=122 else -1 for b in bytes(s, "ascii") ])

Answer: Considering char code of starting letter "a" as constant subtraction number:
sub_num = ord('a') - 1
answer = [ord(c) - sub_num if c.isalpha() else -1 for c in s]
print(sum(answer))    # 158


Como posicionar uma div do lado de outra (React)

Question: Não estou conseguindo posicionar uma div do lado de outra quando realizo um map em um Json.
No momento esta ficando um em cima do outro mas preciso que fique ao lado.

Arquivo .js aonde chama meu Renderizar familias:
return (

                <RenderFamilia />

    );

Arquivo .js que renderiza as familias:
import React from 'react';
import '../styles/Styles.css'

const RenderFamilia = () => {
    const itens = [
        {
            id: "1",
            familia: "Hamburguer",
            descricao: "Hamburguer explosão",
            complemento: "Hamburguer 300 g. bacon, cebloa roxa, queijo, tomate, alface e molho especial.",
            valor: "28,00"
        },
        {
            id: "2",
            familia: "Hamburguer",
            descricao: "Hamburguer top",
            complemento: "Hamburguer 300 g. bacon, cebola roxa, queijo, tomate, alface e molho especial",
            valor: "28,00"
        },
        {
            id: "3",
            familia: "Hamburguer",
            descricao: "Hamburguer familia",
            complemento: "Hamburguer 300 g. bacon, cebloa roxa, queijo, tomate, alface e molho especial.",
            valor: "28,00"
        },
        {
            id: "4",
            familia: "Hamburguer",
            descricao: "Hamburguer costela",
            complemento: "Hamburguer 300 g. bacon, cebloa roxa, queijo, tomate, alface e molho especial.",
            valor: "28,00"
        },
        {
            id: "6",
            familia: "pizza",
            descricao: "pizza calabresa",
            complemento: "Hamburguer 300 g. bacon, cebloa roxa, queijo, tomate, alface e molho especial.",
            valor: "28,00"
        },
        {
            id: "7",
            familia: "pizza",
            descricao: "pizza mmussarela",
            complemento: "Hamburguer 300 g. bacon, cebloa roxa, queijo, tomate, alface e molho especial.",
            valor: "28,00"
        },
        {
            id: "8",
            familia: "pizza",
            descricao: "pizza milho",
            complemento: "Hamburguer 300 g. bacon, cebola roxa, queijo, tomate, alface e molho especial.",
            valor: "28,00"
        }
    ]
    let renderizar = true;
    let familia = '';
    const final = itens.map(item => {
        familia == item.familia ? renderizar = false : renderizar = true;
        familia = item.familia;
        return (

                {renderizar ?

                                    {item.familia}

 : ''}

        );
    });
    return (

            {final}

    );
}
export default RenderFamilia;

Arquivo Css:
  .Single-div {
    width: 100px;
    height: 100px;
    display: inline-block;
}

Answer: EM seu código, em nenhum momento foi usada a classe que você descreveu no Style.css. tente colocar na primeira classname do final()
...
          return (

                {renderizar ?
...

Answer: Eu tinha usado a classe neste momento:
return (

                <RenderFamilia />

    );

Mas alterei para sua sugestão e deu certo, só tive que mudar a classe Css para ficar mais apresentável:
  .Single-div {
    display: inline-block;
}

Comment: Como está escrito atualmente, sua resposta não é clara. Por favor, pode [edit] para adicionar mais detalhes, que ajudarão outras pessoas a entender como isso resolve a pergunta feita. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


Is there a reason not to use parametised routes in the Play Framework

Question: At work I am making some changes to an existing web app built using the Play Framework, and have noticed that none of the routes use parameters. On previous projects I've worked on I would expect to see routes like:
GET    /some-path/:id    @controllers.BaseController.somePath(id: Int)

Instead all the routes would be like so:
GET    /some-path        @controllers.BaseController.somePath()

In this case the web app uses a session manager to store and retrieve values, nothing is sent via parameters in the routes. I haven't seen this pattern before and don't have easy access to anyone who knows why the project was set up like this.
Is there any particular benefits to working like this? Is it more secure, for example?
Answer: I have a feeling the reason they used session data to track what should be parameters is due to lack of knowledge on RESTful design, rather than a deliberate choice.
The reason you wouldn't want to store information in the session for request / response data is mainly due to the reason the session exists: storing data across multiple requests. For standard POST/GET operations the data being sent is only meant to last the lifespan of one request (POST a userID to an action, or GET a list to display on a page). Storing these in the session would break the purpose of the session and result in either unnecessary data being carried over to each request, or it would require you to remove the parameters from session data after you're done with the data.
You could theoretically store this data in "flash" to solve the problem of data persisting across requests, as the flash session in Play only lasts one request, however flash is not secure & can be modified, it is subject to race conditions, may not be compatible on older browsers, and is mainly meant to serve display / error messages that last the one request after they occur.


Criando bibliotecas com multiplas execuções como o Jquery

Question: Estou começando agora a desenvolver minhas próprias bibliotecas Javascript. Eu já entendo um pouco como funciona o prototype mas eu ainda não entendo como eu posso executar na mesma requisição mais de um método assim como o jquery faz... EX:
//no jquery eu posso executar qualquer função em cascata assim
$('alguma coisa').metodo1().metodo2().metodo3();

//ou assim
$('alguma coisa').metodo1();
$('alguma coisa').metodo2();
$('alguma coisa').metodo3();

Gostaria de saber como eu posso criar ume simples biblioteca que eu possa executar inúmeros métodos ao mesmo tempo assim como o Jquery faz...
Answer: Basta no final do método você retornar o próprio objeto (return this) :
Exemplo:
var Numero = function(num){
 this.num = num;
 this.valueOf = function(){
    return this.num;
 }
 this.maisUm = function(){
    this.num += 1;
    return this;
  }
  this.maisDois = function(){
    this.num += 2;
    return this;
  }
  return this;
}
var meuNum = new Numero(1);
alert(meuNum.maisUm().maisDois().maisUm() + 1); //1 + 1 + 2 + 1 + 1 = 6

Javascript é uma linguagem bem flexível, quando eu uso Numero = function(num){ ... } eu estou criando uma classe Numero e indicando que function(num){...} é seu método construtor. Dentro desse método, posso utilizar as propriedades de this para definir as propriedades e métodos da classe.
Comment: Não seja por isso, o javascript tem um método mágico chamado valueOf,  que permite que um objeto se comporte como um valor primário.
Exemplo:
var numDuplo = function(num){ this.num = num * 2; this.valueOf = function(){ return this.num}}

Então posso utilizar assim:

meuNumDuplo = new numDuplo(1):
alert(meuNumDuplo + 1); // retorna 3, porque o valor de meuNumDuplo será 2
Comment: @LeandroLUK E você também pode utilizar sem o "new" para ficar mais parecido com jQuery. Exemplo: Numero(3).maisUm().maisUm() + 1 //retorna 6
Comment: mas se eu fizer isso eu sou obrigado a sempre retornar o registro num, e se eu tiver mais que um elemento estruturado no this isso me quebra...
Comment: o que eu realmente estou procurando é gerar uma biblioteca que eu possa cruzar os métodos... entrando mais no assunto estou criando uma biblioteca para que trabalhe sobre o window.localStorage quase como se fosse SQL mesmo e por causa das variantes do SQL eu preciso poder injetar inúmeros elementos quando necessário...
Comment: Da forma que eu exemplifiquei te dá um bom norte de como fazer isso. Digamos que você quer buscar um dado do localStorage que está como jSon e pegar uma propriedade especifica dele, você poderia criar uma biblioteca que se comportasse da seguinte maneira:
localStorageLib('seuItemNoLocalStorage').get().parseJson().propriedadeQueVoceQuer.val()


A question about finite morphism between two schemes

Question: Let $f:X\to Y$ be a morphism of schemes.
Prove that $f$ is finite if and only if for any affine open subscheme $V=\mathrm{Spec}B$ of $Y$, $f^{-1}(V)=\mathrm{Spec}A$ for some $B$-algebra $A$ which is finitely generated as a $B$-module.
However, I only show that $V$ can be covered by finitely many affine open subschemes $D(b_i)$ of $V$ for $b_i\in B$ such that $A_{a_i}$ is a $B_{b_i}$-algebra which is finitely generated as a $B_{b_i}$-module, where $a_i$ is the image of $b_i$ under $f^\sharp(V):B\to A$.
Comment: You need to assume $Y$ is separated. Then can you show that $V\cap \mathrm{Spec} A_{a_i}$ is affine and then finish the proof?
Comment: Considering ${f^{ - 1}}\left( V \right)$ as $V{ \times _Y}X$ and then just drawing a bunch of pullback diagrams using the cover may help.
Answer: It should be clear that you only need to show that $f^{-1}(V)$ is affine, so you might as well take $X = f^{-1}(V)$ and $Y = \operatorname{Spec}B$. Then to show that $X$ is affine, you can use the criterion for affineness (Hartshorne exercise II.2.17b):

A scheme $X$ is affine if and only if there is a finite set of elements $f_1,\dots, f_r\in A = \Gamma(X,\mathcal{O}_X)$ such that the open subsets $X_{f_i}$ are affine and $(f_1,\dots, f_r) = A$.

You can show that you can take your $f_i$ to be the images of the $b_i$ under the map $f^\sharp : B\to\mathcal{O}_X(X)$ (show that $X_{f^\sharp(b_i)} = \operatorname{Spec} A_{a_i}$). You already know that the $a_i$ generate the unit ideal in $\mathcal{O}_X(X)$ because the $\operatorname{Spec}B_{b_i}$ cover $Y = \operatorname{Spec} B$. I'll leave this part of the proof to you.
Now, to show that $\mathcal{O}_X(X)$ is finitely generated as a $B$-module: let $s\in\mathcal{O}_X(X)$. Then for any $i,$ there exists a set $\{x_{i,j}\}_{j = 1}^{n_i}\subseteq\mathcal{O}_X(X)$ which generate $\mathcal{O}_X(X)\left[\frac{1}{f^\sharp(b_i)}\right] = f^{-1}(B_{b_i}) = \mathcal{O}_{X_{f^\sharp(b_i)}}(X_{f^\sharp(b_i)}) = A_{a_i}$ is a finitely generated $B_{b_i}$-module, so
$$
\frac{s}{1} = \sum_{j = 1}^{n_i} f^\sharp(\beta_j)\frac{x_{i,j}}{f^\sharp(b_i)^{r_{i,j}}}\in\mathcal{O}_X(X)\left[\frac{1}{f^\sharp(b_i)}\right]
$$
for some $r_{i,j}\in\Bbb N_0$, $\beta_j\in B$. Multiply through by an appropriate power $f^\sharp(b_i)^{r_i}$ to clear denominators and get
$$
f^\sharp(b_i)^{r_i} s = \sum_{j = 1}^{n_i} f^\sharp(\gamma_j)x_{i,j}
$$
by absorbing the excess $f^\sharp(b_i)$'s in any one term on the right hand side into $f^\sharp(\beta_j)$ to get $\gamma_j = \beta_j\cdot b_i^{?}$ (now an equality in $\mathcal{O}_X(X)$).
Next, you know that $f^\sharp(b_i)^{r_i} = f^\sharp(b_i^{r_i})$ and that $(b_1,\dots, b_n) = B$, which implies that $(b_1^{r_1},\dots, b_n^{r_n}) = B$ (by a standard argument in commutative algebra, you can adapt Ian's proof here if you're not familiar with the proof). Then there exist $c_i\in B$ such that $\sum_{i = 1}^n c_i b_i^{r_i} = 1$, which implies
$$
s = \sum_{i = 1}^n f^\sharp(c_i)f^\sharp(g_i^{r_i})s = \sum_{i = 1}^n\left(f^\sharp(c_i)\sum_{j = 1}^{n_i} f^\sharp(\gamma_j)x_{i,j}\right).
$$
Thus, the (finite) set $\{x_{i,j}\}_{i,j}$ generates $\mathcal{O}_X(X)$ as a $B$-module.
Comment: You can also play these games more generally and formally. See [here](https://www.math.ucdavis.edu/~osserman/classes/248B-W12/notes/props-mors.pdf) for some details on how to deduce that a property defined "on an affine open cover" holds if and only if it holds for the restriction to any affine open in the target.


Examining Convergence Of Improper Integral.

Question: I have to check the convergence of the improper integral $$ \int_{0}^{\infty} \cos^2x\,dx .$$
I have tried to solve it in the following manner:
$$\begin{align}\int_{0}^{\infty}\cos^2x\,dx &= \lim_{B \to \infty} \int_{0}^{B}\cos^2x\,dx \\&=  \lim_{B \to \infty} \int_{0}^{B}(1-\sin^2(x))\,dx \\ &=   \lim_{B \to \infty}[x]_{0}^{B} -\lim_{B \to \infty} \int_{0}^{B}\sin^2(x)\,dx .\end{align}$$
Now the first term tends to infinity as $B \to \infty,$ so the integral is not convergent.
But unfortunately the answer is given to be convergent. I don't understand how ?
Also I have proven in the same way that $$ \int_{0}^{\infty} (\sin x^2)^2\,dx $$ is divergent. So basically I think that if my process is wrong then I am wrong in both cases.
Am I wrong ? If so, looking for guidance then.
Thank you.
Comment: What you *could* do, however, is observe that $\cos^2 x$ is periodic with period $\pi$, and $\int_T^{T+\pi} \cos^2 x dx = \frac{\pi}{2}>0$. So...
Comment: You cannot do this this way: the first term goes to $+\infty$, but if the second goes to $-\infty$ you have an indeterminate form.
Comment: @ hiren_garai Perhaps there is a typo in your text and the $^2$ is meant to stand under the $\cos$. Then we have  $\int_0^{\infty } \cos \left(x^2\right) \, dx = \frac{1}{2} \sqrt{\frac{\pi }{2}}$
Comment: Oh ! I see. Then what way should I prefer ?
Comment: No, it diverges. See my answer.
Comment: Yes.. I was mistaken, sorry I put down my comment as I didn't notice your answer.
Comment: yes, that might have happened.
Answer: You cannot proceed this way, as you end up with something of the form
$$
\int_0^B dx\, \cos^2 x = u_B - v_B
$$
and $\lim_{B\to\infty} u_B = \infty$. But if $\lim_{B\to\infty} v_B = \infty$ as well, you have an indeterminate form and cannot conclude.

However, note that $\cos^2$ is perdiodic with period $\pi$, so that for any integer $k$
$$
\int_0^{k\pi} dx\, \cos^2 x = k\int_0^\pi dx\, \cos^2 x = k\cdot \frac{\pi}{2}
$$
and therefore
$$
\int_0^{B} dx\, \cos^2 x = \int_0^{\lfloor B/\pi\rfloor \pi} dx\, \cos^2 x
+ \underbrace{\int_{\lfloor B/\pi\rfloor \pi}^B dx\, \cos^2 x}_{\geq 0} \geq  \lfloor B/\pi\rfloor\cdot \frac{\pi}{2} \xrightarrow[B\to\infty]{} \infty
$$
Comment: I have one more query, can I visualise the problem in the way that it is the integration of a positive term from $0$ to $\infty$ and so the area of the curve will be unbounded and hence the integral is divergent ? It's just to find a rough idea about the problem . @ClementC.
Comment: Of course, one may write $$\int_0^L \cos^2(x)\,dx=\frac12 L+\frac14 \sin(2L) $$and conclude.
Comment: Thank you for your answer. In a similar way I can prove the divergence of $$ \int_{0}^{\infty} \text{(sin x²)² dx} $$, right ?
Comment: @hiren_garai yes, indeed.
Comment: I got it.@MarkViola. thanks for your time.
Comment: @MarkViola Thanks for the comment (and indeed, once can just write the explicit close-form integral, as you point out). The periodic "trick" is helpful in general, but not necessary here.
Comment: Hi Clement!  It's always nice to see you on MSE.  And indeed, the periodic "trick" has broad application.  (+1)


Prove that matrices of the form $\begin{pmatrix} x & x \\ x & x \end{pmatrix}$ are a group under matrix multiplication.

Question: G is the set of matrices of the form $G=$$\begin{pmatrix} x & x \\ x & x \end{pmatrix}$.
So for this set to be a group I know it needs to be:

Closed under matrix multiplication
The Associative Property holds
Contains an Identity Element
Every element needs to have an inverse

So the form of the matrices is such that all the elements are the same but not 0. How do I go about proving these?
Working through this problem, I seem to have hit a contradiction. Since G is a subgroup of the bigger $2x2$ nonsingular matrices group why does G not have the same identity element as its parent group? Namely \begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix}
Isn't the subgroup supposed to have the same identity element as its parent group?
Comment: But these matrices are not invertible.
Comment: For starters, what do you expect the identity element to look like?
Comment: @user99680 Yes, but it doesn't matter. It only shows it is not a subgroup of $GL_2(\mathbb R)$. But there are groups of non-invertible matrices. It simply means that the identity of the group is not the identity matrix.... A simpler example is the following: matrices of the type $\begin{bmatrix} a & 0 \\ 0 & 0 \end{bmatrix}$ with $a \neq 0$ are a group under multiplication, even if they are not invertible. The identity in this case is $\begin{bmatrix} 1 & 0 \\ 0 & 0 \end{bmatrix}$ and the inverse is $\begin{bmatrix} \frac1{a} & 0 \\ 0 & 0 \end{bmatrix}$...And when you multiply these matrices
Comment: @user99680 Since the identity of the group is NOT the identity matrix, it doesn't matter.
Comment: @N.S: But under the standard multiplication, these matrices are not invertible.Ah, maybe there is an identity for the subgroup that is not the same as the identity for the group?
Comment: @N.S: How do you know how multiplication is defined?
Comment: @user99680 Because, unless otherwise specified in the exercise, multiplication of matrices is the standard multiplication of matrices... And if it is not standard, what do you mean by invertible? ;)
Comment: @N.S: Good call.
Comment: ... you basically multiply the numbers in the first position, the rest of the matrix is irrelevant... Note that the invertibility of the matrix means $A A^{-1}=I_n$, while the inverse in the group means something else : $AB=E$, where $E$ is sometimes a different matrix. Just because we call them identity and inverse element, it doesn't mean they are the identity matrix and inverse matrix...
Comment: The matrices don't need to be invertible. They just need to be invertible on any subspace they ever touch. $x[1,1]^T[1,1]$ is only non-invertible on $[1,1]^T[1,1]$ if $x=0$.
Comment: I have learned so much from this question.
Answer: Hint
1) What is $\begin{bmatrix} x & x \\ x & x \end{bmatrix}\begin{bmatrix} y & y \\ y & y \end{bmatrix}$?
2) The multiplication of matrices is associative.
3) When you are looking for the identity you want
$$\begin{bmatrix} x & x \\ x & x \end{bmatrix}\begin{bmatrix} e & e \\ e & e \end{bmatrix}=\begin{bmatrix} x & x \\ x & x \end{bmatrix}$$
Now, do the multiplication on the left, what do you get?
4) With the $e$ from $3)$ solve
$$\begin{bmatrix} x & x \\ x & x \end{bmatrix}\begin{bmatrix} y & y \\ y & y \end{bmatrix}=\begin{bmatrix} e & e \\ e & e \end{bmatrix}$$
for $y$. Again, all you need to do is doing the multiplication...
P.S. In order for this to be a group, you need $x \neq 0$.
P.P.S Since $\begin{bmatrix} 1 & 1 \\ 1 & 1 \end{bmatrix}\begin{bmatrix} 1 & 1 \\ 1 & 1 \end{bmatrix}=2\begin{bmatrix} 1 & 1 \\ 1 & 1 \end{bmatrix}$, you can prove that
$$F: \mathbb R \backslash\{0 \} \to G$$
$$F(x) =\frac{x}{2} \begin{bmatrix} 1 & 1 \\ 1 & 1 \end{bmatrix}$$
is a bijection and it preserves multiplications. Since $\mathbb R \backslash\{0 \}$ is a group it follows that G must also be a group and $F$ is an isomorphism... But this is probably beyond what you covered so far...
Comment: 1.  $\begin{matrix}
  2xy & 2xy \\
  2xy & 2xy
 \end{matrix}$

2. Yup thats the easy one.

3. You did the multiplication on the left? Multiplying x by the identity element will give you x, like you have above..
Comment: @RoyM. The multiplication on the left is $\begin{bmatrix}
  2xe & 2xe \\
  2xe & 2xe
 \end{bmatrix}$. Now for which value of $e$ do you get:$$\begin{bmatrix}
  2xe & 2xe \\
  2xe & 2xe
 \end{bmatrix}=\begin{bmatrix}
  x & x \\
  x & x
 \end{bmatrix} \, ? ;)$$
Comment: Are you talking about your first bullet? \begin{bmatrix} x & x \\ x & x \end{bmatrix}\begin{bmatrix} y & y \\ y & y \end{bmatrix}

For which value of $e$ do I get what? I am sorry I am not following!
Comment: @RoyM. I am speaking about $3$. Keep in mind that identity in a group of matrices doesn't necessarily mean identity matrix ;)
Comment: Ahh I see what you're saying. And for your first comment, $e=\frac{1}{2}$?
Comment: @RoyM. Exactly... And now when you solve for the inverse, you have $\begin{bmatrix}
  2xy & 2xy \\
  2xy & 2xy
 \end{bmatrix} = \begin{matrix}
  \frac{1}{2} & \frac{1}{2} \\
  \frac{1}{2} & \frac{1}{2}
 \end{matrix}$. Thus $y=\frac{1}{4x}$...


nested routing like namespace in node.js

Question: I would like to nested the routes using router like we did using namespace ->
app.namespace('/', function () {
    app.get('/', main.index);
    app.get('contact', main.contact);
    app.get('about', main.about);
});
/* user */
app.namespace('/user', function () {
    app.get('login', user.login);
    app.get('logout', user.logout);
    // an example of namespace in namespace
    app.namespace('/settings', function () {
        app.get('/', user.settings);
        app.get('profile', user.profile);
    });
    /* REST CRUD */
    //read
    app.get('/:id?', user.read); // if is not set, go to user profile
    //create
    app.post('/', user.add);
    //update
    app.put('/', user.update);
    //remove
    app.delete('/', user.destroy);
});

I just want to nest the routes same as above but using routers. How???
Answer: I have find the solution and explaining here...
In app.js file :-
var express = require('express');
var routes = require('./routes/index');
var app = express();
app.use('/', routes);
In ./routes/index.js
router.get('/', function(req, res) {
// Home page
.....
});
router.get('/navigation1', function(req, res) {
// Nav1 page
.....
});
& more navigations.....

I am giving here some links. Check it out...
https://scotch.io/tutorials/learn-to-use-the-new-router-in-expressjs-4
Node.js express nested routes
Answer: You can use this package:
https://www.npmjs.com/package/express-namespace-routes

const express = require('express');
const routes = require('express-namespace-routes');
const app = express();

routes.prefix('/user', (user) => {
  user.post('/', (req, res) => res.send(''));
  user.get('/', (req, res) => res.send(''));
  user.get('/:id', (req, res) => res.send(''));
  user.delete('/:id', (req, res) => res.send(''));
  user.put('/:id', (req, res) => res.send(''));

  user.prefix('/settings', (settings) => {
    settings.post('/', (req, res) => res.send(''));
  });
});

app.use(routes);


Relating content types to be used in Views filters

Question: I have two content types:

Games, which have a list of Developers that worked on it.
Developers, which don't store the games they've worked on.

I need:

a view that lists Developers that you can filter by Game, but "Exposed Filters" only let me filter on fields on the Developer, so I'm not sure how to do this.
to be able to add to a list of people that worked on the Game when editing/creating, rather than have to update each Developer's list of Games they worked on.

How can I make an exposed filter which selects Developers where the Game has that Developer?
Answer: Nikit's response about using Relationships in the view is correct, but it's not clear you've have already set up the correct 'node references' between Games and Developers.
So, rather than maintain your own lists of Developers for a Game, you need to use the References module to add a field that allows 'connections' between these content types. You might also want the Corresponding node references module to auto-update the reference field on a Developer when you edit a Game, and vice versa.
From here you can properly relate Games and Developers, so Views can use these relationships and allow you access the associated Games from your Developers view.
Answer: You should use Relationships in Views, and attach second content as required.
Comment: I can point to some videos that describe using relationships: http://vimeo.com/22100751 http://drewish.com/node/127 http://www.drupalove.com/drupal-video/using-drupals-views-relationships
Comment: I'm not seeing how this would work. Can you be more specific?


Delphi2010: Writing code to assign Caption containing Unicode literal values or load unicode symbols from text file?

Question: How to make a Unicode program in Delphi 2010?
I have English Windows and "Current language for non-Unicode programs" is English too. Static controls look good but if I try to change them (Label.Caption := 'unicode value' or Memo.LoadFromFile(textFilename) ) the text looks like:  $^$&%*(#&#.
How to fix it?
Comment: @Rob: I disagree.  You've been around here for years. You can't hold a newbie to the same standards of quality that you aspire to in your own writing, and slap all sorts of negative effects on their posts if they don't measure up. That creates a hostile community that new people don't want to come participate in.
Comment: Easy, guys.  This is a new user. He doesn't need to be downvoted and close-voted for a question like this; he needs to edit the question and give a more clear answer.
Comment: StackOverflow needs a way to downvote a downvote.  Come on guys, this takes "heavy handed" to a new level, and not in a good way.  Thank the gods I didn't have "helpful" people like you around when I was finding my way in Delphi.
Comment: -1. All programs are Unicode programs in Delphi 2010. If you're getting garbage, then there's more to your problem that you need to describe here. You need to describe what you've done, what happens, and what you expected to happen instead. Please clarify. Post some code. Post some pictures, if you need to.
Comment: @Mason, this question *should* be down-voted. It's a lousy, unanswerable question. If Michael edits it to make it a good question, I'll re-vote. I'll also vote to re-open it, but again, only *after* it's a decent question.
Comment: I found an issue. The first project I have created with other Windows language settings, then I have changed settings in Windows. Delphi has saved all a project text not in UTF-8. Why! I just have saved the project and reopened it and I have seen that all characters has been changed. Why does Unicode Delphi save not in UTF-8???...
Comment: Yes, @Deltics, perhaps there does need to be some other way of showing disagreement with a down-vote. As it stands now, it looks like three people actually think this is a clear, useful question that shows research effort, which I really don't see. However, I think the comment I gave when I voted on this question was helpful because I explained its shortcomings, but it now occurs to me that I could have been even more helpful by also reminding Michael that he could edit the question and by mentioning that improving the question could change my vote.
Comment: All Delphi 2010 applications are Unicode. In addition, all versions of Windows in which Delphi 2010 applications can run (I think -- at least all non-ancient versions of Windows) are Unicode. You are doing something very wrong. Please give us a minimal project displaying the issues you are observing.
Comment: @Mason: It isn't that bad. No one can answer the question as it stands, and the OP can still edit it. If (s)he does, it won't be long before it is opened again.
Comment: Michael, if you'd like to ask about why Delphi saves files with a particular encoding, please post a new question about it. I don't think it's related to the issue you have in *this* question, but I'll again ask you to please *edit* this question to clarify exactly what problem you're having.
Comment: Thank everybody for helping. As I sad, Delphi 2010 has saved the project not in UTF-8, I have converted to UTF-8 and all have started to work!
Comment: I changed the title of the question and fixed the grammar.
Answer: Let me assume a bunch of things because you haven't given me very much data to go on.

You have used Delphi before, and you know about the fundamental type names like String, Char, and so on.

You may not be aware of the Unicode differences between Delphi 2007 (char=Ansichar/string=Ansistring) and Delphi 2009-or-later (including Delphi 2010 and XE) where Char=UnicodeChar, and String=UnicodeString.

The most common reason you would see garbage (represented in your question as the text looks like $^$&%*(#&#.") is if you have tried to directly manipulate byte-size AnsiCharacter data and coerce it in a wrong way into a UnicodeString.

MJN also noticed, from one of your comments that you are also having trouble with source code that contains unicode characters that was not saved as a UTF8 file...  When I try to put Unicode characters into a source file Delphi automatically asks me this question, which I assume you also see, and answer correctly (the correct answer is yes)... But your question doesn't mention this at all, you really should try to update  your question to specify the source of your problem.

Here is the right-click file format menu, from which you can change the encoding at any time, the recommended value is UTF8 as shown here:

You should definitely post the affected code that generates the incorrect string values.  You should start, not with a giant application that you are trying to port to Unicode Delphi (which is the fourth and largest assumption I'm making here) and rather, start with some small sample code.
here's an example of "badly written code", that happens to still work in Delphi 7, because each character is one byte in size, but this assumption does not travel upwards to 2009 and XE Delphi:
procedure Tform1.TestBad;
var
 x:PAnsiChar;
 s:String;
begin
  x := 'test';
  s := Copy(PChar(x),1,10);
  Self.Caption := s;
end;

here's the same contrived sample code "fixed" (more like not-intentionally broken) so it will at least work in delphi XE:
procedure Tform1.TestLessBad;
var
 x:PAnsiChar;
 s:String;
begin
  x := 'test';
  s := Copy(x,1,10);
  Self.Caption := s;
end;

The use of pointers above is contrived, and unnecessary, except that I am trying to teach with this example.
The first example will create unicode chinese characters in the caption of the form instead of showing the text 'test', because 2 bytes have become a single character because I have intentionally done something BAD to show you one easy way to generate this noise you speak of, by making mistakes in my code.
If you are having trouble with particular unicode code-points, let me suggest you try this notation:
c := Char($21CC);  // this is U+21CC (cool two arrows thingy used in chemistry to indicate a reversible reaction)

Alternatively you will see this, which is almost the same thing:
c := #$21CC; // U+21CC

Notice how you don't need a UTF8 encoded file to store things you write this way.
Answer: The comments

Why does Unicode Delphi save not in
  UTF-8?

and

Delphi 2010 has saved the project not
  in UTF-8, I have converted to UTF-8
  and all have started to work

seem to be related to the encoding of the Delphi project (dpr and/or pas) source code files. If they are set to ANSI for example, characters which do not belong to the current code page might be saved incorrectly.
The IDE (in Delphi 2009 at least) creates new units with file format set to ANSI. For mixed-language source code, UTF-8 (or one of the UCS flavours) has to be activated manually, using the context menu in the text editor (File Format | UTF8).
The IDE (in Delphi 2009) also seems not to have an option to set the default text format to something other than ANSI. (See How can I set the default file format in the Delphi IDE to UTF8?)

The short answer:
Set the file format for your source code to UTF-8.
(The Delphi 2009 IDE does not use Unicode by default, I guess this is still the same in Delphi 2010)
Comment: I took the liberty of editing the question for the OP, to at least make the title of the question saner.
Answer: If you migrated your project from an old Delphi version, check the font used in your dialogs. Not all fonts support all unicode characters.
I had a problem, which was apparently similar to yours: I had correct unicode strings in the debugger but in the application some of the special characters appeared as black squares. This was with an old program migrated from Delphi 6 where some captions where set through code. On new forms everything was ok (here the captions were set in the dialog editor, but this isn't actually relevant).
The problem was the font of all migrated forms. Delphi 6 used to use "MS Sans Serif" as font. But this font is missing most of the unicode characters. Switching to "Tahoma" solved my problem.


how to make AFNetworkReachabilityStatus the first priority of my app?

Question: I've made a function, called initnetwork in which I try to see if the network is reachable or not, and I call this function in my viewDidLoad, that's the first thing I do.
-(void)initNetwork {
    mainManager = [AFHTTPRequestOperationManager manager];
    mainManager.requestSerializer.timeoutInterval = 30;
    backgroundTaskManager = [AFHTTPRequestOperationManager manager];
    mainImgManager = [AFHTTPRequestOperationManager manager];
    backgroundImgManager = [AFHTTPRequestOperationManager manager];
    [MainView addSubview:labelForRefresh];
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        [defaults setInteger:status forKey:@"networkStatus"];
        if ([[AFNetworkReachabilityManager sharedManager] isReachable]) {
            [defaults setBool:true forKey:@"reachability"];
            labelForRefresh.hidden = true;
        }
        else {
            [defaults setBool:false forKey:@"reachability"];
            [self indicatorStop];
            labelForRefresh.hidden = NO;
            [self hide_button];
            [self hidden_button];
        }
        [self getNetworkAction];
    }];
}

The probleme is, that it is not waiting for the return of setReachabilityStatusChangeBlock, and keep going through my viewDidLoad, initialising many stuff, that I don't want to.
I've tried to put some
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{});
around, but it doesn't seems to work.
do someone have an explanation or a hint for me ?
Answer: Put your code, that depends on block completion inside of setReachabilityStatusChangeBlock: like this:
[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        [defaults setInteger:status forKey:@"networkStatus"];
        if ([[AFNetworkReachabilityManager sharedManager] isReachable]) {
           // put your  viewdidload code here (that depends on block completion)
        }
        else {
            // code
        }
        [self getNetworkAction];
    }];


canceled status blocking font download

Question: I have a page with some text that has been given a font-family of constitution:

This font was downloaded from a foundary and is defined for the page with an @font-face:

When the page renders, the browser goes out for the font but the request is blocked by a cancel and the text doesn't get the font-family applied:

Does anyone know what might be causing this cancel?  This used to work, and I can't imagine what I did or what happened to break it.
Thanks for any help.
Comment: Is there any error reported in console? Is this `Constitution.ttf` deployed in a different domain?
Comment: Yes! The error is: "Access to Font at https://example.com/fonts/Constitution.ttf from `http://example.com` has been blocked by CORS policy. The 'Access-Control-Allow-Origin' header contains multiple values: `http://example.com`, `https://example.com`, but only one is allowed. `http://example.com` is, therefore not allowed access."  Thank  you!  What is the best way to fix this?
Comment: There should be only one `Access-Control-Allow-Origin` header with only one origin (or wildcard sign). I guess this is caused by accidentally add additional `Access-Control-Allow-Origin` header in the server configuration. Please check my answer.
Answer: The Access-Control-Allow-Origin header expect only one origin, or a wildcard (*).
The error you mentioned in the question's comment ("The 'Access-Control-Allow-Origin' header contains multiple values ... but only one is allowed") clearly indicates that there are multiple values in Access-Control-Allow-Origin header, or there are multiple Access-Control-Allow-Origin headers.
To fix the issue, there should be only one Access-Control-Allow-Origin header, with only one origin value.

As mentioned in the question: "This used to work". I guess this issue is caused by accidentally add additional Access-Control-Allow-Origin header in the server configuration.

For reference, please check the W3C specification:

A resource can have one Access-Control-Allow-Origin header defined. The header must match the following ABNF:
Access-Control-Allow-Origin = "Access-Control-Allow-Origin" ":" ascii-origin | "*"
ascii-origin                = ASCII serialization of an origin
Comment: I fixed this with a mod_rewrite to send non-HTTPS requests to HTTPS.  But I'm curuous how I would fix it if I wanted to allow HTTP and HTTPS access. I've never specified an Accedd-Control-Allow-Origin header in the code so how did this get set, and how can I modify it?  Thanks
Comment: @Steve I guess `http://example.com` host the webpage. In that case, you only need to put `https://example.com` in the `Access-Control-Allow-Origin` header. If  `https://example.com` host the webpage, then put `http://example.com` in the `Access-Control-Allow-Origin` header. Otherwise, just use `*`.
Comment: If you've never specified `Access-Control-Allow-Origin` manually, my guess is: it is set by some module/plugin...
Answer:
Put this inside your virtual host definition or .htaccess file:
<FilesMatch ".(ttf|otf|woff|woff2|eot|ttc)$">
    Header set Access-Control-Allow-Origin "*"
    Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
</FilesMatch>

Restart Apache web server
Refresh the page multiple times (Hard Refresh)

canceled status blocking font download


Let X be the number of people that separate A and B

Question: The question is :
Six people, including A and B, stand randomly in a line. Let X be the number of people
that separate A and B, we have to calculate ,P(x), P(0) , p(1)...p(4)
solution: for P(1)
The total number of people including A and B is 6. Those 6 can be arranged in 6! ways = 720 ways.
P(1):So we need 1 human to be between A and B. So we need to choose 1 people out of 4(6-2, without A and B) ; because we excluded A and B. Therefore, the number of ordered ways to choose 1 people out of 4 is 4P1=4 ways.
If we consider A, B and the one human between them as one entity, we need to see how we can arrange this entity along with the 3 remaining people. Therefore, they can be arranged in 4! = 24 ways. One last thing, the A and B can also be interchanged as B and A. Therefore, A and B can be arranged in 2 ways. We can conclude from all of this that the number of ordered ways we can place 1 human between X and Y is $4\cdot24\cdot2 = 192$ ways.
and the probability for that is $192/6! =  4/15$
is my approach to the question correct?
Comment: Yes, this is fine so far.  Be careful about typing here though... asterisks are used to denote *italics* `*italics*` and **bold** `**bold**` and should not be used to represent multiplication.  Instead, use [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) and $\LaTeX$, typing `$4\cdot 24\cdot 2=192$` to get $4\cdot 24\cdot 2=192$ to make it cleaner to read.
Comment: there's no such thing as $P(x), P(1)$, etc. You meant you need to calculate $P(X=1), P(X+2)$, etc.
Answer: Your approach is correct.
Here is an alternative route.
We start with $6$ open spots and will select $2$ of them for placing $A$ and $B$ (no matter in what order). There are $\binom62=15$ equiprobable ways to select $2$ of these spots and exactly $4$ of these pairs will have exactly one spot in between.
So the probability that $A$ and $B$ will have exactly one person in between is $\frac{4}{15}$.
You could take advantage of this to find the other probabilities.


A trigonometric constraint problem (graphic included)

Question: I am working with the geometrical situation seen in the attached hand-drawn graphic below.
The given constants are $h, w, \phi, \text{ and }R$. My aim is to find $x$ as a function of those. The general constructive idea, is that the "leg" (hypotenuse) has an angle $\phi$ with vertical. This leg extends to the point where it must intersect with the circle circumference below (the constraint). This circle has radius $R$. The triangle marked in red is isosceles - perhaps worth noting.
Ofcourse we have: $x = R (\sin \frac{\theta_1}{2}-\sin \frac{\theta_0}{2})$, where $\sin \frac{\theta_0}{2} = (w/2 + b)/2R = (w/2 + h\tan \phi)/2R$.
But how to find $\theta_1$ - and from that $x$? The solution should be valid for all values of $\phi$ from $0$ to the limit at which the aforementioned leg becomes tangent to the circle below. By the way, what is that limit?
I have tried to solve this using the laws of sines and cosines. But it always seem that I end up with a triangle-situation with too little information - or it simply becomes too complicated. I have postponed working on it until I receive some feedback. It is likely trivial but nonetheless too time-consuming for me to solve right now :)

Thanks.
An elaboration of the accepted answer by André Nicolas:
Using the mechanical coordinate method this suddenly get much easier. And that was all I needed. Great. I will just write the algebraic solutions here.
We now know the following ($R$ is now $r$):
$x = \frac{1}{2} {\sin}^2 \phi \left(2 (h+r) \cot \phi + w {\cot}^2 \phi - \sqrt{(4 r^2 - w^2) {\cot}^2 \phi -4h(h + 2r) - 4(h+r) w \cot \phi} \right)$,
$y = h+r + \frac{1}{2} (w-2 x) \cot \phi$,
and
$z = x - \frac{1}{2} w - h \tan \phi$.
The angle $\theta_1$ can now be solved directly:
$\sin {\frac{\theta_1}{2}} = \frac{1}{r}\left( \frac{1}{4}w - \frac{1}{2} h \tan \phi - z \right)$
Answer: The question yields to mechanical coordinate methods. Put the origin at the centre of the circle, and the axes in the usual places. To save some possible confusion, what you call $x$ will be called $z$ in what follows.
Look at the slanty blue (?) line on the right. We find its equation. This line goes through the point $(w/2,R+h)$ and has slope $-\cot \phi$. So we know its equation, say $y=cx+d$. Substitute in $x^2+y^2=R^2$ to find the $x$-coordinates of the points of intersection with the circle. We can easily identify the relevant (smaller) one. So now we know $w/2+b+z$.
To find $w/2+b$, find the $x$-coordinate of the point of intersection of the lines $y=cx+d$ and $y=R$.  (A simpler way to find $w/2+b$ is given in your post. Just wanted to stress that we can fully give ourselves over to the method of coordinates.)
Now we know $w/2+b+z$ and $w/2+b$, so we know $z$.  If we need to, we can now find an explicit expression for $\theta_1$.
Comment: Thanks. All I needed. It seems to work - but would you be kind to check my added notes in the question above? There ofcourse the problem when $phi$ goes to zero. How could I deal with that? Perhaps by using another more general line description instead of slope intercept?
Comment: Could we compare notes? I used $r=10$, $h=3$, $w=12$, $\phi = \arctan (1/3)$. With this values I get $x=\frac{1}{10} \left(93-\sqrt{39}\right) = 8.6755$, $y = \frac{1}{10} \left(31+3 \sqrt{39}\right) = 4.9735$, and $\sin (\theta_1/2) = 1/100 \left(2 + \sqrt{39}\right) = 0.08245$. According to Mathematica.
Comment: @OleThomsenBuus: The procedure does not work when $\phi=0$, since $\cot 0$ is undefined. We can, in line with your suggestion, use the equation $(y-w/2)\sin\phi+(x-R-h)\cos\phi=0$ for the line. It is simplest, however, if you are writing a general program, to separate out the case $\phi=0$, where we can write down the answer without calculating. You will also need to deal with the fact that for any $h$, after a while you will have tangency, and then no intersection if $\phi$ is large enough. By the way, things are nicer if measure everything in $R$-units.


"call 'refresh'" error resulting from Grails WAR hot-deploy

Question: When my Grails WAR is hot-deployed to Tomcat and I refresh the page, I get this error:

1 Feb, 2010 7:00:51 PM org.apache.catalina.core.ApplicationDispatcher invoke
  SEVERE: Servlet.service() for servlet view-servlet threw exception
  java.lang.IllegalStateException: BeanFactory not initialized or already closed - call 'refresh' before accessing beans via the ApplicationContext
   at org.springframework.context.support.AbstractRefreshableApplicationContext.getBeanFactory(AbstractRefreshableApplicationContext.java:15

This error does not persist when Tomcat is restarted.
Comment: Can't help you with the servlet error, but I can tell you it doesn't have anything to do with the Javascript in your page. Something is wrong in Java land.
Comment: there should be another stacktrace preceding this one
Answer: ApplicationContext ctx = new ClassPathXmlApplicationContext();
Spring try to lookup the applicationContext.xml from the CLASSPATH, if the xml file can't be found, "BeanFactory not initialized or already closed" error will be thrown out. That is why you restart the tomcat it works just fine. However I don't know the real cause why the applicationContext.xml is not in the classpath during hot-deploy.
If you are running only one Grails application in your tomcat, you can try to put the applicationContext.xml in Tomcat classpath and try hot-deploy again.


10 wickets in an innings in international matches

Question: Jim Laker and Anil Kumble are the only 2 players who have taken 10 wickets in an innings in Test matches. Is there any other bowler who has taken 10 wickets in an innings in any kind of international format, including one-day internationals, Twenty20 internationals or any other international cricket organised by the ICC?
Comment: I'm clueless about cricket, but why does this post have a score of -7?
Comment: Just for clarification: taking a *10-wicket haul* often means taking 10+ wickets over the two innings of a Test match, which has been done many times. It's better to refer to taking *10 wickets in an innings*, so there's no misunderstanding.
Comment: @Lohoris Even I don't know what is wrong about this question.
Comment: Public service announcement: this question is being discussed on [meta](http://meta.sports.stackexchange.com/questions/564/why-does-this-post-have-such-a-low-score).
Answer:
Is there any bowler who take 10 wicket haul in any kind of international format either Test, ODI or T20?

At present, only two players you have mentioned have taken 10 wickets in an innings in any type of international matches.
Best bowling figure in ODI is: 8.0-3-19-8 by Chaminda Vaas of Sri Lanka vs Zimbabwe as Colombo (SSC)    on 8 Dec 2001.
Have a look at:

Best figures in an innings in Test matches
Best figures in an innings in ODI matches
Best figures in an innings in T20I matches
Best figures in an innings in Under-19s Youth Test matches
Best figures in an innings in Under-19s Youth ODI matches
Comment: @mkr9 - No. As you are talking about [SA tri-series](http://www.espncricinfo.com/ci/content/current/series/630758.html) it is not [an international tournament](http://i.stack.imgur.com/xKsSN.png).
Comment: why not there is world cup for all under-21,under-19 etc organised by ICC. Also for List -A matches, currently there is on going tournament hosted in South Africa.
Comment: I am not saying all Tournaments organised by ICC is a international tournament but in which different countries take part then will be it called.
Comment: In Test, ODI and T20 I know but I don't about other international tournament like Under-19, Under-21, List-A, etc.
Comment: @mkr9 - Under-21 (AFAIK), List-A are not international tournament. I have edited for Under-19 Test and ODI.
Comment: @mkr9 - Tournament organised by ICC doesn't always mean it's international. The meaning of List-A is all One dayers matches including ODI.
Answer: Mehboob Alam from Nepal took all 10 wickets in a World Cricket League match against Mozambique in 2008. Some very brief commentary on this feat can be found at the Guinness World Records website, and a match report is available on Cricinfo.
Comment: Nepal vs Mozambique is fairly clearly an international match. The OP's request includes "any kind of international format [...] organised by the ICC", so this is in scope.
Comment: True but it was not an international match.


Custom module error, does'nt show on the page

Question: I am new to drupal, so basically i have made a simple registration form. The problem is when i go to the registration form it shows a blank page .
i have made 3 files by the name of my custom module -registerme i.e.-
1.registerme.info
name = Register Me
description = A custom registration form
package = Drupal 7 Development
core = 7.x
files[] = registerme.module

2.registerme.module
<?php

function registerme_menu()
{
$items['registerme/newform'] = array(
  'title' => 'Registration Form',
    'page callback' => 'drupal_get_form',
    'page arguments' => 'registerme_newform',
    'access callback' => TRUE,                    //array('access content'),
    'file' => 'registerme.newform.inc',
    'weight' => '-2',
 );
return $items;
}

3.And finally i have registerme.newform.inc
<?php
function registerme_newform(&$form_state)
{
$form = array();
$form['account details'] = array(
    '#type' => 'fieldset',
    '#title' => t('Account Details')
);
$form['account details']['first name'] = array(
    '#type' => 'textfield',
    '#title' => t('First Name')
    );
$form['account details']['last name'] = array(
    '#type' => 'textfield',
    '#title' => t('Last Name')
    );
$form['account details']['mail'] = array(
    '#type' => 'textfield',
    '#title' => t('Last Name')
    );

$form['account details']['pass'] = array(
    '#type' => 'password',
    '#title' => t('Password'),
    '#maxlength' => 60,
    '#size' => 15,
    '#required' => TRUE,
    );
$form['account details']['pass'] = array(
    '#type' => 'password_confirm',
    '#description' => t('Enter the same password'),
    '#size' => 15,
    );
$form['home'] = array(
    '#type' => 'fieldset',
    '#title' => 'Home Address',
);
$form['home']['street'] = array(
    '#type' => 'textfield',
    '#title' => 'Street Address',
);
 $form['home']['city'] = array(
    '#type' => 'textfield',
    '#title' => 'City',
);
 $form['work'] = array(
    '#type' => 'fieldset',
    '#title' => 'Work Address',
);
$form['work']['street'] = array(
    '#type' => 'textfield',
    '#title' => 'Street Address',
);
 $form['work']['city'] = array(
    '#type' => 'textfield',
    '#title' => 'City',
);
 $form['submit'] = array(
     '#type' => 'submit',
     '#value' => t('Register Me'),
 );
 return $form;
}
function registerme_newform_submit(&$form, &$form_state)
{
dsm($form_state);
}
function registerme_newform_validate(&$form, &$form_state)
{
// Some validation to be done on fields.
}

where i am doing wrong getting errors like
Warning: Invalid argument supplied for foreach() in menu_unserialize() (line 400 of
    C:\webserver\Apache\htdocs\Starter\includes\menu.inc).
Warning: array_merge() [function.array-merge]: Argument #1 is not an array in
    menu_get_item() (line 479 of
    C:\webserver\Apache\htdocs\Starter\includes\menu.inc).
Warning: call_user_func_array() expects parameter 2 to be array, null given in
    menu_execute_active_handler() (line 516 of
     C:\webserver\Apache\htdocs\Starter\includes\menu.inc).
Warning: Invalid argument supplied for foreach() in menu_unserialize() (line 400 of
      C:\webserver\Apache\htdocs\Starter\includes\menu.inc).

The form dislpays a blank page when i click on the menu listing Register Me and the url is
    localhost/Starter/?q=registerme/newform
Answer: Error in hook_menu implementation ! See right code below.
function registerme_menu() {
  $items['registerme/newform'] = array(
    'title' => 'Registration Form',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('registerme_newform'), // Should be array !
    'access callback' => TRUE,                    //array('access content'),
    'file' => 'registerme.newform.inc',
    'weight' => '-2',
  );
  return $items;
}

function registerme_newform($form, &$form_state) {

}

function registerme_newform_submit($form, &$form_state)
{
  dsm($form_state);
}
function registerme_newform_validate($form, &$form_state)
{
// Some validation to be done on fields.
}

Clear menu cache before checking !
Comment: It's not recommend to re-invent the same wheel in Drupal. Drupal provides lot of out of the box solutions. If you want to add fields to user registration form check profile2 module !!
Comment: Thanks Anil just one small error is left.
Warning: Parameter 1 to registerme_newform() expected to be a reference, value given in drupal_retrieve_form() (line 800 of C:\webserver\Apache\htdocs\Starter\includes\form.inc)
Help me out.
Comment: See the updated answer for change in signatures!
Comment: Hi, i know i am getting after your life but want to ask that can i use this registration form to register users and login accordingly with this form fields say name and password.Can this be acheived and how if possible .Just need guidance plz direct.I will br greatful to you.Thanks


Morris Chart convert data from string to object

Question: I have this string variable built dynamically:
var vData = "[{value: 7, label: '1'},{value: 45, label: '2'},{value: 38, label: '4'},{value: 9, label: '7'}]";

How can I convert my string variable into an array to pass the data parameter?
I've tryed in Javascript with: JSON.parse(vData), but don't work.
In a separated PHP file, I've tryed with: echo json_encode($arr); at the end of PHP file, but don't work.
Where am I wrong?
Comment: You'll have to wrap your strings and property names in double quotes for `JSON.parse` to work. E.g.: `'[{"value": 7, "label": "1"}]'`
Comment: What data parameter?
Comment: Morris.Donut({
 element: 'show-graph',
 data: vData,
 formatter: function (x) { return x + "%"}
}).on('click', function(i, row){
 console.log(i, row);
});
Answer: You'll have to wrap your strings and property names in double quotes for JSON.parse to work. E.g.: [{"value": 7, "label": "1"}]
I'd strongly suggest fixing this in your string generation code, but just to show you it works (definitely not the right regex approach):

var data = "[{value: 7, label: '1'},{value: 45, label: '2'},{value: 38, label: '4'},{value: 9, label: '7'}]";

data = data.replace(/value/g, '"value"');
data = data.replace(/label/g, '"label"');
data = data.replace(/\'/g, '"');

console.log(JSON.parse(data));


Is the difference between two iid log-concave distributions still log-concave?

Question: Assume two iid random variables X and Y, with continuous and differentiable pdf $f$ and cdf $F$. Let Z=X-Y. Is the pdf of Z log-concave?
Answer: The density of the difference $Z=X-Y$ is
$$g(z)=\int f(x)f(z+x)\text{d}x$$Then
\begin{align*}
g(\alpha z+(1-\alpha) w) &= \int f(x)f(\alpha z+(1-\alpha) w+x)\text{d}x\\&= \int f(x)f(\alpha (z+x)+(1-\alpha) (w+x))\text{d}x\\&= \int f(x)\exp\{\ln f(\alpha z+(1-\alpha) w+x)\}\text{d}x\\&\le\int f(x)\exp\{\alpha\ln f(z+x)+(1-\alpha)\ln f(w+x)\}\text{d}x\quad\text{[log-concavity of $f$]}\\&=\int \exp\{\alpha[\ln f(x)+\ln f(z+x)]+(1-\alpha)[\ln f(x)+\ln f(w+x)]\}\text{d}x\\&=\int \exp\{\ln f(x)+\ln f(z+x)]\}^\alpha\,\exp\{[\ln f(x)+\ln f(w+x)]\}^ {(1-\alpha)}\text{d}x\\&\le\left(\int \exp\{\ln f(x)+\ln f(z+x)]\}\text{d}x\right)^ {\alpha}\\
&\qquad\times\left(\int\exp\{[\ln f(x)+\ln f(w+x)]\}\text{d}x\right)^ {(1-\alpha)}\qquad\text{[Hölder's inequality]}
\end{align*}
and
$$\ln g(\alpha z+(1-\alpha) w) \le \alpha \ln g(z) + (1-\alpha) \ln g(w)$$


Mostrar dados dinamicamente

Question: Tenho esse ajax que faz a requisição de uma lista de nomes para mim.. este é o código em javascript puro:
 function listagem() {

 var lista = {

idUsuario: document.querySelector(".campo").value,
token: document.querySelector(".campo-token").value
};

let xhr = new XMLHttpRequest();
var variavel = document.querySelector(".token-servico").innerHTML;
xhr.open("POST", "http://listAll", true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.setRequestHeader("Authorization", "Bearer " + variavel);

xhr.addEventListener("load", function () {

  if (xhr.status == 200) {

    window.sessionStorage.setItem('lista', xhr.responseText);

    var lista = window.sessionStorage.getItem('lista');

    lista = JSON.parse(lista);

    let x = document.querySelector('#body')

    lista.map(item => {

      x.innerHTML += '
'+ item.nome +'
'
    });

}

Porém, do jeito que está a listagem aparece só depois que eu clico num botão. O que posso fazer para que a lista apareça assim que a página for acessada?
Grato a quem responde
Comment: Apenas isso: `window.onload = listagem;`
Answer: Altere a função listagem() para document.addEventListener("DOMContentLoaded", function(event){, que irá executar o código quando a página for carregada:
Sem mencionar que há trechos no seu código sem fechamento que corrigi abaixo:
document.addEventListener("DOMContentLoaded", function(){

   var lista = {

      idUsuario: document.querySelector(".campo").value,
      token: document.querySelector(".campo-token").value
   };

   let xhr = new XMLHttpRequest();
   var variavel = document.querySelector(".token-servico").innerHTML;
   xhr.open("POST", "http://listAll", true);
   xhr.setRequestHeader("Content-type", "application/json");
   xhr.setRequestHeader("Authorization", "Bearer " + variavel);

   xhr.addEventListener("load", function () {

      if (xhr.status == 200) {

         window.sessionStorage.setItem('lista', xhr.responseText);

         var lista = window.sessionStorage.getItem('lista');

         lista = JSON.parse(lista);

         let x = document.querySelector('#body')

         lista.map(item => {

            x.innerHTML += '
'+ item.nome +'
'
         });
      }
   });

});

Mostrar dados dinamicamente


Can you hold a table tennis paddle with two hands?

Question: By ITTF regulation, is it legal to hold a paddle with two hands?
On one serve, someone managed to return by using his normal hand with the addition of his other to stabilize the paddle better. Is that legal?
In ITTF guidelines
it says

2.5.5 The racket hand is the hand carrying the racket.
2.5.6 The free hand is the hand not carrying the racket; the free arm is the arm of the free hand.
2.5.7 A player strikes the ball if he or she touches it in play with his or her racket held in the hand, or with his or her racket hand below the wrist.

However it fails to say that both hands can't be the racket hand.
Answer: Yes, it is legal to hold the racket with two hands.
During a serve, you need to hold the racket with one hand, because you need to hold the ball with your free hand.
From the ITTF Handbook, 2.06 (The Service):

2.06.01   Service shall start with the ball resting freely on the open palm of the server's stationary free hand.

After the service, you do not need a free hand.  There is no rule prohibiting holding the racket with two hands.
The ITTF Handbook for Match Officials (PDF) makes it clear that it is permissible to switch hands during a rally:

9.3  For the same reason he or she cannot make a good return by throwing his or her racket
  at  the  ball,  because  the  racket  does  not  "strike"  the  ball  if  it  is  not  held  in  the  racket hand at the moment  of impact. However,  a player may transfer his or her racket from
  one hand to the other during play and strike the ball with the racket held alternately in
  either hand, because the hand holding the racket is automatically the "racket hand".

In order to switch hands, you need to hold the racket in both hands at some point.
Comment: @Yaitzme That's not a rule, just a fact. Unless you are throwing the racket from one hand to the other during the match, if you switch hands during play, there will be a point where both hands are holding the racket.
Comment: 'Hold the racket in both hands at some point.' Is there a reason behind including that rule?
Comment: Seems rather silly though to use that technicality to say it can be held in both hands *and strike the ball as such*, which is a very different thing than just changing hands.  **strike the ball with the racket held alternately in either hand** seems to indicate just one hand is legal.
Comment: @Joe Keep in mind that the last quote is not a rule, it is just a guideline for match officials. My point for including it was to show that they acknowledge that there is no prohibition against holding the racket with two hands during play. If it was illegal to held the racket with two hands while hitting the ball, there would need to be an explicit rule prohibiting that.


On the transport equation $x \cdot \nabla u = |x|^2$

Question: I have no clue about how to  solve the following system
\begin{equation*}
 \begin{cases}
 x\cdot\nabla u=|x|^2, \quad x\in\mathbb{R}^n, \\
 u|_{x_1=1}=3x_n.
 \end{cases}
 \end{equation*}
Study the domain where the function is defined.
Can you help me with some hints?
Answer: Since
$$
x \cdot \nabla u = |x|^2,
$$
but also
$$
x \cdot x = |x|^2,
$$
I would try
$$
\nabla u = x,
$$
which leads to
$$
u(x) = {1 \over 2} x \cdot x + {\tt const}.
$$
In general, I would recommend looking into the method of characteristics.
Answer: Use the method of characteristics to decompose the problem. Observe, we have the string of equations:
$$\frac{dx_1}{x_1} = \ldots = \frac{dx_n}{x_n} = \frac{dz}{x_1^2 + \ldots x_n^2}$$
Solving for the constant characteristics for the first n-1 equations, we get:
$$\phi_i = \frac{x_{i-1}}{x_i}$$
So the last equation becomes:
$$\frac{dx_n}{x_n} = \frac{dz}{x_n^2 \phi_{n-1}^2(1 + \phi_{n-2}^2(\ldots (1 + \phi_1^2) \ldots )))}$$
Which, if we allow $\psi := \phi_{n-1}^2(1 + \phi_{n-2}^2(\ldots (1 + \phi_1^2) \ldots )))$, then this boils down to:
$$\frac{dz}{\psi} = x_n dx_n$$
$$\implies \frac{z}{\psi} = \frac{1}{2}x_n^2 + \eta(\phi_1, \ldots, \phi_{n-1})$$
$$\implies z = \psi(\frac{1}{2}x_n^2 + \eta)$$
where we defined $\psi$ already, which we know equals:
$$\psi = \frac{|x|^2}{x_n^2}$$
and $\eta$ is a function on the constants $\phi_1, \ldots, \phi_{n-1}$.
This leads to:
$$u = \frac{1}{2} x \cdot x + \eta(\phi_1, \ldots, \phi_{n-1})\frac{|x|^2}{x_n^2}$$
Now considering the initial conditions:
$$u(x_1 = 1, \cdot ) = 3x_n = \frac{1}{2}\sum_{i=1}^n x_i^2 + \eta(1, \phi_2, \ldots, \phi_{n-1}) \frac{1}{x_n^2} \sum_{i=1}^n x_i^2$$
$$\implies 3x_n^3 - \frac{x_n^2}{2}\sum_{i=1}^n x_i^2 = \eta(1, \phi_2, \ldots, \phi_{n-1}) \sum_{i=1}^n x_i^2$$
$$\implies \frac{3x_n^3}{|x|^2} - \frac{x_n^2}{2} = \eta(1, \phi_2, \ldots, \phi_{n-1}) $$
Of course we can easily translate the variables $\phi_2 = x_2, \phi_3 = \frac{x_3}{x_2}, \ldots$ which instantly makes $\eta$ a function of $x_2, \ldots, x_n$. Therefore,
$$ \implies \eta = \frac{3x_n^3}{1 + \sum_{i=2}^n x_i^2} - \frac{x_n^2}{2}$$
Thus, we get:
$$u = \frac{1}{2} x \cdot x + |x|^2 \left ( \frac{3x_n}{1 + \sum_{i=2}^n x_i^2} - \frac{1}{2} \right )$$
Which simplifies to:
$$u = x \cdot x  \left ( \frac{3x_n}{1 + \sum_{i=2}^n x_i^2} \right )$$


Using bash to add an xml tag to specific location

Question: Hi I've been looking around for a while and haven't found a viable solution. I am new to bash so apologies!
I am trying to add an xml function tag <generalSideMenu /> to a specific position in an xml file underneath <null>.
I also want to run this script from a text file that I am running line by line from the controller.
Hope that all makes sense and thank you in advance for your help!
Comment: Parsing xml with base/sed/awk whatever is a definitely bad idea. Use proper parser libraries from Ruby/Python whatever you want to
Answer: Use a proper XML handling tool. For example, in xsh, you can just type
open file.xml ;
xinsert element generalSideMenu into //null ;
save :b ;


Setup IR Remote Control Using LIRC for the Raspberry PI (RPi)

Question: After much searching I was surprised and dismayed about the conflicting information on how to setup IR remote control for my RPi project. I thought it would be easy but setting up Linux InfraRed Control (LIRC) has been problematic for a long time
But much changed in June 2019 with the release of the Buster version of Raspbian making much of the tutorials out there worthless. Many tutorials have you create a hardware.conf file but LIRC does not need nor want it and the lirc-rpi module has been replaced with the gpio-ir module.
So how do you set up LIRC on the RPi using Raspbian (Buster)?
Answer: This answer assumes the RPi is running raspbian (version Buster Jun 2019). Also a working knowledge of the terminal, basic commands from the command prompt and editing text files is assumed.
Step 1: Install lirc
1) Open terminal window and install LIRC. Be forewarned that this will likely raise an error "Failed to start Flexible IR remote input/output application support" as the installed files now have .dist appended and the suffix must be removed as noted below. Not hard but frustrating.
$ sudo apt-get update
$ sudo apt-get install lirc

----DON'T WORRY! as this will likely raise an error "Failed to start Flexible IR remote input/output application support" as the .dist suffix needs to be deleted from lirc_options.conf. Just copy the file as shown.
$ sudo cp /etc/lirc/lirc_options.conf.dist /etc/lirc/lirc_options.conf

2) Reinstall lirc now that the lirc_options.conf file has been renamed
$ sudo apt-get install lirc

Step 2: Edit lirc_options.conf
Edit /etc/lirc/lirc_options.conf as follows by changing these two lines:
:
:
driver = default
device = /dev/lirc0
:
:

Step 3: Perform copy to remove .dist suffix from lircd.conf.dist
Remove suffix .dist from /etc/lirc/lircd.conf.dist
$ sudo cp /etc/lirc/lircd.conf.dist /etc/lirc/lircd.conf

Step 4: Edit config.txt
Edit /boot/config.txt by adding one line in the lirc-rpi module section as follows. This example assumes the RPi is 'listening' on BCM Pin 17 for the IR receiver but any RPi IO pin can be used. I have not tried it yet but if you want to send commands from the RPi then add and uncomment the 4th line as shown below to send IR commands on BCM pin 18
:
:
:
# Uncomment this to enable the lirc-rpi module
#dtoverlay=lirc-rpi
dtoverlay=gpio-ir,gpio_pin=17
#dtoverlay=gpio-ir-tx,gpio_pin=18
:
:
:

Step 5: Check status and reboot
1) Stop, start and check status of lircd to ensure there are no errors!
$ sudo systemctl stop lircd.service
$ sudo systemctl start lircd.service
$ sudo systemctl status lircd.service

2) Reboot
$ sudo reboot

Step 6: Test remote
This step assumes you have have a IR receiver hooked up to your RPi on the pin specified in config.txt.
1) stop LIRCD service and test remote using mode2 command
$ sudo systemctl stop lircd.service
$ sudo mode2 -d /dev/lirc0

3) Point the remote at the receiver and press some buttons. You should see something LIKE this:
:
:
space
pulse
:
:

4) Press Ctrl-C to exit
5) Your IR receiver is setup and ready to proceed to Part 2 and be accessed in python.
Comment: Thanks for answer. What is the difference between `gpio_pin` and `gpio_in_pin` in config.txt? What is the difference between `lirc-rpi` and `gpio-ir`?
Comment: I think this answer is an extract from https://www.instructables.com/Setup-IR-Remote-Control-Using-LIRC-for-the-Raspber/ , here is the Part 2: https://www.instructables.com/Easy-Setup-IR-Remote-Control-Using-LIRC-for-the-Ra/
Comment: This answer is fine if you actually want to use the *default* driver (which has a silly name). However, LIRC is a complex and flexible tool with other drivers available, notably the default *devinput*. See e. g., the official docs at  http://lirc.org/html/configuration-guide.html
Comment: I could not run `mode2` command. I received `Cannot initiate device /dev/lirc0` error. I must also stop socket `sudo systemctl stop lircd.socket`
Answer: The above solution doesn't work with Raspbian Buster Kernel 4.19. I've checked it with (Raspbian Buster version 2020-05-27)
However, it works fine if you use only irsend that sends IR signals. If you want to receive & record IR signals using irrecord, mode2, irw or irexec commands some staff required.
Step - 1: Install a patch to use irrecord with kernel 4.19.X and gpio-ir
sudo su -c "grep '^deb ' /etc/apt/sources.list | sed 's/^deb/deb-src/g' > /etc/apt/sources.list.d/deb-src.list"
sudo apt update
sudo apt install devscripts

Step - 2: If you have already installed lirc with apt, please uninstall it as follows
sudo apt remove lirc liblirc0 liblirc-client0

Step - 3: Installing with a patch for gpio-ir in Raspbian Buster
sudo apt install dh-exec doxygen expect libasound2-dev libftdi1-dev libsystemd-dev libudev-dev libusb-1.0-0-dev libusb-dev man2html-base portaudio19-dev socat xsltproc python3-yaml dh-python libx11-dev python3-dev python3-setuptools
mkdir build
cd build
apt source lirc
wget https://raw.githubusercontent.com/neuralassembly/raspi/master/lirc-gpio-ir-0.10.patch
patch -p0 -i lirc-gpio-ir-0.10.patch
cd lirc-0.10.1
debuild -uc -us -b
cd ..
sudo apt install ./liblirc0_0.10.1-5.2_armhf.deb ./liblircclient0_0.10.1-5.2_armhf.deb ./lirc_0.10.1-5.2_armhf.deb

Note: The final install command will fail. You have to configure /boot/config.txt and /etc/lirc/lirc_options.conf files.
Step - 4: Edit /boot/config.txt
:
:
:
# Uncomment this to enable the lirc-rpi module
#dtoverlay=lirc-rpi
dtoverlay=gpio-ir,gpio_pin=17
#dtoverlay=gpio-ir-tx,gpio_pin=18
:
:
:

Step - 5: Perform copy to remove .dist suffix from lirc_options.conf.dist and lircd.conf.dist
sudo cp /etc/lirc/lirc_options.conf.dist /etc/lirc/lirc_options.conf
sudo cp /etc/lirc/lircd.conf.dist /etc/lirc/lircd.conf

Step - 6: Reinstall
sudo apt install ./liblirc0_0.10.1-5.2_armhf.deb ./liblircclient0_0.10.1-5.2_armhf.deb ./lirc_0.10.1-5.2_armhf.deb

Step - 7: Edit /etc/lirc/lirc_options.conf
:
:
driver = default
device = /dev/lirc0
:
:

Step - 8: Check status and reboot
Check:
$ sudo systemctl stop lircd.service
$ sudo systemctl start lircd.service
$ sudo systemctl status lircd.service

Reboot:
$ sudo reboot

Step - 9: Test remote
$ sudo systemctl stop lircd.service
$ sudo mode2 -d /dev/lirc0

Here is the reference for full description
Answer: Make your custom remote control used by installing one python module.
Circuit Diagram link

Install ircodec
Run this command in terminal "sudo systemctl start pigpiod"
Receive and transmit IR signal (https://pypi.org/project/ircodec/)


Are Reversibly Encrypted Passwords safe, and Why isn't it working when enabled for a user?

Question: In my event log, when my router tries to use Radius to authetnicate I get the following:

"""The user could not be authenticated
  using Challenge Handshake
  Authentication Protocol (CHAP). A
  reversibly encrypted password does not
  exist for this user account. To ensure
  that reversibly encrypted passwords
  are enabled, check either the domain
  password policy or the password
  settings on the user account. """

However, I enabled that for the account I am using in the User's Properties in AD.   Is there some other place this needs to be enabled, or maybe I have to wait for it to replicate or restart a service (Other than the Radius one)?  The IAS server is the same machine as a domain controller, and I made the change on that machine, so I would think it would take effect right away.
Also, just how unsafe is it to "reversibly encrypted passwords" ?
Edit:
I should also probably say why I am doing this in case there is a better way.  I am setting up a Cisco router to by an endpoint for Client-Initiated L2TP/IPSec tunnels. I want to authenticate against AD, so if there is a better way to handle the authentication please do let me know :-) Ideally, I could still use the built-in Windows VPN Client.
Comment: I suppose, suggesting you choose an alternate VPN technology that doesn't require you kill the security of your domain won't be accepted?
Comment: If the Password policy the GPO is set to 'disabled', does that override any individual user settings?
Comment: The password policy attribute I meant was  "Store passwords using Reversible Encryption".
Answer: Microsoft's TechNet page on this (here) basically says:

"Storing passwords using reversible
  encryption is essentially the same as
  storing plaintext versions of the
  passwords. For this reason, this
  policy should never be enabled unless
  application requirements outweigh the
  need to protect password information."
Comment: Ya, saw that. That is the description for the setting the GPO
Answer: mh's link is spot on - once something is stored in a way that it can be recovered it's should be considered no better than plaintext. As it is implemented in AD enabling reversible encryption means that anyone (or anything) with Domain Admin rights can decrypt passwords because they have access to the global LSA secret which is the only part of the process that is used that is secret in any sense, everything else involved can be read from the AD by anyone or is contained in a DLL that can be manipulated\reverse engineered.
From an attack perspective if someone has Domain Admin rights it's already game over but from an internal security perspective it also means that Domain Admins can decrypt passwords into the original plain text which is not good. If nothing else I wouldn't want to be facing a security investigation where the key evidence was event log entries showing a user logging in and out using a password that technically I could know if I wanted to.
There is an interesting set of blog entries by Niels Teusink on the subject starting here.
There are many better alternatives in terms of authentication (X.509 Certs,  One Time Password Tokens, Smart Cards ..) but whether you can use them or not depends on your application and the client system the users need to use. If you have full control of the environment you should be able to find a solution that allows you to avoid using them but implementing them properly may be costly and your users may find them inconvenient.
Edited following your update I'd suggest using AD Integrated Certificates, it will be a bit of work but the end result is solid and you can reuse the capability for lots of other things.
Answer: Why it wasn't working was apparently because the password has to be reset.  I was able to do this via Active Directory.
Also, it seems I can configure the router and the Radius server to use ms-chap-v2 which doesn't require that I store the passwords with reversible encryption.


Why $d(u^k)=kdu(u^{k-1})$ without knowing $u$ is a commutative element?

Question: This is related to McCleary's User's guide to spectral sequences, Chpt 1, Example 1.H.
Suppose $V,W$ are graded $Q-$algebra and $E_2=V\otimes_QW$ is bigraded algebra converging to $H^\star=Q$. Assume $V\cong Q[x_{2n}]$ where $x_{2n}$ is of degree 2n to make $V$ commutative.
Consider differential action on $E_2^{0,\star}$. Take any $1\otimes u\in Q\otimes_QW^\star=E_2^{0,\star}$. $d(u)\in V\otimes_QW$ for sure. So $d(1\otimes u)=\sum_iv_i\otimes w_i$ for some $v_i,w_i$.
Suppose $u$ is of degree $l$ in $W^\star$. Then $(1\otimes u)\cdot\dots\cdot(1\otimes u) =(1\otimes u^k)$ where $\cdot$ is in $k$ times.
Now consider $d(1\otimes u^k)=d((1\otimes u)^k)$. In particular, this is asking for general derivation acting on an element $x^k$. Suppose $d:A\to A$ is degree 1 derivation with $x\in A$ with $A$ graded commutative. Consider $d(x^2)=dx(x)+(-1)^{|x|}xd(x)$. Now to commute $xd(x)$, I need to pick up an extra sign. In particular, I am not convinced that $d(1\otimes u^2)=2d(1\otimes u)(1\otimes u)$.
The book says $d(1\otimes u^k)=k\sum_iv_i\otimes w_iu^{k-1}$. If I specialize to $k=2$, I have $d(1\otimes u^2)=2d(1\otimes u)(1\otimes u)$
$\textbf{Q:}$ How did the book reach conclusion that $d(1\otimes u^k)=kd(1\otimes u)(1\otimes u^{k-1})$? If $u$ is of even degree, I could believe this is the case but this may not be the case. The goal is to check $W=\wedge[y_{2n+1}]$.(i.e. $W$ is exterior algebra generated by 1 variable.)
$\textbf{Q':}$ Given $V=Q[x_{2n}],W=\wedge[y_{2n+1}]$ graded algebra as above, I can construct $E_2$. However, it seems that $E_2$'s differential map is extra information from $V,W$ graded algebra structure.
Answer: Regarding Q, I agree that this may not be the case if $u$ is in odd degree. In his proof, though, if $u$ is in odd degree, then $u^2$ will be forced to be zero ("If $W^*$ contains any other elements ..." on p. 21). So the formula is only used when $u$ is in even degree.
Regarding Q', it's not a question but a statement. In general, the differential $d_r$ of a spectral sequence is extra information beyond the identification of $E_r$. Sometimes you can deduce what $d_r$ must be, as in this example, but certainly not always.
Comment: Thanks a lot for clarification.


Any one can help me to get the answer of this integral?

Question: $g$ has an exponential distribution with rate parameter $m>0$. ${\rm Pr}(g)=m e^{-mg}$.
Compute $E[g^{2/a}]=$ where $a$ is a constant.
So I expanded it as $m \int_0^\infty g^{2/a}  e^{-mg} dg =$?
Answer: Hint: Substitute $u=mg$ and this will be recognized as a Gamma function expression.


Espaçamentos Cross-browser em Mail Marketing

Question: Estou desenvolvendo uma peça de E-mail Marketing e estou tendo problemas com espaçamentos de table, tr e td nos navegadores IE e com o Outlook e Outlook WebmailApp
Os navegadores renderizam corretamente, se você notar os cantos arredondas de cima dos boxes, que são inseridos como imagem ficam com um espaço em branco entre eles e a próxima Table, eu gostaria que esse espaços saíssem, como acontece no gmail por exemplo.
Outro problema é que não consigo aplicar cor de fundo no Hotmail, simplesmente não vai..
Estou testando pelo: http://putsmail.com/
Segue o código que estou usando, se alguém souber de algo que estou fazendo errado ou que possa me ajudar, qualquer ajuda seria bem vinda, Obrigado.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Lorem ipsum lorem ipsum lorem </title>

                            Lorem ipsum lorem ipsum lorem

                             Lorem Lorem Lorem
                            Lorem Lorem
                              | Lorem Lorem Lorem Lorem
                            Lorem Lorem

                            Lorem ipsum lorem ipsum lorem

                            Lorem ipsum lorem ipsum lorem

                            Lorem Lorem
                            R$

                            XX,XX

                        Lorem ipsum
                        X,XX
                        Lorem ipsum

                         xxx pontos

        Lorem IpsumLorem IpsumLorem Ipsum

        Lorem IpsumLorem Ipsum

                 xxx

        Ips um XX,XX por
        Ipsum
        R$

        XX,xx

        Lorem2 Ipsum2 Lorem2 Ipsum2 Ipsum2

        Lorem2 Ipsum2 Ipsum2

                 xxx

        Lo remXX,xx por
        Ipsum
        Lo

        XX,xx

Answer: Colei seu código na ferramenta e vi que faltou fechar um  na linha 55.
Eu ia falar pra você testar essas coisas, mas acho que você já tentou:

colocar style="display:block" nas imagens.
colocar a cor de fundo na  e a tabela dentro, para ver se pega.

Mas fazer email mkt é realmente chatinho. Geralmente eu exporto das slices do Photoshop/Fireworks mesmo, porque apesar do código ser sujo, é isso que os programas entendem :/
Comment: `style="display:block"` nas imagens é indispensável.


How to update with LINQ an object property knowing its name?

Question: My problem is very simple : I am parsing an Excel file containing the name of the SQL column, and its value.
I would like, with LINQ, to create my object and set its property, knowing its name. How can I do it ? I would like to do something like :
object obj = new object();
obj["property_name"] = "test";

but instead I can only do something like obj.propertyName which doesn't suite my case.
Thank you.
Comment: Another useful life lesson "Don't sneer".
Comment: How you retrieve information from `Excel` file?
Answer: You can use Anonymous Types
Look -> http://msdn.microsoft.com/en-us/library/vstudio/bb397696.aspx
var myObj  = new { property_name = "test"};

Answer: you could do this with Reflection...
obj.GetType( ).GetProperty( "property_name" ).SetValue( obj, "test" );

// EDIT:
sorry, i give you the wrong code-example. i have made an update.
Comment: I have to specify an index in the SetValue but I can't manage to get anything but "Object cannot be stored in an array of this type."


Changing Path using 'sed'

Question: I am trying to change the path using 'sed'
sed -i "s|METASPLOIT_PATH=/opt/metasploit/apps/pro/msf3||METASPLOIT_PATH=/opt/metasploit-framework|g" config/set_config

but an error showed up which I am neither understanding nor expecting
sed: -e expression #1, char 51: unknown option to `s'

What does this mean??
Answer: Looks like a typo to me, you have a duplicate pipe character in the middle of the substitute expression.
The following command works:
sed -i "s|METASPLOIT_PATH=/opt/metasploit/apps/pro/msf3|METASPLOIT_PATH=/opt/metasploit-framework|g" config/set_config

Answer: there is two consecutive pipes in your command
try :
 sed -i "s|METASPLOIT_PATH=/opt/metasploit/apps/pro/msf3|METASPLOIT_PATH=/opt/metasploit-framework|g" config/set_config

Changing Path using 'sed'


normalization operation before feeding the input sequence to the deep learning model

Question: before training a network, I normalize each input sequence, by having this function,
def norm(x):
    return (x - np.mean(x)) / (np.std(x) + 1e-7)

datamatrix[row_id,:]=norm(datamatrix[row_id,:])

Here, datamatrix[row_id,:] represents a single input sequence. For each normalization operation, I plot the following figure, where the dashed line represented the normalized sequence, while the solid line represents the original sequence. It seems that the normalization operation even enlarges the range of original sequence, i.e., the max and min
Answer: Your original vector/sequence seems to have a mean 0 and standard deviation less than 1 mainly because the starting region and the ending region are more or less zero. So it doesn't seem to be surprising that the scaled vector has bigger elements - you are dividing all of them by a number smaller than 1.
Try printing the statistics yourself and see
print(x.mean(), x.std())


How to write lists of data to a .csv file in python?

Question: I'm trying to write lists of information onto a .csv file in python. So far, I've only been able to get the header to print. I want to grab 2 columns from an existing .csv file to write into the new .csv file with my data. so far, I have
def get_id_size():
    read_file = pandas.read_csv('poem_info.csv')
    poemid = (read_file[['poemname']])
    poemsize = (read_file[['poemsize']])
    return (poemid, poemsize) #this is the columns i want in my new.csv file

    with open('poem_data.csv', 'w') as outfile:
        # write header
        outfile.write('poemid,poemsize,cli,ari\n')

my new data is in
        cli = calculate_cli
        ari = calculate_ari

So my question would be: How can I assign poemid, poemsize, cli, and ari to a csv file? I'm very new to python and I can't figure out the syntax to do so
Comment: Do you actually need `pandas`? Doesn't seem like you're using it for much of anything that the built-in `csv` module (particularly on Py3, where it's Unicode friendly) couldn't handle.
Comment: I don't particularly need it, but I thought it would be faster if I read into the existing csv file using pandas
Comment: Are `calculate_cli()` and `calculate_ari()` using the value from `poemid` and `poemsize`?
Answer: Well, I'm not a pandas guru, but you don't really need it here:
import csv

with open('poem.csv', newline='') as inf,
     open('poem_data.csv', 'w', newline='') as outf:
    csvout = csv.writer(outf)
    csvout.writerow(['poemid', 'poemsize', 'cli', 'ari'])
    for (poemid, size, *_), c, a in zip(csv.reader(inf), cli, ari):
        csvout.writerow([poemid, size, c, a])

That reads from the input file (ignoring all fields past the first two; if the fields are actually index 1 and 3, you could use for (_, poemid, _, size, *_), c, a in zip(...): instead), pairs them up with your computed values, then writes them out. I'm sure there is a nicer way in pandas, but this doesn't require third party modules at all, so it may be preferable in some cases.
To split this up into functions, you'd need to either open the file outside the function or listify the results (so the with block doesn't cut off access to the file before you're done. For example:
def get_id_size():
    with open('poem.csv', newline='') as inf:
        return [(poemid, size) for poemid, size, *_ in csv.reader(inf)]

cli = calculate_cli()
ari = calculate_ari()

with open('poem_data.csv', 'w', newline='') as outfile:
    csvout = csv.writer(outfile)
    # write header
    csvout.writerow(['poemid', 'poemsize', 'cli', 'ari'])
    for (poemid, size), c, a in zip(get_id_size(), cli, ari):
        csvout.writerow([poemid, size, c, a])

Note: This is Py3 code; changes would be needed for the Py2 csv module.
Comment: Thanks! I'm running in Py3, but when I implemented your code, I get an     "csvout.writerow(['poemid', 'poemsize', 'cli', 'ari'])
io.UnsupportedOperation: not writable" error
Comment: @emptybladder: Yeah, typo. Forgot to pass the mode when opening for write. Already fixed (just added `'w'` as second argument to `open` for `outf`. Sorry for confusion.
Comment: (at least on Windows) you should open `csv.writer` files as binary. `open('poem_data.csv', 'wb', newline='')` EDIT: oh hmm, maybe that's just in py2
Comment: @AdamSmith: That's only for Python 2. On Python 3, you want text mode (`csv` writes `str`, not `bytes`); the `newline=''` is what prevents line ending translation (so `csv` writes newlines appropriate to the dialect regardless of Windows vs. Linux vs. old Mac weirdness). See [the modern docs](https://docs.python.org/3/library/csv.html#csv.reader), specifically [the final footnote](https://docs.python.org/3/library/csv.html#id3).
Comment: @ShadowRanger aye, just old crufts of long-deprecated knowledge from the days of yore cropping up in my head. Thanks for the clarification!
Answer: Pandas is not required but it will simplify your life. You could do the following (removing the function get_id_size() altogether):
import pandas as pd

df = pd.read_csv('poem_info.csv')

# Change the column name of poemname
df.rename(columns={'poemname':'poemid'}, inplace=True)

# Add the new columns
df['cli'] = calculate_cli()
df['ari'] = calculate_ari()

# Export
df.to_csv('poem_data.csv',header=True,index=False)


Homogeneity does not suffice for a map between vector spaces to be linear

Question: The following problem is taken from Sheldon Axler's book Linear Algebra Done Right, more precisely Exercise 1. from Chapter 3:
Problem: Give an example of a function $f : \mathbb{R}^2 \to \mathbb{R}$ such that $f(av) = af(v)$ for all $a \in \mathbb{R}$ and all $v \in \mathbb{R}^2$ but $f$ is not linear.
I tried to include things like absolute values and square roots in order to handle the homogeneity, but I did not had any success in constructing such an example yet by doing so.
Do you know such an example? Thank you in advance!
Comment: Have you drawn pictures of what homogeneity does and does not require of the function? Not every function has to be given by a formula.
Answer: I just finished working on this problem and this is what I got:
Let
$$ f:\mathbb{R}^2 \to \mathbb{R}\\
(x,y) \mapsto \begin{cases}
 \frac{x^2}{y} \ , \   y \neq 0 \\
0 \  , \ y=0 \end{cases} $$
This is a homogeneous map since $$f\Bigl(a(x,y)\Bigr) = f\Bigl((ax,ay)\Bigr) = a\ \frac{x^2}{y} = af\Bigl((x,y)\Bigr)$$ whenever $a \neq 0$ and in the case of $a=0$ we get:
$$f\Bigl(\ 0(x,y)\ \Bigr) = f\Bigl((0,0)\Bigr) = 0 = 0f\Bigl((x,y)\Bigr)$$
However, it is not additive, in general, since $$f\Bigl((x_1,y_1)+(x_2,y_2)\Bigr) = \frac{(x_1 + x_2)^2}{y_1+y_2} \neq \frac{x_1^2}{y_1}+\frac{x_2^2}{y_2} = f\Bigl((x_1,y_1)\Bigr)+f\Bigl((x_2,y_2)\Bigr)$$ hence not linear.
Answer: consider the map: $$f:\mathbb{R}^2 \to \mathbb{R}\\ (x,y) \mapsto \begin{cases}
 x \text{ if } y=0 \\
0 \text{ else }\end{cases} $$
then this is homogenous $f(a(x,y))(f(ax,ay))=\begin{cases}ax \text{ if } y=0 \\ a0\text{ else }\end{cases}$, but not linear, since $$f(1,1)+f(1,-1)=0 +0 = 0 \neq f(2,0) =f((1,1)+(1,-1)).$$
Comment: You say "this is clearly homogeneous", but it can't be (in the sense given in the problem) unless your norm is constantly zero. Otherwise, there's no way for it to send $-v$ to $-f(v)$ as norms never output negative numbers.
Comment: sorry, you are completely right, I think i remmedied that, I was just very tempted by the simplicity of the norm.