Prove, that the following rules for homomorphisms are true or false.

Question:
Let $\Sigma=\{a,b\}$, $L$ and $R$ be languages over $\Sigma$ and $h:\Sigma^* \to \Sigma^*$ be a homomorphism. Prove or disprove the following statements:

$h^{-1}(L\cup R)=h^{-1}(L)\cup h^{-1}(R)$
$L=h^{-1}(h(L))$

$\begin{align}
h^{-1}(L\cup R)&=\{x\in\Sigma^*\mid h(x) \in L\cup R\}\\
&=\{x\in\Sigma^*\mid h(x)\in L \lor h(x)\in R\}\\
&=\{x\in\Sigma^* \mid h(x)\in L\}\cup \{x\in\Sigma^*\mid h(x)\in R\}\\
&=h^{-1}(L)\cup h^{-1}(R)
\end{align}$

$L=h^{-1}(h(L))$
No, let $L=\{aab,ba,aa,b\}$ and $h(a)=\lambda$, $h(b)=b$, $\left((h(\lambda)=\lambda\right)$. It follows, that $h(L)=\{b,b,\lambda,b\}$ and $h^{-1}(h(L))=\{b,b,\lambda,b\}$, but $L\neq h^{-1}(h(L))$. The statement is not true.
Are both proofs correct? Thank you in advance.
Answer: Your solution for (1) is correct.
Your solution for (2) is not correct. With your choice of $h$ and $L$, one has $h(L) = \{b, 1\}$ (where $1$ is the empty word, a better notation when you use monoid homomorphisms, since the empty word is the identity of the monoid $\Sigma^*$). Then $h^{-1}(h(L)) = a^*ba^* + a^* \not = L$.
A much simpler example is to take $h(a) = h(b) = 1$ and $L = \{1\}$. Then $h(L) = \{1\}$ and $h^{-1}(h(L)) = \Sigma^*$.


Firebase How to get parent node from a query

Question: I have this simple query:
<code>var userz = firebase.database().ref()
.child("accounts")
.orderByChild("userId")
.equalTo(fbid)
.once("value", function(snapshot) {
    ...
});
</code>
With this structure:
- accounts
---- IdAccount
-------- Name
-------- userId
-------- provider
When I ask snapshot.key, I get back "accounts" value.
I just want to know which "IdAccount" value I got when I did this query and I don't know how to do that.
Answer: I changed "value" to "child_added" and it worked !
<code> var userz = firebase.database().ref()
    .child("accounts")
    .orderByChild("userId")
    .equalTo(fbid)
    .once("child_added", function(snapshot) {
        ...
    });
</code>


Creating secure .exe files in C#

Question: I have heard some mutterings about C# being quite easy to "crack" and/or reverse engineer.
Is this the case and if so, how can I go about preventing this, if possible ? Or at least making it more difficult ?
Thanks, George.
Answer: Obfuscate your assembly.
You can refer to this instituitional article to learn more about Obfuscation.
Answer: You can obfuscate your source code using for example Dotfuscator software which comes with Visual Studio.
If you want to see reverse engineering in action - download Reflector, and open your exe in it. You'll be surprised :)
Answer: You could obfuscate the generated assembly.
Answer: To some extent it is. The IL can be viewed and reverse-engineered. Some people use obfustators to scramble all of the names in the assembly, thus making it near impossible to derive any app logic.
Comment: Ok thanks. Does this apply to other languages such as C++, VB etc too ??
Comment: Yes - all of the .NET compilers (C#, VB, C++, F#) will spit out language-agnostic IL which can be reverse engineered.
Answer: There are a number of libraries to deal with this, I think Microsoft release (or at least endorse) Dotfuscator
Answer: .Net code is pretty easy to view even when compiled, because all the metadata (the information about classes, methods and properties) is all contained in the executable. Basically all you need to get at the code is Reflector.
Obfuscating will basically rearrange and rename everything to make tools like Reflector harder to use. There's a stackoverflow question asking about which particular obfuscater you could use.

Creating secure .exe files in C#


Is the union of two non-dense sets still non-dense?

Question: I've seen here that the union of two nowhere dense sets is again nowhere dense.
Here I ask something milder:

Is the union of two non-dense sets still non-dense?

I would say it is true, but I don't really know how to prove it. Some hint?
Comment: Could you give a definition of "non-dense"? If "non-dense" simply means "not dense", then trivial examples show this to be false in a maximal way (e.g. the real line is can be the union of two rays).
Comment: From [how to ask a good question](https://math.meta.stackexchange.com/questions/9959/how-to-ask-a-good-question): Your question should be clear without the title.
After the title has drawn someone's attention to the question by giving a good description, its purpose is done. The title is not the first sentence of your question, so make sure that the question body does not rely on specific information in the title.
Comment: Why would you say it is true?  Can't you include that in your question?
Answer: Consider the topological space $X=\{0,1\}$ with the discrete topology.
If you prefer a more 'natural' example, consider $\Bbb{R}$ with its usual topology, and the two subsets $(-\infty,0]$ and $[0,\infty)$. I'm sure you can tell from here that it fails spectacularly.
Comment: Yes, by the exact same method as in this answer.
Comment: Everything right. Thanks
Comment: +1 for your patience with the OP
Comment: You are right, that was a stupid question. And yes, thanks for the patience. But sometimes one is just (really) tired. I guess it happens to everyone
Comment: Oh, I see. Thanks. But then, what kind of conditions can we ask for the statement to be true? E.g. If the space is $\Bbb R^N$ with euclidean topology, and we have two sequences $\{a_n\}_n$ and $\{b_n\}_n$, none of which dense, can we argue their union is not dense?
Comment: Of course not; for example $\Bbb{Q}$ is dense in $\Bbb{R}$ and countable. Honestly this is so far from anything true that it barely makes sense to me to try to 'cut it down' to something true.
Comment: $\Bbb Q$ is of course dense in $\Bbb R$, but can we split it into two sets, none of which dense?


Better play 100 tickets in one lottery draw or 100 plays/draws with 1 ticket?

Question: I heard many people say that it is better to play 100 tickets in one draw of 5/49 lottery, rather than 100 plays/draws with 1 ticket.
Is there any scientific basis for this, or actually there is no difference?
Comment: Does this answer your question? [If I play the lottery with a specific amount of money, should I put it all on one game or distribute it among several games](https://math.stackexchange.com/questions/2990504/if-i-play-the-lottery-with-a-specific-amount-of-money-should-i-put-it-all-on-on)
Answer: It sort of depends, however, it is usually better to spread out your tickets over the 100 lotteries, rather than place all of your tickets into one...
Let's say that you have $n$ lotteries $L_1 , L_2, \dots, L_n$ to enter, where in your case, $n=100$.
Let $n_i$ be the total number of tickets in the $i^{th}$ lottery (before you add your tickets). Let $t_{i}$ be the number of tickets you enter into the $i^{th}$ lottery.
The probability that you win the $i^{th}$ lottery is
$$p_{i} = \frac{t_{i}}{n_{i}+t_{i}}$$
where the $t_{i}$ in the denomenator comes from the fact that you are adding $t_i$ tickets to the lottery.
The expected number of lotteries that you win is
$$\mathbb{E}[Lotteries\ I \ Win]=\sum_{i=1}^{n} p_i$$
Now, suppose that $n_{i} = 50$ for all $i$. That is, each lottery has exaclty 50 tickets entered into it. Then, if you place all of your tickets into lottery 1, the probability you win is $p_1 = 100/150 = 2/3$ and $p_j =0 $ for all $j\geq2$. Thus, the expected number of lotteries you win is $2/3$.
 However, if you place exactly one ticket into each of the 100 lotteries, then the expected number of lotteries you win is $1/51 \cdot n = 100/51 \approx 2$, so in this case, you were better off placing one ticket in each lottery than you were placing all of your tickets into one.
In general, your strategy will depend on the expected number of tickets entered into each lottery. Intuitively, you probably want to place a few more tickets into lotteries where few people are playing, and hold back on those that have a lot of participants. If you assume that the same number of tickets $N$ have been entered into each lottery, then you actually maximize your expected winnings by placing one ticket into each lottery, and minimize your chances of winning by placing all of your tickets into exactly one (i.e. if the lotteries are identical, then the worst thing you can do is place all of your tickets into one). To see this, note that
$$\frac{100}{N+100}\leq \frac{100}{k} \cdot \frac{k}{N+k}$$
for any $1\leq k \leq 100$.
Sort of seems unintuitive at first, but the math doesn't lie :).


Obtaining $\frac{\sin x}{x}$ via integral of Bessel function of the first kind

Question: How can I prove that,
$$\frac{\sin x}{x} = \int_0^{\pi/2} J_0(x\cos\theta)\cos\theta \hspace{0.11cm} \mathrm{d}\theta$$
Answer: Note that
$$J_0(x)=\sum_{n=0}^\infty \frac{(-1)^n}{(n!)^2}\left(\frac{x}{2}\right)^{2n}$$
So
$$\eqalign{
\int_{0}^{\pi/2}J_0(x\cos\theta)\cos\theta\,d\theta&=
\sum_{n=0}^\infty \frac{(-1)^nx^{2n}}{(n!)^24^n}\int_{0}^{\pi/2}\cos^{2n+1}\theta\,d\theta\cr
&=\sum_{n=0}^\infty \frac{(-1)^nx^{2n}}{(n!)^24^n}\cdot \frac{(2^nn!)^2}{(2n+1)!}\cr
&=\sum_{n=0}^\infty \frac{(-1)^nx^{2n}}{(2n+1)!}=\frac{\sin x}{x}.
}
$$
Edit: Note that
$$\eqalign{I_n-I_{n-1}&= -\int_{0}^{\pi/2}\cos^{2n-1}\theta\sin^2\theta\,d\theta\cr
&=\left[\frac{\cos^{2n}\theta}{2n}\sin\theta \,d\theta\right]_0^{\pi/2}-\frac{1}{2n}\int_{0}^{\pi/2}\cos^{2n+1}\theta\,d\theta
}$$
This proves that
$$I_n=\frac{2n}{2n+1} I_{n-1}=\frac{(2n)(2n-2)\cdots(2)}{(2n+1)(2n-1)\cdots (3)(1)}I_0=\frac{2^{2n}(n!)^2}{(2n+1)!}$$
Comment: When I use Beta function for Wallis function I go until the integral is equal to $\frac{\pi}{2}\frac{\Gamma(k+1)}{\Gamma(k+3/2)}$. Can you show how do you solve the integral explicitly?
Answer: Since $$J_{m}\left(x\right)=\sum_{k\geq0}\frac{\left(-1\right)^{k}}{4^{k}k!\left(k+m\right)!}x^{2k+m}
 $$ we have, exchanging series and integral (which is permitted due to the absolute convergence), $$ \int_{0}^{\pi/2}J_{0}\left(x\cos\left(\theta\right)\right)\cos\left(\theta\right)d\theta=\sum_{k\geq0}\frac{\left(-1\right)^{k}}{4^{k}k!^{2}}x^{2k}\int_{0}^{\pi/2}\cos^{2k+1}\left(\theta\right)d\theta
 $$ and the integral in the RHS is the Wallis integral which can be calculated (using Euler's Beta function) as $$\int_{0}^{\pi/2}\cos^{2k+1}\left(\theta\right)d\theta=\frac{\left(2k\right)!!}{\left(2k+1\right)!!}=\frac{4k!^{2}}{\left(2k+1\right)!}
 $$ so finally $$ \int_{0}^{\pi/2}J_{0}\left(x\cos\left(\theta\right)\right)\cos\left(\theta\right)d\theta=\sum_{k\geq0}\frac{\left(-1\right)^{k}}{4^{k}k!^{2}}x^{2k}\frac{4^{n}k!^{2}}{\left(2k+1\right)!}
 $$ $$=\sum_{k\geq0}\frac{\left(-1\right)^{k}}{\left(2k+1\right)!}x^{2k}=\frac{\sin\left(x\right)}{x}.
 $$
Comment: When I use Beta function for Wallis function I go until the integral is equal to $\frac{\pi}{2} \frac{\Gamma({k+1})}{\Gamma({k+3/2})}$. How do you get that double factorial solution for Wallis integral?
Comment: @Shibli The relation between the Gamma function and the double factorial is the equation $(2)$ of http://mathworld.wolfram.com/DoubleFactorial.html. For prove it, you have only to iterate the property of Gamma function $\Gamma(z+1)=z\Gamma(z)$, then use $\Gamma(1/2)=\sqrt{\pi}$ and finally extract $1/2$ from every factors.
Answer: We may exploit the fact that $J_0$ is a very well-behaving analytic function and the integrals $\int_{0}^{\pi/2}\cos^n\theta\,d\theta$ are known. We get:
$$ \begin{eqnarray*}I(x)=\int_{0}^{\pi/2}J_0(x\cos\theta)\cos(\theta)\,d\theta&=&\sum_{k\geq 0}\frac{(-1)^k}{4^k k!^2}\int_{0}^{\pi/2}x^{2k}\cos^{2k+1}(\theta)\,d\theta\\&=&\sum_{k\geq 0}\frac{(-1)^k}{4^k k!^2}\cdot\frac{2^k k!}{(2k+1)!!}\,x^{2k}\\&=&\sum_{k\geq 0}\frac{(-1)^k}{(2k+1)!}\,x^{2k}\\&=&\color{red}{\frac{\sin x}{x}}.\end{eqnarray*}$$


Não percebo uma resolução de ordenação

Question: O professor pediu o exercício seguinte:
"Escreva um programa que recebe três pontuações (números inteiros); ordena essas pontuações
utilizando instruções if e escreve as três por ordem crescente no ecrã."
Tentei fazer à minha maneira sozinho mas acabei por ficar enrolado durante quase 30 minutos perdido no meio de tantos if's e else's e fui ver a resolução que o professor disponibilizou,mas não consigo entende-la.A resolução é a seguinte:
System . out . println("Indique a 1ª pontuação:");
    int pontuacao1=scanner.nextInt();
    System . out . println("Indique a 2ª pontuação:");
    int pontuacao2 = scanner.nextInt();
    System . out . println("Indique a 3ª pontuação:");
    int pontuacao3 = scanner.nextInt();

     if (pontuacao2 < pontuacao1)
    {
        int valor = pontuacao1;
        pontuacao1 = pontuacao2;
        pontuacao2 = valor;
    }
    if (pontuacao3 < pontuacao2)
    {
        int valor = pontuacao2;
        pontuacao2 = pontuacao3;
        pontuacao3 = valor;
        if (pontuacao2 < pontuacao1)
        {
            int valor2 = pontuacao1;
            pontuacao1 = pontuacao2;
            pontuacao2 = valor;
        }
    }

    System.out.print(pontuacao1 + ", " + pontuacao2 + ", " + pontuacao3);

A primeira parte de input de valores eu percebo mas a partir do if é que não. Alguém pode explicar?
Answer: Variável temporária
A váriavel valor serve para temporariamente armazenar um valores para não perdê-lo.
Vamos lá,
Recebemos três valores, vamos por exemplo supor: 11, 5, 3.
Agora precisamos ordená-los, por isso vamos fazer as comparações com as estruturas condicionais if:
if (pontuacao2 > pontacao1): Vamos comparar de a segunda pontuacao é maior que a primeira. No nosso caso não certo? Então vamos perguntar ao próximo if,
if (pontuacao3 < pontuacao2): A terceira pontuação é menor que a segunda? SIM. Então entramos na estrutura,
Como a última posição é menor que a segunda elas deveriam estar trocadas certo? Sim. Porém se apenas fizermos:
pontuacao2 = pontuacao3;
pontacao3 = pontuacao2;

O que será que acontece? Vamos pensar:
// pontuacao2 vai receber o valor de pontuacao3, logo pontuacao2 vai virar 3,
// Agora pontuacao3 recebe o valor de pontuacao2, mas perceba, pontuacao2 agora é 3, logo as duas variáveis vao acabar tendo o valor 3.
Onde foi parar nosso 5? Nesse caso perdemos ele. Por isso de uma variável temporária, para que possamos temporariamente segurar o 5 para darmos ele à outra pontuacao. Vejamos:
int valor = pontuacao2;
pontuacao2 = pontuacao3;
pontuacao3 = valor;

// Agora temporariamente armazenamos o valor de pontuacao2 em valor, nesse caso, 5
// Então passamos o valor de pontuacao3 para pontuacao2, ela recebe o 3
 // Por fim, ainda temos nosso 5 guardado, em valor, agora só passarmos ele para pontuacao3. Prontinho.
Só repetir isso para a próxima condição: pontuacao2 < pontuacao1, que no caso também é verdadeira.
Agora vamos pensar na estrutura dos if
Temos primeiro uma pergunta, se pont2 < pont1. Devemos fazer essa pergunta, no caso de condição verdadeira, entramos no if e invertemos as posições.
Agora temos uma outra pergunta, se pont3 < pont2, por que nesse caso usamos outro if ao invés de um else if? Usamos outro if porque queremos obrigatoriamente realizar esta verificação independentemente do resultado da primeira.
Agora, por que o terceiro if está dentro do segundo? Perceba, essa condição SÓ será testada caso a segunda seja válida. Se pont2 não é menor que pont1 e pont3 não é menor que pont2 significa que os números já estão ordenados, desse modo realizar uma terceira verificação seria desnecessário, então assim acabamos por otimizar nosso código.

Não percebo uma resolução de ordenação


Creating JSON output in Java

Question: I am trying to create below JSON in Java.
"data": {
    "keys": ["access_token"]
}

I have tried below code for same
JSONObject jsonObjSend = new JSONObject();
JSONObject data = new JSONObject();
JSONArray keys = new JSONArray();
keys.add("access_token");
jsonObjSend.put("keys", keys);
data.put("data",keys);
System.out.println(obj.toString());

Comment: And what have you tried to do?
Comment: Then whats the problem
Comment: post your code as a part of your question with appropriate formatting.
Comment: What's the problem. What kind of output does your code produce?
Answer: you are doing it wrongly. you need to add data to jsonObjSend check this.
import org.json.JSONArray;
import org.json.JSONObject;

public class Test {

public static void main(String[] args) {
    JSONObject jsonObjSend = new JSONObject();
    JSONObject data = new JSONObject();
    JSONArray keys = new JSONArray();
    keys.put("access_token");
    data.put("keys", keys);
    jsonObjSend.put("data",data);
    System.out.println(jsonObjSend.toString());
   }
}

Answer: Please mind the desired output is not a valid JSON:
"data": {
  "keys": [
    "access_token"
  ]
}

A valid JSON would be:
{
  "data": {
    "keys": [
      "access_token"
    ]
  }
}

Once you are using the org.json library to work with JSON, you might find the following code useful:
JSONObject root = new JSONObject();

JSONObject data = new JSONObject();
root.put("data", data);

JSONArray keys = new JSONArray();
keys.put("access_token");
data.put("keys", keys);

String json = root.toString();

It will produce this JSON:
{"data": {"keys": ["access_token"]}}

Comment: is there any way to pass BIG json data ??
Comment: @AltamashShaikh I haven't tried with big JSON data and have no idea what *big JSON data* means for you. You could try.
Comment: BIG json data means i was trying to make a http call with json as payload , so i tried with JSON parser and it worked for me :)
Comment: @AltamashShaikh If it worked for you, please consider accepting my answer.
Answer: You can achieve it by using google gson Json.
Have a look to the sample code
JsonObj obj = new JsonObj();
Data data = new Data();
String keys[] = {"access_token"};
data.setKeys(keys);

obj.setData(data);
System.out.println("==================>>>"+gson.toJson(obj));

class JsonObj{
    private Data data;
    public Data getData() {
        return data;
    }
    public void setData(Data data) {
        this.data = data;
    }
}
class Data{
    private String[] keys;

    public String[] getKeys() {
        return keys;
    }
    public void setKeys(String[] keys) {
        this.keys = keys;
    }
}

Creating JSON output in Java


Mistura de CLASS e ID em HTML e CSS

Question: Fiz a prova do concurso do IFSULDESTE de Minas Gerais organizada pela Fundação CEFET-MG e estou com dúvidas na seguinte questão:
8 - Considere o código da página HTML a seguir.

É correto afirmar que a cor do texto do elemento  do código acima é
a) red.
b) gray.
c) rebeccapurple.
d) darkgoldenrod.
e) cornfl owerblue.
Por que, segundo o gabarito, a letra E é a opção correta? Não entendi essa mistura de CLASS e ID. Marquei a letra A.
Fonte: Fundação CEFET. Disponível em: https://concurso.fundacaocefetminas.org.br/documentos/InformticaBomSucesso41637000719030930238.pdf. Acesso em: 31 jul 2019.
Comment: Não diz. Penso que seja o strong, mas vc tem razão, deveria ter especificado. Posso entrar com recurso.
Comment: @Vitor Carnaval, vc editou a questão especificando o elemento strong, mas a questão original não diz.
Comment: Pelo link que passou diz sim, elemento **strong**
Comment: Ah sim, tem razão
Comment: A opção C e a opção E tem o mesmo peso, mas a opção é ganha simplesmente pq é a regra que vem por último. Se vc colocar o CSS da letra C depois da letra E vc vai ver que é ele que fica valendo.
Comment: Dê uma olhada neste artigo: https://medium.com/emanuelg-blog/entendendo-a-preced%C3%AAncia-de-estilo-em-css-especificidade-heran%C3%A7a-e-efeito-cascata-a437c4929173
Answer: A resposta correta é a alternativa "E" mesmo. No CSS, quando se usa # na frente, é porque está utilizando Id, e não classe. Nesse caso ele está usando o Id "pai", e o Id "filho", tornando o atributo específico, e quanto mais específico ele for, mas "forte" ele será em relação aos outros, sendo assim, ele tem importância maior do que os outros atributos.
Answer: CLASS e ID são coisas diferentes. ID é único por página, CLASS pode ter vários. Foi misturados vários justamente para confundir, pois se trata de uma prova. E um código sobrescreve o outro. Todos funcionaria, se só existisse somente 1 dos códigos CSS. (Claro que BODY iria colocar cor para tudo, e as outras funções somente para o id="sid").
Então o único motivo de aparecer vários assim é por se tratar de uma prova, pois somente 1 deles já funcionaria.

Mistura de CLASS e ID em HTML e CSS


O que é Xamarin?

Question: Parece que o Xamarin é muito novo. Dizem que você pode desenvolver android ou IOS ou Windows Phone pelo C#. É isso mesmo ?
Pra quem está começando agora, vale a pena ou não ?
Comment: Relacionada: [Desenvolver para várias plataformas usando C# e Xamarin Studio](https://pt.stackoverflow.com/questions/38099/desenvolver-para-várias-plataformas-usando-c-e-xamarin-studio)
Comment: Relacionada²:[Xamarin é completamente grátis?](https://pt.stackoverflow.com/questions/210633/xamarin-é-completamente-grátis)
Comment: Veja a wiki da tag [Xamarin](https://pt.stackoverflow.com/tags/xamarin/info).
Answer: Exatamente, você programa em C# e ele "converte" em um App Android e iOS.
Tem suas vantagens, uma delas por não precisar saber 2 linguagens (java ou kotlin para Android e Swift para iOS) e criar um App para as duas plataformas.
Também as desvantagens, por exemplo não ter tantas possibilidades de customizacoes no design do App, e ser 100% nativo, podendo ou não ter alguma perda na performance.
Existem muitas matérias disso, o xamarim não é tão "novo" assim, mas melhorou bastante desde seu lançamento.
Comment: Complementando o que o colega disse, veja esse link: https://developer.xamarin.com/guides/android/application_fundamentals/

O que é Xamarin?


Azure Cloud no matches for kind "SecretProviderClass" in version "secrets-store.csi.k8s.io/v1alpha1"

Question: I am working in azure cloud and wanted to add a simple ServiceProviderClass using the doc from Azure Azure /
secrets-store-csi-driver-provider-azure  replacing the secret, keyvaultName and tenantId
apiVersion: secrets-store.csi.x-k8s.io/v1alpha1
kind: SecretProviderClass
metadata:
  name: azure-kvname
spec:
  provider: azure
  parameters:
    usePodIdentity: "false"         # [OPTIONAL] if not provided, will default to "false"
    keyvaultName: "kvname"          # the name of the KeyVault
    cloudName: ""          # [OPTIONAL for Azure] if not provided, azure environment will default to AzurePublicCloud
    objects:  |
      array:
        - |
          objectName: secret1
          objectType: secret        # object types: secret, key or cert
          objectVersion: ""         # [OPTIONAL] object versions, default to latest if empty
    tenantId: "tid"                    # the tenant ID of the KeyVault

And when I try to apply it to my cluser using the Azure Cloud Bash:
hacker@Azure:~$ kubectl apply -f secrets-provider.yaml
error: unable to recognize "secrets-provider.yaml.yaml": no matches for kind "SecretProviderClass" in version "secrets-store.csi.k8s.io/v1alpha1"

It seems to be that kind and version are incompatible eventhough they are everywhere on the doc.
Answer: The problem is actually really simple, the secret-store-csi-driver was not yet install. Thus it was not recognized. Basically make sure you follow the pre-requisistes.
From the Azure Cloud Terminal you can use Helm to install the driver:
helm repo add secrets-store-csi-driver https://raw.githubusercontent.com/kubernetes-sigs/secrets-store-csi-driver/master/charts
helm install csi-secrets-store secrets-store-csi-driver/secrets-store-csi-driver

There is an ongoing issue with the driver secrets-store-csi-driver-provider-azure#259, for azure you need to explicitly specify --grpc-supported-providers=azure

And now it works:
hacker@Azure:~$ kubectl apply -f secrets-provider.yaml
secretproviderclass.secrets-store.csi.x-k8s.io/azure-kvname created
hacker@Azure:~$ kubectl get SecretProviderClass
NAME           AGE
azure-kvname   39s

Hopefully that will help.


ENTER in fpdf when $_POST function.. ln ()?

Question: Is there any code I can put in the input post text so that when appearing on fpdf it gives an enter space (to the next line) ..???
Answer: Use FPDF::Multicell() or FPDF::Write() and it should be done automatically.
Comment: hey! thnx for responding... say i put that in my <input text... so that it delivers in fpdf...it just displays the text but no enter..
Comment: No. You need to use these functions to write text to PDF.


logica de loop em blocos em JavaScript

Question: Meu código tem um array com inúmeros objetos, esse abjetos os quais são URL'S, com eles faço um loop que percorre todo este array e faz um request para cada url do array. Mas preciso que meu loop percorra o array em blocos, Ex: de 10 em 10; até chegar no final, tudo isso para que não o faça instantaneamente e acabe sobrecarregando o servidor e também  para que não demore muito percorrendo de 1 em 1 pois o array é muito grande, á base do código é basicamente isso.
const array = ["URL-1","URL-2","URL-3"] etc...

for (var i = 0; i < array.length; i++) {
    axios.get(array[i], (res) => {
        const res = res;
    });
}

Answer: bom no final eu mesmo acabei achando um jeito viável.
const main = async () =>
{
    if ( array.length >= index )
    {
        if (index != count)
        {
            console.log(index);
            index++
            main();
        }else{
            console.log("+10");
            count = (count + 10);
        }

    }else{
        console.log("end");
        clearInterval(handle);
    }
}
const handle = setInterval(main, 2000);

Obrigado por nada.
Comment: "Obrigado por nada" é ofensivo. Ninguém é obrigado a te ajudar. Muito menos na hora que você espera. Se acha que este site é para isto, está no lugar errado.

logica de loop em blocos em JavaScript


Using $r_Q$ statistic to check multivariate normality

Question: Suppose in R, I have a data set
data(iris)

and I want to check for multivariate normality of the first four columns ("Sepal.Length" "Sepal.Width"  "Petal.Length" "Petal.Width") using the rQ statistic. How can one do this?
I understand how to check if each of the marginals are normal (for example, ppcc function in R will do this), but I dont see how I can use rQ to check for multivariate normality. Supposing one of the ppcc calls fails marginal normality, then we can reject multivariate normality; but even if all four of the marginals are normal (checked by rQ) this does not imply multivariate normality.
How do I proceed?
Comment: Could you please define what is the rQ statistic?
Answer: I believe the package MVN is what you're looking for. Following from your example dataset, which is actually the one they use in their vignette:
# load MVN package
library(MVN)

# load Iris data
data(iris)

# setosa subset of the Iris data
setosa <- iris[1:50, 1:4]

result <- mvn(data = setosa, mvnTest = "mardia")
result$multivariateNormality

             Test        Statistic           p value Result
1 Mardia Skewness 25.6643445196298 0.177185884467652    YES
2 Mardia Kurtosis 1.29499223711605 0.195322907441935    YES
3             MVN             <NA>              <NA>    YES

There is a variety of tests implemented: Mardia's test, Henze-Zirkler's test, Royston's test, Doornik-Hansen's test and the E-statistic test.
Answer: I think it's also important to flesh out the underlying statistical motivation for the various multivariate tests already mentioned - beyond just how to carry it out in a statistical software.
Let's assume you have a multivariate Normal distribution
$$\boldsymbol{X}\sim N_{d}(\boldsymbol{\mu},\boldsymbol{\Sigma})$$
then
$$(\boldsymbol{X}-\boldsymbol{\mu})\boldsymbol{\Sigma}^{-1}(\boldsymbol{X}-\boldsymbol{\mu})\sim\chi^{2}_{d}$$
So we have that the above is Chi-squared distributed with $d$ degrees of freedom. We can then exploit this fact and test for joint-normality. We can calculate
$$D_{i}^{2}=(\boldsymbol{X}_{i}-\hat{\boldsymbol{X}})'S^{-1}(\boldsymbol{X}_{i}-\hat{\boldsymbol{X}})$$
for $i=1,\ldots,n$, where $\hat{\boldsymbol{X}}$ and $S$ are your estimates for $\boldsymbol{\mu}$ and $\boldsymbol{\Sigma}$, respectively. Technically speaking, because of the use of the above estimates, the $D_{i}$ are not independent of each other even if the original $X_{i}$ are independent. $D_{i}$ is generally known as the Mahalanobis distance. Thus, under the null hypothesis of multivariate Normality, we have that
$$n(n-1)^{-2}D_{i}^{2}\sim\text{Beta}(d/2,(n-d-1)/2)$$
However, for large $n$, we have that it is well approximated by a Chi-squared distribution as above. Given this, we can construct QQ-plots of the $D_{i}^{2}$ against  that of a Chi-squared (or Beta) distribution. An example is shown below using R:
n=dim(data)[1]
p=dim(data)[2]
S=cov(data)
dif=scale(data,scale=FALSE)
dd=dif %*% solve(S) %*% t(dif)
d=diag(dd)
r=rank(d)
chi2q=qchisq((r-0.5)/n,p)
plot(d,chi2q,pch=20,main="",xlab="Mahalanobis distance",ylab="Chi-squared quantile",col="blue")
abline(0,1,lwd=2,col="red")

Mardia's test of multivariate normality is based on multivariate measures of skewness and kurtosis and compares these with theoretical reference distributions (much like how the Jarque-Bera test assesses univariate normality).
If we define the following measures
$$b_{d}=\frac{1}{n^{2}}\sum_{i=1}^{n}\sum_{j=1}^{n}D_{i,j}^{3}$$
$$k_{d}=\frac{1}{n}\sum_{i=1}^{n}D_{i}^{4}$$
Under the null hypothesis of multivariate normality we have that as $n\rightarrow\infty$
$$\frac{1}{6}nb_{d}\sim\chi^{2}_{d(d+1)(d+2)/6}$$
$$\frac{k_{d}-d(d+2)}{\sqrt{8d(d+2)/n}}\sim N(0,1)$$
Generally, tests of the skewness and kurtosis are performed separately but there are joint tests too.
Comment: Nice explanation!


easter egg like research Jquery

Question: I want to make a research system by typing, so this will work like easter eggs. For example : I type "albert" on the website, and the Jquery script will scroll to the div with the id #albert.
First, do you think this is even possible?
I already try using keyup listener, but all the function is retrieving is numbers, maybe ASCII. I tried something like :
$(document).keyup(function(e) {
    input += e.which;
    clearTimeout(timer);
    timer = setTimeout(function() { input = ""; }, 500);
    goto();
});

function goto() {
    alert(input); // display only numbers
    $('html, body').animate({
        scrollTop: ($("#" + input).offset().top)
    },500);
}

Answer: Close. Use String.fromCharCode:

var input = "";
var timer = null;
$(document).keypress(function(e) {
    input += String.fromCharCode(e.which);
    clearTimeout(timer);
    timer = setTimeout(function() { input = ""; }, 500);
    goto();
});

function goto() {
    if (input == "albert") alert("Hello, Albert.");
}

Comment: @AlexanderSolonik: It does for me. Why wouldn't it?
Comment: or listen to the `key`property of the keyboardevent
Comment: @Amadan the setTimeout never runs ?
Comment: Okay so now, letters are retrieved instead of unicode, but when I type albert, script don't scroll to #albert div. Any ideas?
Comment: If you copied my code literally, it's because I left it out as it wasn't really relevant to the question and would have made the example less clear. If you didn't, then I don't know; is there an error? What does your code look like?...
Comment: Yes, I admit my question was quite unclear. What I want : When i type albert on a page of my website, the page scroll directly to the div which id is #albert. What happens : Nothing, when I type albert. I hope it is clear enough now, btw the code looks exactly the same I post except the string.fromcharcode you corrected.
Comment: Ah, I see. `($("#" + input.toLowerCase()).offset().top)` since `evt.which` is giving codes of uppercase letters; you are expected to handle shifting yourself when listening to keyboard. http://jsbin.com/sesicijuja
Comment: It... Works! Thanks for the attention Amadan

easter egg like research Jquery


Timer Class - Give an error if the start timer is invoke twice in Python

Question: how do I invoke an error if the start timer class function is invoke twice ? Thanks
import time
class Timer(object):
    def __init__(self):
        self._startTime = None
        self._endTime = None

    def start(self):
        self._startTime = time.time() if self._startTime is None else print('Started')

    def end(self):
        self._endTime = time.time()
        print('seconds',self._endTime - self._startTime)
t = Timer()
t.start()
t.start() # should give an error

Comment: `raise` an exception.
Answer: You can create a instance variable (if you want 1 invocation per class instance) or class variable (only 1 invocation in entire lifecycle as class variable is shared by all instances of class) to keep count of number of invocations and when count exceeds some threshold (In your case it's 1), you can raise an exception. Something like this:
import time
class Timer(object):
    def __init__(self):
        self._startTime = None
        self._endTime = None
        self.count = 0 # Instance variable, which allows 1 invocation per instance of this class

    def start(self):
        self.count+=1
        if self.count == 2: # Threshold is 2 here
            raise Exception # You custom exception here
        self._startTime = time.time() if self._startTime is None else print('Started')

    def end(self):
        self._endTime = time.time()
        print('seconds',self._endTime - self._startTime)

Refer this for more details about class variables vs instance variable in Python.


$k(x,s) = 1+\sum_{n=1}^\infty 2e^{-t(n\pi)^2}\cos(\pi n s)\cos(\pi nx) \geq 0$

Question: I am asked to show that the following function is positive for each $(x,s)\in[0,1]^2$ where $t>0$ is a parameter:
$k(x, s) := \displaystyle 1+\sum_{n=1}^\infty 2e^{-t(n\pi)^2}\cos(\pi n s)\cos(\pi nx)$
The background is the following: I am looking at the semigroup $T$ on $L^2[0,1]$ with
$$T(t)f = \sum_{n=0}^\infty e^{-t(n\pi)^2}\langle f,e_n\rangle_{L^2(0,1)} e_n$$
where $e_n(x) = \sqrt{2}\cos(\pi n x)$ if $n>0$ and $e_0 \equiv 1$. Now, for each $t>0$ there is supposed to be a positive kernel $k\in C([0,1]^2)$ with $T(t)f(x) = \int_0^1 k(x,s)f(s)ds$.
I showed that $k$ from the start is indeed a kernel for $T(t)$ but I have no idea how to show positivity. One would need to see that $T(t)$ is a positive operator but I don't see how this would work.
Comment: Related: https://math.stackexchange.com/questions/1847213/fourier-cosine-transforms-of-schwartz-functions-and-the-fejer-riesz-theorem
Answer: $$I(t,x,s)=\sum_{n\in\mathbb{Z}}e^{-t(\pi n)^2}\cos(\pi n s)\cos(\pi n x) $$
is a series whose terms are the values over the integers of a Schwartz function.
By Poisson summation formula, the given series equals $\sum_{n\in\mathbb{Z}}\widehat{f}(n)$, where
$f(n) = e^{-t(\pi n)^2}\cos(\pi n s)\cos(\pi n x)$. The Fourier transform of $e^{-t\pi^2 n^2}$ is a function of the same gaussian form, the Fourier transform of $\cos(\pi ns)\cos(\pi n x)$ is a combination of Dirac deltas with positive coefficients, hence $\widehat{f}(n)$, as the convolution of two non-negative functions, is non-negative.
This proves $I(t,x,s)\geq 0$ even without the restriction $(x,s)\in[0,1]^2$.
Comment: Thanks alot. I think i misinterpreted your comment. I was trying to apply the technique to show that this function is not positive everywhere.
Comment: @TimB.: it was me changing opinion, not you misunderstanding it. I initially thought that Hadamard's 3-4-1 trick should have been the way to go, then I realized that Poisson's summation formula was the actual way to go. You're welcome.


use python to read xml one block at a time

Question: I am very new to Python and have the following XML. I want to be able to read each testdata block (one at a time) and be able to read the children within the testdata block. Basically, I would like to read the file and take each testdata block one at a time, based on the row number ( row=1 ), if (execute= no) then skip that entire test data block. Next go read the children of testdata and get the value of the  lines. Next, read get the value of search and the value of found. once all that is read, I will write my own code to do whatever I want with it. Once that code is done, we will go back to the  with row=2 and read the same as in row1 and run my own code that I wrote and so on until all the testdata blocks are read. I am using Python2.7 and would really appreciate your help as I am stuck!
<?xml version="1.0" ?>
<data>
<testdata row="1" execute="yes" regression = "no">
    <command>Text command1</command>
    <command> Text command2</command>
    <command> Text command3</command>
    <command> Text command4</command>
    <command> Text command5</command>
    <command> Text command6</command>
    <command> Text command7</command>
    <command> Text command8</command>
    <verification> search ="verify" found ="yes" </verification>
</testdata>

<testdata row="2" execute="yes" regression = "no">
    <command>Display Command 1</command>
    <command>Display Command 2</command>
    <command>Display Command 3</command>
    <command>Display Command 4</command>
    <command>Display Command 5</command>
    <command>Display Command 6</command>
    <command>Display Command 7</command>
    <command>Display Command 8</command>
    <verification> search ="find" found ="yes" </verification>
</testdata>
</data>

Comment: Have you looked into either BeautifulSoup or the `etree` library? Both of them could do what you want with only a few commands. https://docs.python.org/2/library/xml.etree.elementtree.html
Answer: The built-in etree library is probably going to be a big help here. You could do something like this:
import xml.etree.ElementTree as ET

tree = ET.parse("my_file.xml")   # iterparse would process one element at a time
root = tree.getroot()

for testdata in root.findall("testdata"):
    if testdata.get("execute") == "yes":
        command_list = []
        for command in testdata.findall("command"):
            command_list.append(command.text)
        verify = testdata.find("verification").text
        # Insert your code here.

Also, instead of <verification> search ="verify" found ="yes" </verification>, your file would be easier to parse as <verification search ="verify" found ="yes" />. Then you could use something like verification.get("search").
More info can be found here (and I took some of the code from here as well):
https://docs.python.org/2/library/xml.etree.elementtree.html
Comment: You should also look at the `iterparse` function, which can yield each node one at a time as it's completed (and/or, if you prefer, as it's started, but then you don't have the children yet). In some cases it can be more readable, although of course sometimes it has the opposite effect. (Also, if you have a huge XML file, it can make a huge difference in performance to process it iterably instead of parsing the whole thing and then searching it, but for the files you're looking at that doesn't seem relevant.)
Comment: One question: the `findall` function returns a list. Why are you iterating over that list to build an identical list? (Even if you wanted to make sure it's a list rather than some other iterable, why not just `list(…)`?)
Comment: @abarnert I wasn't aware of that one, I added a comment.
Comment: @abarnert we're making a list of the text specifically. I suppose they could iterate over `list(testdata.findall("command"))` and just call the `.text` on each element. Either way would work.
Comment: @abarnert Thank you for your suggestions. They are helpful.
Comment: @TheSoundDefense: Sorry, didn't notice that… Never mind.
Answer: If you use the etree library and parse this data, you can have the following:
import xml.etree.ElementTree as ET
parsed_element = ET.fromstring(xml)
for child in parsed_element.findall('testdata'):
    if child.get('execute') == 'yes':
        print "Execute something on child here"


Module 'html5lib.filters.sanitizer' has no attribute 'allowed_elements'

Question: I am not able to add any content in the page it is throwing the error
AttributeError at /en/admin/cms/page/add-plugin/

module 'html5lib.filters.sanitizer' has no attribute 'allowed_elements'

Comment: What version of django & cms & html5lib? Can you add the full stacktrace? And what plugin is it? What version of that plugin?
Comment: There's a probably workaround here; https://github.com/divio/django-cms/issues/6401
Comment: Upgrading from html5lib==0.9999... to html5lib==1.0.1 solved this problem for me.
Answer: Go to your virtualenv and install html5lib in version 0.999999999
pip install html5lib==0.999999999

For me works fine :)


the unit group of an infinite field cannot be cyclic

Question: It is well-known that the unit group of a finite field is a finite cyclic group. But for infinite fields, e.g., $\mathbb{Q}$ or $\mathbb{R}$, the unit groups are not cyclic. I heard this fact in my class and I'm trying to prove it.
Assuming the unit group is infinite cyclic with the generator $a$, I tried to show some element, $\frac{1}{a+1}$ or $\frac{1}{a^2+1}$ cannot be a power of $a$, but it doesn't seem hopeful. Could someone help me?
Comment: Check out in particular [Blue's answer](http://math.stackexchange.com/a/838273/11619) in that older thread, where this problem was discussed.
Answer: Note that in fact, more is true: a finite subgroup of the multiplicative group of any field is cyclic.
If the field $K$ has characteristic zero, it contains $\mathbf{Q}$ as a subfield, and thus $K^*$ contains $\mathbf{Q}^*$ as a subgroup. Hence it is sufficient to show that $\mathbf{Q}^*$ is not cyclic (because a subgroup of a cyclic group is cyclic). Suppose $a$ is a generator of $\mathbf{Q}^*$. Then also $a/2 \in \mathbf{Q}^*$, but no power of $a$ can equal $a/2$ (consider absolute values).
If $K$ has characteristic $p$ and is an algebraic extension of $\mathbf{F}_p$, for every element $a \in K$ you can consider the finite field $\mathbf{F}_p(a)$ to see that the subgroup generated by $a$ must be finite.
Finally if $K$ is a transcendental extention of $\mathbf{F}_p$, is contains $\mathbf{F}_p(t)$ as a subfield, so $K^*$ contains $\mathbf{F}_p(t)^*$ as a subgroup, and again it suffices to show that $\mathbf{F}_p(t)^*$ is not cyclic. Again, for any purported generator $a$, consider $a/2$, but this time you argue on its degree.
Comment: Ah, no, in infinite cyclic groups, negative powers are allowed, so $1/a = a^{-1}$...
Comment: Ah, it was marked as a duplicate while I fixed this...


How to prove criterion for topological equivalence of metrics?

Question: I have problems proving the following statement.
Prove that two metrics$\quad d_1,d_2 $ are topologically equivalent if and only if $$\forall x\in E\quad
 \forall \epsilon>0 \quad\exists \delta>0:$$ $$\forall y\in E\quad d_1(x,y)<\delta \Rightarrow d_2(x,y)<\epsilon$$ $$\quad \quad \quad \quad d_2(x,y)<\delta \Rightarrow d_1(x,y)<\epsilon$$
Comment: (I) what is a basis of a topology? (II) what is a basis of a metric space  topology?
Comment: Basis of a topology is $$\beta=\{B_r(x) \quad x \in E, \quad r>0\}$$
Comment: how could you show that a basis set for one metric is open in the other metric?
Comment: [this answer of mine](https://math.stackexchange.com/a/2267519/4280) might be relevant to you.
Answer: Two topologies say $\mathcal T_1, \mathcal T_2$ on a set $X$ are equivalent, if you have $$\forall x\in X, \forall \mathcal U_1 \in \mathcal T_1 \text{ with } x\in \mathcal U_1,~  \exists \mathcal U_2 \in \mathcal T_2 \text{ such that}\quad  x\in \mathcal U_2\subset \mathcal U_1  $$
and
$$\forall x\in X, \forall \mathcal U_2 \in \mathcal T_2 \text{ with } x\in \mathcal U_2,~  \exists \mathcal U_1 \in \mathcal T_1 \text{ such that}\quad  x\in \mathcal U_1\subset \mathcal U_2. $$
Assume you have the hypothesis you gave above, let $x\in X$ and let $\mathcal U_1 \in \mathcal T_1$ such that $x\in \mathcal U_1$,
there exists $r>0$ such that $B_{d_1}(x,r)\subset \mathcal U_1$, let such an $r>0$.
By hypothese, there exists $\delta>0$ such that
$$ \forall y\in X, d_2(x,y)\leq \delta \Rightarrow d_1(x,y)\leq r.$$
Let such a $\delta>0$, we have :
$$  \mathcal U_2 := B_{d_2}(x,\delta)\subset B_{d_1}(x,r)\subset \mathcal U_1 \quad \text{ and } \quad x\in \mathcal U_2$$
You can proceed the same way to prove the other part of the statement.
Now, assume the two topologies are equivalent,
Let $x\in X$ and let $\varepsilon>0$, the ball $B_{d_1}(x,\varepsilon) \in \mathcal T_1$ thus there exists a $\mathcal U_2 \in \mathcal T_2$ such that $\mathcal U_2 \subset B_{d_1}(x,\varepsilon)$ and $x\in \mathcal U_2$. Let such an $\mathcal U_2\in \mathcal T_2$.
There exists $\delta>0$ such that $B_{d_2}(x,\delta)\subset \mathcal U_2$, let such a $\delta>0$.
We have :
$$ x\in B_{d_2}(x,\delta) \subset \mathcal U_2 \subset B_{d_1}(x,\varepsilon)$$
thus
$$ \forall y\in B_{d_2}(x,\delta), y\in B_{d_1}(x,\varepsilon)$$
which can be stated also :
$$ \forall y\in X, d_2(x,y)< \delta \Rightarrow d_1(x,y)\leq \varepsilon$$
The other statement can be proven the same way.


Insert com PDO e INNER JOIN

Question: Tenho uma tabela pessoa que possui os campos nome, cidade e telefone e time_id. Também tenho outra tabela com nome de time e nela tenho um campo chamado meu_time, como posso fazer um INNER JOIN para cadastrar o time nesse tabela time mas na tabela pessoa no campo time_id receber o id correspondente?
$sql = "INSERT INTO pessoa (nome, cidade, telefone) VALUES(:nome, :cidade, :telefone)";
$stmt = Parent::__construct()->prepare($sql);
$stmt->bindParam(':nome', $nome);
$stmt->bindParam(':cidade', $cidade);
$stmt->bindParam(':telefone', $telefone);
$stmt->execute()

Comment: Apenas uma dúvida porque não está claro na pergunta. Você está querendo usar `INNER JOIN` em um comando `INSERT`?
Comment: @Pagotti, acredito que seja um insert em duas tabelas
Comment: axo que ele quer buscar uma informação em uma tabela e usar ela... mas axo que ele vai ter que fazer um select
Comment: Exatamente, vou tentar explicar melhor. Tenho um formulário e por ele cadastro no banco o nome da pessoa, cidade, telefone e o time dela, mas eu não queria deixar o time na mesma tabela da pessoa, isso porque outras pessoas podem ter o mesmo time, ai ficaria mais organizado se as tabelas ficassem separadas
Comment: Pode colocar a estrutura das duas tabelas na pergunta pra saber se da pra usar o `LAST_INSERT_ID`?
Comment: O time eu digito pra cadastrar, mas caso ele já exista eu não queria criar outro cadastro com o mesmo nome de time, caso exista eu queria apenas usar o que já esta lá
Comment: A tabela se chama principal se chama usuario, ai dentro dela tenho a tabela pessoa e a tabela time
Comment: o time já esta cadastrado?
Comment: O time eu vou cadastrar junto na hora de cadastrar o usuário, mas eu não queria cadastrar o time no mesmo campo de pessoa
Comment: é que fica mais organizado separado e vou ter um controle maior sobre ele
Comment: Atualiza sua pergunta colocando esses detalhes e a estrutura da tabelas envolvidas.
Answer: Caso time_id já exista, vc faz um INSERT com SELECT:
INSERT INTO pessoa (
    nome,
    cidade,
    telefone,
    time_id
    )
VALUES (
    :nome,
    :cidade,
    :telefone,
    SELECT meu_time FROM tabela WHERE tabela.campo=pessoa.campo LIMIT 1
)

Mas caso não, então serão dois inserts e não da pra fazer dois inserts ao mesmo tempo em um unico statement, então vamos usar a TRANSACTION que possibilita isso:
BEGIN
   INSERT INTO tabela_time (coluna1,coluna2,coluna3,...) VALUES (valor1,valor2,valor3,...);
   INSERT INTO pessoa (nome,cidade,telefone,time_id) VALUES (:nome,:cidade,:telefone,LAST_INSERT_ID());
COMMIT

Referência sobre TRANSACTION
Referência sobre LAST_INSERT_ID()
Referência sobre INSERT com SELECT
Comment: Só uma correção. Usa `BEGIN` ou então `START TRANSACTION`. https://www.db-fiddle.com/f/9JgDy59Bbu19TtcYgzja4j/0
Comment: Deu certo, amo vocês gente hehe
Comment: @Pagotti, obrigado pela correção
Answer: Vocês podem me dar a ultima ajuda? eu decidi colocar mais uma tabela, dessa vez chamada selecao, mas ta dando erro:
"begin;
insert into time    (meu_time) values ('cruzeiro');
$time = last_insert_id();
insert into selecao (minha_selecao) values ('brasileira');
insert into pessoa  (nome, cidade, telefone, time_id, selecao_id) values ('Otavio', 'São Paulo', 'telefone', $time, last_insert_id());
commit;";

Insert com PDO e INNER JOIN


Any simpler solution for this simple problem?

Question: The problem is: for complex number $z=re^{i\theta}$, derive an inequality between $r$ and $\theta$ such that $$|\cos(2z)|<1$$
In my solution, I found that if $z=a+bi$, then the following is satisfied: $$\cos(4a)<2-\cosh(4b)$$
However, when I substitute in $a=r\cos(\theta)$ and b=$r\sin(\theta)$, the inequality becomes extremely complicated.
Since the problem is so simple, I believe that there is a solution that is in the form $f(r)<g(\theta)$. But I failed to obtain it.
Could anyone give a simpler solution?
Any help will be appreciated.
Comment: How do you define $\cos(z)$?
Comment: @Holo the complex cosine function. I can't see any ambiguity.
Answer: Expanding the complex $\cos$:
$$
2\cos(re^{i\theta}) =
(e^{2r\sin\theta} + e^{-2r\sin\theta})\cos(2r\cos(\theta)) + i\sin(2r\cos(\theta)),
$$
$$|\cos(re^{i\theta})| =
|\cosh({2r\sin\theta})|,
$$
And $\cosh$ is positive in $\Bbb R$ and $< 1$ in...


named: Strange warnings in /var/log/messages

Question: I got these warnings in /var/log/messages:
Jun 20 01:49:41 pro named[17711]: network unreachable resolving 'pdns3.ultradns.org/A/IN': 2001:500:b::1#53
Jun 20 01:49:41 pro named[17711]: network unreachable resolving 'pdns6.ultradns.co.uk/AAAA/IN': 2001:502:ad09::3#53
Jun 20 01:49:41 pro named[17711]: network unreachable resolving 'pdns6.ultradns.co.uk/A/IN': 2001:502:ad09::3#53

Anybody has any idea what named is trying to do?
Answer: Bind is trying to to resolve ipv6 addresses from an ipv6 server. Is your server configured with IPv6?
Comment: Doesn't seem to be enabled: `modprobe -c | grep ipv6` returns nothing.
Comment: Check the BIND configuration. Also check if you have net-pf-10 installed in your kernel as well.


How to successfully print out deck of 52 cards and 5 hands of non-repeating cards?

Question: I want to fill and print out the deck of 52 cards, and then print out 5 hands of 5 non-repeating cards successfully, but then it doesn't work. How would I be able to fix that?
Code:
 #include <stdio.h>
 #include <stdlib.h>
 #include <time.h>

 /* handy typedefs */
 typedef unsigned char card;
 typedef unsigned char pairs;

 /* arrays for the names of things */
 static char *suits[4] = {"Hearts","Diamonds","Clubs","Spades"};
 static char *values[13]= {"Ace","Two","Three","Four","Five","Six",/
                        "Seven","Eight","Nine","Ten","Jack","Queen","King"};
 static char *colour[]= {"Black","Red"};

int main()
{
  card deck[52][24],*deckp;
  int s, c, a;

  for (s = 0; s < 4; s++)
  {
    for(c = 0; c < 13; c++)
    {
       sprintf(deck[(s * c) + c], "%s of %s", values[c], suits[s]);
    }
  }

  for(a = 0; a < 52; a++)
  {
    printf("%s\n", deck[a]);
  }

  int hand,cd,winner;

  int iRand;
  int i;
  int irand;

  srand(time(NULL));       /* seed the random number generator */

  for(cd=0;cd<5;cd++)
  {

    for(hand=0;hand<5;hand++)
    {
      /* deal the hands here */

    }
  }

  for (hand=0;hand<5;hand++)
  {
    printf("Hand %i:\n",hand+1 );
    for ( i = 0; i < 5; i++) {
      irand = (rand() % 52);
      printf(" %s \n ", deck[irand]);
    }
  }
  /* determine the winner and print it */
  return 0;
}

void filldeck(card deck[52])
{
  return;
}

void shuffle(card deck[52])
{
  int i,rnd;
  card c;

  for(i=0;i<52;i++)
  {
    /* generate a random number between 0 & 51 */
    rnd=rand() * 52.0 / RAND_MAX;
    c = deck[i];
    deck[i] = deck[rnd];
    deck[rnd] = c;
  }
}

Comment: "deck[52][24]" - what does 24 represent?
Comment: How would you do it in real life?  You would probably shuffle the deck into a random order, then deal them out starting at the top of the deck and working your way down until each hand has the required number of cards.  You probably would *not* roll some dice and say "ok...(roll roll roll...) player 1 gets cards 10, 12, 22, 23, 31 from the top....(roll roll roll)  player 2 gets cards 47, 51, 15, 10, 11 from the top...etc".  See the difference (and the problem?)
Comment: You need to use a proper shuffle. Fisher-Yates shuffle is good. Your shuffle is badly broken. http://blog.codinghorror.com/the-danger-of-naivete/
Comment: What doesn't work? What have you tried, and what seems to fail?
Comment: The question you asked is unclear. Please don't ever say "it doesn't work". Make it clear what you expect to happen, and what does happen.
Comment: The `typdef` of `card` to `unsigned char` is not a good idea. It doesn't add anything useful, but obscures the fact that `deck` is an array of strings. If `card` is a type, it should represent a playing card; a good type for card might be a struct that has its suit and rank as members. Such a definition will come in handy when you have to evaluate your hands.
Answer: Replace deck[(s * c) + c] with deck[s * 13 + c].


How can I change font size in Eclipse for ALL text editors?

Question: I had to do a presentation yesterday, and as part of the presentation, I used Eclipse to show some code. Many of my coworkers in the room could not read the text and asked me to increase the size of the text for ALL files, not just Java files or XML files.
But it wasn't immediately obvious from the available options how to do this. I went to menu Window → Preferences and typed font in the search input. This filtered the options to General → Appearance → Colors and Fonts. From here, I could see an option to change the font in Java files, but I didn't know how to change the font globally.
I'm using Eclipse v4.3 Service Release 1 (Kepler) on Windows.
This is similar to Stack Overflow question How can I change font size in Eclipse for Java text editors?.
Answer: This is what we figured out, and this is also found in this answer and also this answer (I'll quote):

Go to Preferences → General → Appearance → Colors and Fonts, expand the "Basic" folder and select "Text Font" and change that to whatever size you like.

Pretty simple!
Comment: Does not work. Nothing happens when you click apply after changing that.
Comment: It is working after testing it. There is probably an issue with Eclipse if it don't works.
Comment: It's needed to change "Text Editor Block Selection Font" too, or else, when activating block selection, it will toggle fonts.
Answer: The answer by @Jake works fine on the editor. To also change the font size of the global Eclipse GUI, I have added the follows:
<code>*{font-size:8;}
</code>
in the file:
<code>ECLIPSE_HOME/plugins/org.eclipse.ui.themes_*/css/e4_default_gtk.css
</code>
worked for me. This is explained here: How to change eclipse font sizes
Comment: First link ("How to set font and colors of Eclipse UI") is dead
Comment: This basically works but a font-size without a unit is invalid in my opinion.
Comment: That seems to work. However, if you do that, eclipse as of Oxygen will ignore font settings made in the Appearance dialog. Meaning, that the dialog will still preview the font setting, but the target component (eg. java text editor) will not use it.
Answer: Eclipse provides a handy shortcut to shortcut for what is well explained in Jake Toronto answer (only by 2 points increments/decrements though).
On MacOS:

Increase by 2 points: command + "+"
Decrease by 2 points: command + "-"

On Windows/Fedora:

Increase by 2 points: CTRL + "+"
Decrease by 2 points: CTRL + "-"
Comment: I am using Windows Eclipse for CPP.
To increase the font [CTRL + "+"] doesn't work but [CTRL + SHIFT + "+"] works.
Answer: Go to Preferences → General → Appearance → Colors and Fonts, expand the "Basic" folder and select "Text Font" and change that to whatever size you like.
this video help you
Answer: The answer by @George worked fine, but if it doesn't work on the file he referred to, then you might try applying the same modification on another file from the same folder: e4_basestyle.css.
For me it worked this way (my version of the Eclipse SDK is 4.2.2).
Answer: Just for reference, if anyone change font settings from Preferences → General → Appearance → *Colors and Fonts**, but it wouldn't work...
In my case, it caused by the Eclipse color theme. Just uninstall it.
Answer: For XML or HTML Files, you can select the "Structured Text Editors" option instead of "Basic" in the path given by Jake Toronto's answer.
Answer:
Open Eclipse Preferences
In left menu select "General>Appearance>Colors and Fonts"
In the resulting window under the Java node select "Java Editor Text Font"
Notice button "Edit Defalt..." is now enabled, click it
Choose your preferred font settings and click OK

Now you will notice that all editor fonts have changed to your selected default (if they were set to the default to begin with). Also you can now change any editor back to this setting by selecting the editor font setting and clicking "Go to Default"


What is an immutable value class in Java? (Effective Java by Joshua Bloch)

Question: I'm currently diving deep (at least relative to my limited knowledge as a programmer) into Java using Joshua Bloch's Effective Java.
In Item 1 under Creating and Destroying Objects, he states to consider static factory methods instead of constructors.
For example,
public static Boolean valueOf(boolean b) {
        return b ? Boolean.TRUE : Boolean.FALSE;
    }

His reasoning in this item is clear to me, except for the part where he states that using static factory methods "allows an immutable value class". He expands on this statement: "guarantees that no two equal instances exist: a.equals(b) if and only if a == b". He states this is because using static factory methods doesn't require the creation of a new object every time they're invoked. Ergo, this makes classes instance-controlled: "allows classes to  maintain strict control over what instances exist at any time."
I understand what these statements mean individually but cannot make sense of how exactly it relates to using static factory methods instead of constructors.
I'd appreciate any comments on helping me understand the matter, preferably with an example. Thank you in advance.
Comment: As far as I know an immutable object is an object which provides only getter methods and no setter methods (and no other method which mutates the state of the object). So it shouldn't be related to how you create the object (calling new / calling a static factory). Anyway it's a good practice to separate the concerns "Creating an object" and "Using an object"
Comment: @ddfra: the question isn't just about immutability, it specifically asks about immutable value classes. That are classes where object identity is strictly bound to value: i.e. one value is only ever represented by exactly one instance. In Java `enum` classes are an example of this pattern.
Answer: When you provide a constructor then the caller decides if a new object is created:
If the constructor for my FooBar class is publicly accessible then any code can run new FooBar() and it will create a new FooBar object (it could fail during construction, but it can't that expression can't just return an existing object instead).
If I made the constructor inaccessible but provide a factory method such as constructFooBar() then the code in the FooBar class  can decide if a new object is created or not. So if some other code calls FooBar.constructFooBar() then the FooBar class alone can decide if it wants to construct a new instance, return an existing one or abort in osme other way (return null or throw an exception).
You can't have the guarantees you mention without controlling who can create instances, which means you can't make the constructors directly accessible.
Note that Boolean is not actually a good example of this, because it does have a publicly accessible constructor.
So this code:
Boolean b1 = Boolean.TRUE;
Boolean b2 = new Boolean(true);
System.out.println(b1.equals(b2));
System.out.println(b1 == b2);

would print true and false.
Comment: The wrapper constructors _are_ [deprecated](https://bugs.openjdk.org/browse/JDK-8252180) for removal. They're not gone yet but they're soon to be.
Comment: True, but that still means that one can't depend on the properties described in the question for `Boolean`.


Using _set.filter(id = 4) Django field fetch

Question: Here is my problem

I'm trying to fetch the data from from page model which is connected to Subject model with a foreignkey. Is there any way on how to fetch the data quickly?
Here is my views.py

urls.py

I'm trying to fetch the field title form page_set.filter object.
here is my models.py
from django.db import models
from ckeditor.fields import RichTextField
# Create your models here.

class Subject(models.Model):
 title = models.CharField(max_length = 200)
 slug = models.SlugField(blank = False)
 visible = models.BooleanField(default = True)
 position = models.IntegerField()
 date_published = models.DateTimeField(auto_now_add = True)
 date_updated = models.DateTimeField(auto_now_add=False)

 def __str__(self):
    return self.title

class Page(models.Model):
 subject = models.ForeignKey(Subject, on_delete= models.CASCADE)
 title = models.CharField(max_length = 200)
 slug = models.SlugField(blank = False)
 description = models.TextField()
 thumbs = models.ImageField(blank = True)
 visible = models.BooleanField(default = True)
 position = models.IntegerField()
 date_published = models.DateTimeField(auto_now_add = True,auto_now=False)
 date_updated = models.DateTimeField(auto_now_add=False, auto_now=True)

 def __str__(self):
    return self.title

class NewsFeed(models.Model):
 title = models.CharField(max_length = 200)
 slug = models.SlugField(blank = False)
 description = models.TextField()
 thumbs = models.ImageField(blank = True)
 visible = models.BooleanField(default = True)
 position = models.IntegerField()
 date_published = models.DateTimeField(auto_now_add = True)
 date_updated = models.DateTimeField(auto_now_add=False)

 def __str__(self):
    return self.title

Comment: you need to call `.get()` instead of `.filter()` on Queryset on `a.page_set`
Comment: show your models, and no pictures please
Comment: Please don't paste code as picture.
Answer: The Page.objects.filter(id=4) results in a QuerySet of Pages, not a single Page. Even if the QuerySet contains one element, it is not a Page (like a list with one number, is not a number). Or as specified in the filter(..) documentation:

Returns a new QuerySet containing objects that match the given lookup parameters.

You can use Page.objects.get(id=4) to obtain a Page object (given it exists, and only one such object exists, otherwise it will raise an error). Or as specified in the get(..) documentation:

Returns the object matching the given lookup parameters, which should
  be in the format described in Field lookups.
get() raises MultipleObjectsReturned if more than one object was
  found. The MultipleObjectsReturned exception is an attribute of the
  model class.
get() raises a DoesNotExist exception if an object wasn't found for
  the given parameters. This exception is an attribute of the model
  class.
Comment: Thanks for the feedback I was looking for a fast answer, I disregarded the .get method instead I used the filter from the tutorials. I've used the .get method now and it works perfectly. Regards


Select rows based on the values in a column

Question: I have an Excel file with a userform where users can insert exchange rates and different parameters for financial report.
I set up a DB file and I want to select rows based on the values in BV column (book value) and it should be higher than 100.000EUR.
The problem is that I have three other currencies besides EUR and I need to calculate EUR amount based on exchange rate.
I made an exchange rate field in my userform (BVAL is EUR default, and I also have BVGBP, BVPLN and BVRSD, which are 100.000EUR divided by each exchange rate).
This works:
SqlQuery = " SELECT * FROM Sheet1 where (bv>=" & BVAL & " and Currency = 'EUR')";"

But when I try to combine multiple results, syntax is not working. I tried other solutions found online.
SqlQuery = " SELECT * FROM Sheet1 where (bv>=" & BVAL & " and Currency='EUR') or (bv>=" & BVGBP & " and  Currency='GBP') _
or (bv>=" & BVPLN & " and  Currency='PLN') or (bv>=" & BVRSD & " and  Currency='RSD');"

Comment: Edit question to show sample raw data and desired output as text tables. What does 'not working' mean - error message, wrong result, nothing happens? What are BVGBP, BVPLN and BVRSD - VBA variables?
Comment: Use parameters. Not string concatenation.
Answer: You SQL syntax is correct, but your VBA is not. Also, for better readability, break up the long lines:
SqlQuery = " SELECT * FROM Sheet1 where " & _
    "(bv>=" & BVAL & " and Currency='EUR') or " & _
    "(bv>=" & BVGBP & " and Currency='GBP') or " & _
    "(bv>=" & BVPLN & " and Currency='PLN') or " & _
    "(bv>=" & BVRSD & " and Currency='RSD');"


Qual a importancia do weak e unowned no swift?

Question: Estou estudando swift faz algum tempo e agora estou querendo me aprofundar na linguagem e na plataforma IOS.
Queria saber de forma mais concreta qual é a importância e qual a forma correta de usar o weak e unowned.
Answer: Essas referencias têm a ver com o ARC. Na prática estás a indicar ao compilador que tipo de referencia é aquela variável para ele conseguir evitar referencias circulares.
Tipicamente tens strong, weak e unowned.

Strong protege o ponteiro de ser deallocado pelo ARC. Enquanto alguma coisa tiver uma referencia a um tipo de objeto strong, não é dealocado. Isto leva a retain cycles. Tens dois objetos com referencias strong, nenhum vai ser dealocado.
Weak Faz o contrário.  Não proteje o ponteiro de ser dealocado.  Um exemplo deste tipo de objetos são os IBActions. Imagina se não fossem do tipo weak. Terias vários problemas.
Unowned é igual ao tipo weak mas não pode ser optional. O tipo weak, quando é dealocado fica com o valor nil. Unowned é utilizado quando sabes que nunca vai ser nil.

Existe mais teoria por tras desta questão, mas esta é a básica.


Refreshing parent page after child FORM close

Question: Currently I have a pop up form they shows a list of data, and I wished to refresh the parent page after the user closes the pop up form. I have look at a few stackoverflow examples and mostly is asking me to use
window.onunload = refreshParent;
 function refreshParent() {
 window.opener.location.reload();
 }
But I tried using those codes in my files and it didn't work. Anyone got any other method or anyone can guide me which part should I enter my code into.
HTML

Stages
Payment Percentage
Pay

<input type="button" id="cancel_hide" value="Close" />

JS
$(document).ready(function(){
$(".login_a").click(function(){
    $("#shadow").fadeIn("normal");
    var test = $(this).attr('data-id');
    var topost = 'getMilestoneDetail.php='+test;
    var returnResults = $.getJSON('getMilestoneDetail.php?id='+test,function(data)
    {
        var m1 = (data.mileStone1);
        var m2 = (data.mileStone2);
        var m3 = (data.mileStone3);

        if(m1 != ''){
        $("#milestone_1").html(data.mileStone1);
        $("#percentage_1").html(data.percentage1);
        }
        if(m2 != ''){
        $("#milestone_2").html(data.mileStone2);
        $("#percentage_2").html(data.percentage2);
        }
        if(m3 != ''){
        $("#milestone_3").html(data.mileStone3);
        $("#percentage_3").html(data.percentage3);
        }
    });
     $("#login_form").fadeIn("normal");
     $("#user_name").focus();
});
$("#cancel_hide").click(function(){
    $("#login_form").fadeOut("normal");
    $("#shadow").fadeOut();
});
});

Answer: If you simply want to reload your page when user clicks the close button then you can do something like this:
$("#cancel_hide").click(function(){
    $("#login_form").fadeOut("normal");
    $("#shadow").fadeOut();
    location.reload(true); //true, so it will not reload the page from browser cache
});

Note: I assume #cancel_hide is the button that is used close the pop-up..


Geometric distribution in a dice case

Question: Say, for a particular case (e.g. getting out of jail in the Monopoly game) our success is two dice showing the same number i.e. (1,1), (2,2) etc. So, there are 6 cases out of 36 possible outcomes. Thus, the probability  of success is 1/6 and that of failure is 5/6.
I am trying to understand the geometric distribution in such an example. Will, the count of trials until success, become data points for the geometric distribution? And after every success, do you start counting from 1 again?
Is this the right understanding of the geometric distribution?
Comment: Yes, you are right. But need to pay attention that there are two definitions:  The final trial with success is counted or not. For example, after 2 failures, the 3rd trial is success. If count success, X=3, if not, X=2. Both definitions are popular. So when deal with geometric distribution, to make sure which definition is used.
Answer: if $X$ counts the trial (roll) on which you finally get
a Success, the expected number of trials required is
$$E(X) = 1/p = \frac{1}{1/6} = 6.$$ See Wikipedia for
both of the definitions mentioned by @user158565. The first definition there is the one
I used just now.
Usually, an analytic proof for $E(X)$ uses moment generating functions or some sort of 'trick' using differentiation. (The Wikipedia article linked above shows such an analytic proof of the expectation for the second definition.)
However, using R as a calculator for your example, I can sum the first
one thousand terms is the infinite series
for $$E(X) = p + 2qp + 3q^2p + 4q^3p + \dots = \frac 1p,$$ where $p = 1/6, q = 1-p = 5/6.$ The remaining
terms (beyond $x = 1000)$ are so small that
the difference between the finite sum and the
infinite sum is negligible. (Summing the first 100 terms is not quite good enough.)
p = 1/6;  q = 1-p
x = 1:1000;  PDF = q^(x-1)*p
sum(x*PDF)
[1] 6
sum(PDF)
[1] 1

R statistical software uses the second definition, where $Y$ is the number of failures before the first success.
So in the following simulation to demonstrate $E(X),$ I use $E(Y+1) = E(X).$
I use a million
iterations (to get out of jail a million times)
in the simulation, so we can expect about 2-place accuracy.
set.seed(727)  # for reproducibility
mean(rgeom(10^6, 1/6)+1)
[1] 5.992297  # aprx $E(X) = 6.$

Geometric distribution in a dice case


Joint distribution of two dependent variables

Question: I was wondering how to (or if it is even possible) find the continuous joint distribution between two random variables $x$ and $y$ when you know the continuous marginal density distributions of both $x$ and $y$, and we know there is a correlation between the two random variables, i.e., ${\rm Cor}(x,y)$ = $\rho$ which is of unknown magnitude?
Comment: Possibly of interest: [Is it possible to have a pair of Gaussian random variables for which the joint distribution is not Gaussian?](http://stats.stackexchange.com/a/30205/7290)
Comment: @gung Using copulas is interesting, but how would this be done without knowing the correlation, $\rho$?
Comment: Essentially Chris, the answers are saying, "there is an indefinite number of possible joint distributions that are compatible with given marginals and a given correlation between two random variables".
Answer: From Sklar's Theorem, it follows that you can construct the joint distribution using a copula:
$$H(x,y) = C(F(x),G(y)).$$
So, you need two ingredients: the marginal distributions $(F,G)$, and the copula $C$. You mentioned that you know the marginals, so this ingredient is done. Now, you need information to construct the copula. So, if you cannot come up with enough information to select/estimate/guess/divine the copula, then you cannot construct the joint distribution.
Answer: Supposed that in Excel you create z-score of random variable P and Q, using a built-in function
=norminv(rand(),0,1)
If ρ is specified, then
X = P and Y = P*ρ + Q*sqrt(1-ρ^2)
The generated X and Y will distributed as normal distribution with zero mean and sd 1 with correlation coefficient = ρ.
I saw this formula a long time ago but could not find the reference now. Luckily, it works.


Cox Time Varying Regression model - python lifelines - start and stop variables

Question: I have a question about the implementation of Cox Time Varying Regression model, that I need to perform to understand the impact of co-variates on my survival prediction.
I found an example here (https://lifelines.readthedocs.io/en/latest/Time%20varying%20survival%20regression.html) but I still have a doubt.
My dataset contains some patients (so rows of the dataframe with the same ID) that are not studied continuously during the observation time, showing some "gaps"; so, for example, I have info like that:

ID: 1 , start: 0 , stop: 50  , event : 0
ID: 1 , start: 60 , stop: 80  , event : 0
ID: 1 , start: 80 , stop: 100 , event : 1

So, as you can see, the first two time intervals are not consecutive but have a gap (from 50 to 60). Do you know whether I can include these patients in my analysis or I have to remove them? I have this doubt because I've never seen this "situation" in the examples I found online.
Thank you in advance.
Answer: If there can be at most one event per individual in a Cox model, then the gaps don't matter. Each time interval is treated as left-truncated at the lower end and, if there is no event, right-censored at the upper end. For such a model, you don't even need to keep track of patient IDs. In that case, as the R vignette on time-dependent survival models explains in Section 2:

this representation is simply a programming trick. The likelihood equations at any time point use only one copy of any subject, the program picks out the correct row of data at each time.

Thus an individual provides information during the time intervals for which you have data, and no information during the gaps.
The situation is different if there can be more than one event per individual in a Cox model, or in fully parametric models.
Be very careful, however, in building and interpreting models with time-varying covariate values. There is a big risk of survivorship bias; the lifelines package thus won't allow predictions from such a model.
Comment: Thank you very much for your reply. I actually didn't completely catch your last comment about the survivorship bias: do you think that the presence of gaps bias the model or it was a generic comment, unrelated to my initial doubt?
Comment: @ValerioPugliese that's a generic comment, made because I've answered several related questions on this site and time-varying covariates are often found to be troublesome. You might look at [this answer](https://stats.stackexchange.com/a/489006/28500) from the author of `lifelines` and my generally supportive (if less dogmatic) [answer](https://stats.stackexchange.com/a/534939/28500) on the same page. The original fitting of the model about which you inquired isn't at issue, even with gaps of time within an individual. It's interpretation and prediction that pose problems, even without gaps.


Using Acceleo 3 with Ant

Question: I'm looking for information on how to perform Acceleo source generation with an Ant script. I've done some Googleing, but I haven't really found any straightforward way to do that. I'm looking first to do it in Eclipse, but a headless (is that the right word?) script would also be nice for semi-automatic builds.
Can anyone offer any help? Or are my expectations of what Acceleo can do unreasonable?
Answer: I believe all you need to do is to use a  ant task to call your generation class.
The generation class is the one generated along your mtl file that contains an "@main" annotation.
Beware though, the generation will run in standalone mode, so don't use services that rely on eclipse API!
The ant task should look like this:
<code><java classname="your.generation.class.GenerateJava"
        classpathref="your.classpath.defined.in.ant">
    <arg value="your/input/model/example.uml"/>
    <arg value="your/target/folder" />
</java>
</code>
Hope this will help...
Comment: Thanks, I'll give this a try. We're using an ecore model, does that change anything? Sorry for the noob questions, but I'm new to this kind of source generation.
Comment: Using an Ecore model won't make any difference, it should be straightforward.

Using Acceleo 3 with Ant


High available and secure FrontEnd to WebApps behind a firewall

Question: my question is about proposed implementation of high available and secure FrontEnd to WebApps behind a firewall. The components of the network and their relationships are as follows:
1) 2 WebApps servers behind a firewall (BackEnd), denoted by GUI1 and GUI2, running Web Applications
2) 2 machines LB1 and LB2 located in DMZ configured with floating IP in active/standby mode for redundancy. Their task is

to give an additional layer of security serving as a proxy (they are performing NAT on packets coming from GUI)
to handle the traffic basing on inspection of cookies (in fact the only requirement is to achieve cookie-based session persistence, not sophisticated LB techniques)

Security requirments:

The only acceptable communication method with GUI that is allowed (clearly through the FireWall) is via reverse SSH tunnel.
The traffic incoming to FrontEnd is most often https (and some http)

The question is: what kind of software (open source) is the best option to be implemented on frontend machines LB1 and LB2, to realize these goals? Recall, in short:

SSL termination (as necessary for inspecting cookie)
Cookie Based LB
active/standby mode

I have no practical experience in this field, however it seems that NginX on LB1 and LB2 (to solve SSL and cookies issue) together with HearBeat (to achieve the desired redundancy property) should work.
I am aware that the proposed architecture is somehow similar to HAproxy or LVS (configured as two redundant instances), however I need a solution that guarantees dealing with all described tasks simultaneously (for instance, HAproxy does not support SSL termination).
Any comments and suggestions are welcomed. Thanks!
Comment: Looks like a shopping question, but have a look at http://www.apsis.ch/pound/ (if you cant afford f5-bigip).
Answer: how about nginx behind haproxy?
Comment: I am not sure if I have understood correctly. Did you mean setting an nginx server in front of haproxy in such a way that the request from the webbrowser is send through the nginx server first where SSL is terminated if necessary and next to haproxt server which performs load balancing to the suitable backend server? In this way nginx would be used as SSL terminator only and in fact both servers could be running on the same machine (nginx is listening on http and https port and forwarding packages on another port where haproxy is configured to listen). Does it make sense?
Comment: @MaciejS - i was rather thinking about having HAProxy as internet facing server [if you have so much load] to do load balancing between nginxes. and nginxes as ssl terminators / cookie-based load balancers between your backends. although probably just nginx might be enough.
Answer: With native SSL support coming in haproxy in a few days/weeks, maybe you'll want to be a happy beta tester ? :-)


difference between trial and observation

Question: What's the difference between a trial and an observation?  My sense is that an observation is a measurement of a variable for a single trial.  Is this correct?
Answer: Simply put,
A Trial —— is the act of carrying out an experiment, while
An Observation —— is the value of a data point used in an experiment
Note: The total number of data points used in an experiment, is also known as sample size or number of observations, n


just want to change checkbox value while submit

Question: I am using drupal 7:
$form['title']['#tree'] = TRUE;
$form['title']['node_first'] = array(
    '#type' => 'checkboxes',
    '#options' => array(
        'value' => $value->title,
    ),
);
$form['title']['node_second'] = array(
    '#type' => 'checkboxes',
    '#options' => array(
        'value' => $value2->title,
    ),
);

i am getting this output after submitting (when first checkbox has been checked) :
    Array
(
    [title] => Array
        (
            [node_first] => Array
                (
                    [value] => value
                )

            [node_second] => Array
                (
                    [value] => 0
                )

        )
)

desired output:
Array
(
    [title] => Array
        (
            [node_first] => Array
                (
                    [value] => True
                )

            [node_second] => Array
                (
                    [value] => False
                )

        )
)

Comment: Drupal won't do that for you; just cast the value to a bool if you need one
Answer: It should be possible to manipulate the values as desired in a custom validate function. In your form code, add something like this:
$form['#validate'][] = 'mymodule_custom_validate';

The mymodule_custom_validate is a function you could define as such to change the values to booleans, or anything else you need:
function mymodule_custom_validate(&$form, &$form_state) {
  if ($form_state['values']['title']['node_first']['value'] === 'value') {
    $form_state['values']['title']['node_first']['value'] = True;
  }
  else {
    $form_state['values']['title']['node_first']['value'] = False;
  }
  if ($form_state['values']['title']['node_second']['value'] === 'value') {
    $form_state['values']['title']['node_second']['value'] = True;
  }
  else {
    $form_state['values']['title']['node_second']['value'] = False;
  }
}

This is a fairly rudimentary implementation, but hopefully this will lead you in the right direction. You can see in this example how the values can be manipulated before they reach the submit handler.
Answer: Surely a single checkbox would be better?
$form['title']['#tree'] = TRUE;
$form['title']['node_first'] = array(
    '#type' => 'checkbox',
    '#title' => $value->title,
);
$form['title']['node_second'] = array(
    '#type' => 'checkbox',
    '#title' => $value2->title,
);

Form API Reference


What are the chords used to end blues songs like "One Way Out"?

Question: The ending to "One Way Out" as done by the Allman Brothers Band has an ending that is common to lots of blues songs.  It follows what sounds like a descending run like a normal turnaround with the ending being two chords with a beautiful minor/flat sound.  What are these chords and how do they fit into the standard blues form?  Here is the song.
Comment: Yes, hearing this song recently just reminded me that I've wondered about that ending that sounds the same for lots of songs for a long time.  Being the blues, I shouldn't have been surprised that it's a simple variation of a turnaround.
Answer: This is indeed one variation of a standard blues cliché. The chords they play are
| A  A7/C#  D7  D#dim7 |  A  Adim7  A7  |
Note the chromatically ascending bass line in the first bar:
A C# D D#
which would often lead to an A7/E chord, i.e. the chromatic line would continue up to the E. The descending melody line you hear could be
| A G F# F# | E Eb E |
There is also a cliché melody line which would really descend chromatically from the G to the E (i.e., it would replace the second F# in the above line with an F), but it doesn't fit these chords. For that chromatic line to work you would need to replace the D#dim7 chord with a Dm7, which is one other variation of this classic progression.
This progression can be played at the end of a (blues) song, as in "One Way Out". With a slight variation it can also be played as a standard turn-around in the last two bars of a 12-bar blues. As a turn-around the progression leads back to the V7 chord (E7), which, in turn, leads back to the beginning of the next 12-bar verse/chorus:
| A  A7/C#  D7  D#dim7 |  A  F7  E7  |
Comment: @PJNoes: It's a blues in A, this means that the root chord is A7 (which has a major third). It's not a minor blues, but normally you wouldn't call it "major blues". Note that the chords of a blues are usually not based on one single scale.
Comment: Can I assume from the bass line that this is a major blues song?  If it were minor blues wouldn't the notes be from the natural C scale?


Sub-Turing Complete Class of computational models

Question: Many programming languages and systems are Turing-complete; they can simulate any Turing machine, and therefore can simulate any finite state machine as well.
Consider the following informal model:
Language A defines a finite set of NAND gates, their connections to each other, and which gates receive input and which are outputted.
In this model, any finite state machine can be built. The NANDs can form latches, registers, busses and control structures, and in the end any finite state machine, including full computers and other systems.
The model, however, does not have the ability to simulate an infinite tape, only a tape of finite size. It cannot simulate any Turing machine because it may not have the memory to do so.
Are Language A and all other systems that can simulate any finite state machine considered Turing complete? Is there a separate class for them, or is there an opportunity to define such?
Answer: As you have realized, there is a hierarchy - with potentially infinitely many levels - of classes of languages, including regular languages (recognizable by finite automata) and decidable (accepted by a Turing machine).
All real computers - including theoretical models which can be used to construct them, like yours involving NAND gates - are not Turing equivalent because they cannot in theory access an infinite tape. In practice, time, space and matter are insufficient in physical reality to allow for real Turing-equivalent computation. All physical computation can be carried out by a finite automata. There are regular languages, in practice, too complex to ever accept by constructing a real finite state machine or general-purpose computer.
Modeling languages as being of a type higher than regular is for convenience - it is a lie in the same way that modeling matter as continuous (e.g., when computing moment of inertia) is a lie. Matter is really made of discrete molecules, which in turn are comprised of smaller discrete particles.


Is this an acceptable fingering of a G Chord?

Question: I'm trying out the CAGED method, and whenever I use the G Form, either my pinky can't keep enough pressure on the High E string, or my ring finger lies so flat that it mutes the A string.
By curling up my pinky and fretting the high E with my pinky knuckle, I get a clean chord every time.
The problem is that it hurts, but I don't know if it's the "I've never done this before" kind of pain or the "I shouldn't be doing this" kind of pain.
I should add that the ring finger on that hand had its tip crushed when I was about 10, so it's a little misshaped. So, while advice on how to finger it properly without using the knuckle is appreciated, it may not work for my unique hand. However, it may work, so feel free to give advice on that.
Comment: For those of us who don't know, what's the CAGED method?
Comment: The CAGED method has you keep your index finger free for barre chords when you move down the fretboard
Comment: See this question for more details on the CAGED method http://music.stackexchange.com/questions/1455/how-to-begin-learning-the-caged-method
Comment: Is that your right hand in the photo? Or has the image been flipped?
Comment: It's my left. That'll teach me to use PhotoBooth, it automatically flips images.
Comment: That skin, at least for me, is pretty sensitive.  If it were me and the pain continued for a length of time after I had stopped playing it's bad.  My thumb used to get sore from using it to fret notes when all other fingers were busy.  It stopped hurting after I built up a callus.
Comment: As long as it sounds good, why not? Just play with what feels right and comfortable as long as it sounds good!
Comment: I just saying that it might make it harder to change between chords, if you don't build callouses on that part of the finger than find another fingering but good luck.
Answer: Wow, that looks nasty! Looks like your missing your pinky!
I have no issues playing the caged system in both open and barre but I love the sound of the open G played with just the 1st and 6th G's fretted. Very easy to play and a very nice sounding chord. It goes well with playing an open Am7 with doubled 7ths(3rd and 1st string).
Try it out and and use it instead. You can use your middle or pinky for the 1st string but I suggest you use your pinky to get used to using it. ALSO, because your not fretting the 5th string(A) you must mute it or you'll get a Gadd9 type of chord that won't sound that great. You do this simply by allowing your finger that is fretting the G on the 6th string to rest against the 5th string.
In any case if it's really easy for you to play like you are then I guess you can but realize it will be hard for you to use that pinky for melodic notes and it might slow you down when changing chords.
Answer: Try using your index finger for the A string and your Middle finger for the E string, Then your pinky should fit comfortably on the lower e string...
I would most certainly not hold the pinky the way you are...  Since You will get huge problems when learning more difficult chords in the future...
Comment: He wants to slide the g form of the chord up the fret board, so he needs his index finger to form a barre underneath.
Answer: I had issues with the G chord as well. Training myself in classical style for discipline requires the pinky to hold down the high E string. Like you, I was either muting the A string with my ring finger or muting the high E string because my pinky wasn't pushed down hard enough. In observing very carefully what I was doing, I noticed that rather than actually pushing down on the high E string when my fingers were properly arched, my pinky's nail (which was actually pretty short) was grinding into the fingerboard and prevented me from properly holding the high E string down to get a clear tone (even when playing right behind the fret). I filed my pinky nail down and voila, I was finally able to apply proper pressure to the high E string to get a clear chord without having to flatten my ring finger causing the A string to be muted.
Answer: Now, it might be easier now to finger the G chord like this, but later on it will slow your chord changes. It would probably be better to use the tip of your pinky.
I think the problem is that when you try to finger the G chord normally, i.e., using the tip of your pinky on the high E string, your fingers are lying too flat on the string. It seems that fingering the G chord like the way you are doing naturally raises the other two fingers so that it is not muting the other strings. What I would recommend you to do is to practice fingering the chord using only the very tip of your fingers. Play each note of the chord to make sure that each note rings cleanly. If you're a beginner, then it helps to keep your thumb behind the neck (later on you can put your thumb over the neck of you like it that way).
Comment: The OP doesn't just want to play an open G, it's a moveable G shape.
Answer: Fingering the chord this way is not a good idea, because You're building up a bad habit instead of good practice. I'm sure You can get the right sound using Your pinky in normal way, with practice and patience.
Chord You try to finger is basic chord, that  You find in the start of learning the guitar chords path. Your fingering will not help You to progress on this path to more advanced chords.
P.S. And to to be advocatus diaboli - things like this can sometimes define Your unique style (i think primarly of Django Reinhardt and his crippled fingers - which has influence on his style and sound), but i don't think this is the case.
Comment: I think you missed the OP's point of moving the chord up the fingerboard.


Is there a name for the interval [1: 5/2]

Question: I was looking at intervals here: https://en.wikipedia.org/wiki/List_of_pitch_intervals
and I noticed that they are all contained in the octave [1: 2]
How does one talk about something like [1: 5/2]?
Comment: @KeizerHarm It's not a perfect twelfth or an "octave plus a perfect fifth" because the ratios multiply.  A perfect twelfth would be 2 × (3/2) = 3.  (Or [1 : 3] using the inverted form in the question.]
Comment: That'd be an octave plus a perfect fifth.
Comment: Ok so you just combine the names of intervals to go out past the octave?
Comment: It depends, you can also call it a perfect twelfth. See this page: https://en.wikipedia.org/wiki/Interval_(music)#Compound_intervals
Comment: @Theodore Ok, my bad ^^; OP please discount everything I said
Answer: First of all, you're describing the intervals in their inverse.  An octave is usually written (including within the Wikipedia article you linked) as the ratio 2 : 1.  It may also be written as the improper fraction 2/1.
When combining smaller intervals, the ratios multiply to reach the total.
The particular interval you mention, 5 : 2  or 5/2 can be considered as (2/1) × (5/4), which is to say an octave plus a just major third, also known as a just major 10th.
Comment: Side note (obvious to most of us :-) ) is that adding named intervals requires subtracting "one."  In this case octave (8) plus fifth (5) produces  twelfth (8 + 5 -1 ).   In math we call this something like the "fence post theory" because you don't want to count the point which is the  end of one sequence  *and* the beginning of the next one twice.


Deriving formula for approximating the derivatives

Question: Derive the following formula for approximating derivates and show that it is O(h^4) by establishing its error:
$$
f'(x) \approx \frac{1}{12h} [-f(x+2h)+8f(x+h)-8f(x-h)+f(x-2h)]
$$
I've tried writing everything out with their taylor expansions. Then I get
$$
f'(x) \approx \frac{1}{12h} \left( 12hf'(x) \right)
$$
But I am not sure if im doing the right thing. Any ideas or hints?
Answer: Write the Taylor expansion of your terms up to fourth order
For example:
$$ f(x+h)= f(x) + hf'(x) + h^2/2 f"(x) + h^3/6 f'''(x) + O(h^4)$$
$$ f(x-h)= f(x) - hf'(x) + h^2/2 f"(x) - h^3/6 f'''(x) + O(h^4)$$
$$  f(x+2h)= f(x) +2hf'(x) + (2h)^2/2 f"(x) + (2h)^3/6 f'''(x) + O(h^4)$$
$$f(x-2h)= f(x) -2hf'(x) + (2h)^2/2 f"(x) - (2h)^3/6 f'''(x) + O(h^4)$$
Plug in the RHS and solve for f'(x) to get the LHS.
Comment: Thank you for this comment. Where do you get + O(h^4) from?
Comment: All the other terms have a factor of $h^4$
Comment: Unfortunately, this isn't enough terms to compute the error term. See my answer.
Answer: It's best to go to a high enough order we can see how close the approximation is. Using$$\begin{align}f(x+ch)&\in f(x)+cf^\prime(x)h\\&+\tfrac{c^2}{2}f^{\prime\prime}(x)h^2+\tfrac{c^3}{3!}f^{(3)}(x)h^3+\tfrac{c^4}{4!}f^{(4)}(x)h^4+\tfrac{c^5}{5!}f^{(5)}(x)h^5+o(h^5),\end{align}$$you can show the right-hand side is $f^\prime(x)-\tfrac{1}{30}f^{(5)}(x)h^4+o(h^4)$. (To save you work beside computing the $h^4$ coefficient, note the $f^{(2n)}$ terms will always cancel because $f(x+ch)-f(x-ch)$ is odd in $c$, while the $f^{(3)}$ term cancels because $8f(x+h)+f(x-2h)$ has no $h^3$ term.) The error is $O(h^4)$, making the approximation excellent for small $h$.
Comment: Thanks a lot for this! Where do you get + o(h^5) from in the end? It's not a part of the formula in my book
Comment: @Zebraboard See the [Peano form of the remainder in Taylor's theorem](https://en.wikipedia.org/wiki/Taylor%27s_theorem#Statement_of_the_theorem). See also [little-o notation](https://en.wikipedia.org/wiki/Big_O_notation#Little-o_notation). At your level, writing $+\cdots$ may be good enough.


Erro no map: this.state.filmes.map is not a function. Não estou conseguindo acessar as informações do results. Poderiam me ajudar?

Question: import React, { Component, Fragment } from 'react';
import $ from 'jquery';

export class ListaFilmes extends Component{

    constructor() {
        super();
        this.state = {
            filmes: [],
        }

    }

    componentDidMount() {

        $.ajax({
            url: "http://localhost:3000/filmes?page=1",
            type: 'GET',
            dataType: 'json',
            contentType: 'application/json',

            success: function (resposta) {

                this.setState({filmes: resposta});
                console.log(resposta);

            }.bind(this),
            error: function (data) {

                console.log(data)
            }
        });
    }

    render(){
        return(

                {this.state.filmes.map((item) =>

{item.results}

                )}

        )
    }
}

Comment: Nunhuma [dessas](https://pt.stackoverflow.com/search?q=map+is+not+a+function+%5Breact%5D) resolve seu problema? Parece que esse é um erro comum no React
Answer: O que ocorre é que no seu state o "filmes" é um array, mas, o retorno de sua API é um objeto. Como você está atribuindo a resposta da API ao state "filmes", você acaba recebendo este erro de "map is not a function", já que "map" se aplica a arrays.
No seu objeto recebido da API, você tem "results", e "results" é um array. Você deve atribuir o valor dele para "filmes".
Sua consulta ficaria da seguinte forma:
componentDidMount() {
$.ajax({
    url: "http://localhost:3000/filmes?page=1",
    type: 'GET',
    dataType: 'json',
    contentType: 'application/json',
    success: function (resposta) {
        this.setState({filmes: resposta.results});
        console.log(resposta);
    }.bind(this),
    error: function (data) {

        console.log(data)
    }
});

}
Comment: Coloquei como você pediu!! Deu certo!!! Muito obrigada msm, fiquei um tempão tentando achar o erro!! Me salvouuu