Ao finalizar o script com "Ctrl+C" (KeyboardInterrupt) não fecha Selenium o Firefox

Question: Estou utilizando o selenium para manipular uma pagina, ao executar o script ele abre o firefox, mas o que eu queria fazer é o seguinte, se acontecer qualquer problema no script ou se o usuário finalizar, quero que o firefox feche também.
Tentei varias coisas como:
Usar o exit:
def __exit__(self):
    self.fechaAba()

Ou o del:
def __del__(self):
    self.fechaAba()

A função que estou utilizando é esta, ela esta funcionando, utilizo ela nas exceptions para fechar o firefox quando da erro.
def fechaAba(self):
    try:
        self.__driver.driver.close()
    except:
        setLog("Firefox ja finalizado")

Mas por exemplo se aperto Ctrl + C para finalizar o script ele não fecha o firefox, o mais perto que eu cheguei foi utilizando o atexit:
import atexit

    def __init__(self):
        atexit.register(self.exit_handler)

    def exit_handler(self):
        self.fechaAba()

Ele apresenta a mensagem "Firefox ja finalizado", mas o firefox continua aberto:
KeyboardInterrupt

[2017-09-28 15:16:41]: Firefox ja finalizado

[2017-09-28 15:16:42]: Firefox ja finalizado

Quando eu uso o driver.close() ele entra na exception e apresenta a mensagem "Firefox ja finalizado", ou seja ele não conseguiu executar o comando, e quando eu uso quit o efeito é parecido, ele executa normalmente o quit(Não entra na exception), mas o firefox continua aberto.
Fiz um pequeno exemplo:
from selenium import webdriver
import time
import atexit

class WhatsappAPI(object):

    driver = None

    def __init__(self):
        print "__init__"
        atexit.register(self.exit_handler)
        self.driver = webdriver.Firefox()
        self.driver.get("http://web.whatsapp.com")

    def comeca_acao(self):
        while True:
            time.sleep(10)
            print "ok"

    def exit_handler(self):
        print "exit_handler"
        self.driver.quit()

    def __exit__(self):
        print "__exit__"
        self.driver.quit()

    def __del__(self):
        print "__del__"
        self.driver.quit()

w = WhatsappAPI()
w.comeca_acao()

Resultado:
teste.py
__init__
Traceback (most recent call last):
  File "C:\Users\Futurotec\Documents\futurofone_chat\branch\v3.12\_externo\WhatsappBot - Instalador\Final\WhatsappWebAPI\teste.py", line 34, in <module>
    w.comeca_acao()
  File "C:\Users\Futurotec\Documents\futurofone_chat\branch\v3.12\_externo\WhatsappBot - Instalador\Final\WhatsappWebAPI\teste.py", line 17, in comeca_acao
    time.sleep(10)
KeyboardInterrupt
exit_handler
__del__

Quando aparece no terminal "__init__" ele abre o firefox, quando aperto ctrl c o firefox continua aberto, o que eu quero é que o firefox feche ao aperta ctrl c ou quando entrar em qualquer exception. Nas exceptions já funciona, mas quando aperto ctrl c não.
Comment: Após testes percebi que o problema realmente parece ser ou com o Sellenium ou com o geckodriver (provavelmente só ocorre no Windows, mas não posso afirmar). Estou tentando criar para contornar. +1 porque a duvida será muito útil para muitos visitantes.
Comment: tente utilizar a biblioteca Pyinput para verificar a sequência de teclas pressionadas, caso positivo para "Cltr+C" vc utilizar o webdriver.quit() | firefox.quit()
Answer: Experimenta tratar a exceção KeyboardInterrupt quando for executar o programa, ex:
try:
  w = WhatsappAPI()
  w.comeca_acao()
except KeyboardInterrupt:
  w.driver.quit()
  print "Ate logo!"

Answer: Você pode matar o firefox independentemente do Selenium, com a consequência de que você mata o processo por completo, não apenas a aba que seu script tenha iniciado. Além de não fechar o processo de forma "limpa".
import os
os.system("taskkill /f /im firefox.exe")

/f manda encerrar à força. /im faz o taskkill identificar o programa pelo nome.
Comment: O problema que esta solução irá fechar todas as instâncias do firefox, e o problema em questão que ele não consegue realizar o comando depois da finalização do script, então acredito que este comando não será executado também.
Comment: Este código pode ser colocado dentro de um [tratador de saída](https://docs.python.org/3/library/atexit.html). Ainda vai fechar o firefox por completo, mas vai rodar quando você apertar ctrl c.


Consumir arquivo .mdb e gravar no MySQL com PHP

Question: Possuo um arquivo .mdb , e preciso injetar todos os dados dele no MySQL através de código PHP. O que eu faço é o seguinte:
<code>// Executa comando via shell para upload do banco no mysql
$scriptEsquema = shell_exec('mdb-schema uploads/arquivo.mdb mysql | grep -v ^DROP | mysql -u usuario meubancodedados');
$scriptInsert = shell_exec('mdb-export -D "%Y-%m-%d %H:%M:%S" -H -I mysql uploads/arquivo.mdb MINHATABELA | mysql -u usuario meubancodedados');
</code>

No meu computador funciona tranquilamente, mas ao passar para um servidor ele não funciona mais.

Existiria um outro jeito de fazer isso com PHP? Ou algo que devo fazer no servidor?
Comment: coloca o caminho inteiro na sua linha, se for linux `/var/www/html/teu-projeto/uploads/arquivo.mdb` e se for windows `c:\um\lugar\uploads\arquivo.mdb`, acredito que o bash execute sem identificar onde está seu diretório quando isso é feito da forma que especificou. ou simplesmente põe no código `cd/caminho/uploads/arquivo.mdb && mdb-schema ...`
Answer: Se não me engano, geralmente, este comando "shell_exec" é bloqueado por segurança no servidor de produção, sobretudo nas hospedagens compartilhadas.
Sugiro três coisas:
1/Verifique se sua hospedagem libera esse comando para rodar no servidor.
2/Exportar os dados desse BD para CSV, criar rotina em PHP para ler esse CSV e então dar carga no BD MySQL.
3/Se sua hospedagem for dedicada, então suba esses dados via SSH, se bem que a chance de liberar o comando "shell_exec" será maior pois o servidor será dedicado.
Então é isso. Espero que ajude de alguma forma as respostas.
Answer: Uma maneira de fazer isso é fazer uma conexão diretamente ao arquivo:
<code>$db = 'uploads/arquivo.mdb';
$conn_mdb = new COM('ADODB.Connection');
$conn_mdb->Open("DRIVER={Driver do Microsoft Access (*.mdb)}; DBQ=$db");
if (!$conn_mdb) {
   echo "Xiii, faiô a conexão do MDB! ";
   die();
}
$sql = 'SELECT campo1, campo2 FROM tabela';
$res = $conn_mdb->Execute($sql);

$conn_mysqli=mysqli_connect("localhost","my_user","my_password","my_db");
if (mysqli_connect_errno()) {
   echo "Xiii, faiô a conexão do MySQL: " . mysqli_connect_error();
   die();
}

while (!$res->EOF) {
     mysqli_query($conn_mysqli,"INSERT INTO tabela (campo1, campo2)
                                VALUES ('".$res->Fields['campo1']->Value."',
                                        '".$res->Fields['campo2']->Value."')");
    $res->MoveNext();
}
</code>
Aqui tem mais sobre esse tipo de conexão.
Caso seu sistema seja Linux, é melhor utilizar uma ferramenta chamada MDBTOOLS.
A propósito, se a opção for só exportar os dados do seu mdb para o banco MySQL, o próprio programa Microsoft Access tem uma opção para exportar os dados em formato de planilha Excel (CSV), cujo o formato é compatível com o MySQL.
Para Windows, também existem outras opções para exportar arquivos mdb diretamente para o MySQL. Como por exemplo o MySQL Front.


Inequality with natural numbers - how to find a solution

Question: Assume $z,y\in\mathbb{N}$ where $z\geq y$.  I want to prove that there exists $x\in\mathbb{N}$ such that:
$ 2z > x \geq z $
where $y$ divides x.
I've tried for some cases and it seems to hold. How to solve this? Or more general/important how to solve these kinds of problems?
Comment: Are you sure about your statement? Take $z=y=0$.
Comment: @5xum For me, $\mathbb{N}=\left\{0,1,2,3,\cdots \right\}$. But your example is perfect.
Comment: I added the extra condition that $y$ should divide x.
Comment: and 0 is not contained in my definition of $\mathbb{N}$ :)
Answer: The candidate values for $x$ are $z,z+1, z+2,\dots, z+(z-1)$
Take a look at the remainder of these values when divided by $y$, i.e.
$$z \bmod y, (z+1) \bmod y, (z+2) \bmod y,\dots, (2z-1) \bmod y.$$
The numbers in this list can only take $y$ different values and they increase by $1$ until hitting $y$, at which point they fall to $0$. Because there are $z$ of them, the fall to $0$ must happen somewhere.
Comment: You can use `\bmod` for "binary mod". =)
Comment: This was a very simple approach: Just write down the candidates and then consider the residue classes - I'll do this next time I encounter such a problem, thanks!
Comment: @guestguest Well, it may not work the next time, but here, this "quasi-pidgeonhole" principle works quite well.


Ler de arquivo txt para vetor de char

Question: Tenho um arquivo dados.txt com CPFs (fictícios) nos seguinte formato:
382031758-71
647900189-01
460754503-73
696170135-72

E assim por diante, sendo no total 500 cpfs. Estou tentando ler cada um e colocar em char cpf[12] (porque cada um tem 12 caracteres contando o -), porém ao imprimir são impressos três caracteres estranhos tipo @ýý
int main(){

//abre o arquivo em modo leitura
FILE *dados = fopen("dados.txt", "r");

char cpf[12];

fseek(dados, 0, SEEK_SET); //vai para o inicio do arquivo
//fgets(cpf, 100, dados); //pega 12 caracteres

for(int i = 0; i < 12; i++){
    cpf[i] = fgetc(dados);
}

printf("%s\n", cpf);

fclose(dados);
}

Tentei também com fscanf(dados, "%s\n", cpf); mas deu na mesma. Assim, gostaria de entender como ler esses dados dessa forma. Quero armazenar em uma variável porque preciso usar isso para testar uma função hash depois.
Comment: C ou C++ ? O código que tem é C mas marcou a tag C++ e C++ tem formas bem mais simples de ler informação de arquivos, assim como de armazenar em variaveis.
Comment: Creio que seja por causa que o seu vetor não esteja considerando o fim da cadeia de caracteres, mude `char cpf[12]` para `char cpf[13]`
Comment: não é isso, mesmo que mude para cpf[100] continua assim
Comment: tanto faz, pode ser em c++
Answer: A leitura que está a ser feita não só não aloca espaço para o terminador, como também não o coloca. Por este motivo quando tenta mostrar o valor na consola apanha outros valores que estão na memoria que segue onde o vetor de char foi alocado.
Para corrigir basta o seguinte:
int main() {
    FILE *dados = fopen("dados.txt", "r");

    char cpf[13]; //13 em vez de 12 para guardar tambem o terminador
    fseek(dados, 0, SEEK_SET);

    for(int i = 0; i < 12; i++) {
        cpf[i] = fgetc(dados);
    }
    cpf[12] = '\0'; //coloca o terminador no fim da string

Assim como disse em comentário o C++ fornece-lhe formas mais simples de ler arquivos assim como de armazenar strings, que lhe evita precisamente este tipo de pormenores que são fáceis de passar despercebidos.
Em c++ para ler todos os cpfs pode fazer assim:
#include <iostream>
#include <fstream>

int main() {
    std::ifstream dados("dados.txt");
    std::string cpf;
    while (std::getline(dados, cpf)){ //ler cada cpf até ao fim
        std::cout << cpf << std::endl; //usar o cpf
    }
}

Utilizei o ifstream para operar no arquivo como dados de entrada, e fiz a leitura linha a linha à custa de getline.

Ler de arquivo txt para vetor de char


Webform + Translations

Question: I have a website where 80% of it are Webforms. Admins can create webforms themselves and registered users can fill them in. ( A PDF will be created etc etc...).
Now I have to make this website in 3 other languages then the default.
I Found already the following module:
https://www.drupal.org/project/webform_localization
Now my initial question:
Imagine you have a webform in the wizard with  a label, and a textarea and a default value as type or static text. What is the best way to get the 'default' values in the context translated?
Example
https://i.stack.imgur.com/t4uLi.png
Note:
This is text which got changed for every webform generated on the website.
Answer: This is content - not static text; your only options are to translate it manually yourself or use one of the contrib modules like Lingotek or Cloudwords.
Answer: If you use Entity Translation (recommended), you can use the Webform Translation module.

Webform + Translations


(C++) How do I display an error when more than one "." is used in a calcualtor?

Question: I am making a calculator using command line arguments, and one of the problems I am having is that I can't find a way to display an error to inputs that have more than one ".". 3.33 can be accepted, but 126.96.36.199 cannot because its an invalid number.
int main(int argc, char *argv[]) {
  if (argc == 1) {

    cout << "E\n";
    return 0;
  }
  if (argc <= 2) {
    cout << "P\n";
    return 0;
  }
  if (argc > 4) {
    cout << "P\n";
    return 0;
  }

  if (argc == 3) {
    cout << endl << (atof(argv[1]) + atof(argv[2])) << endl;
    return 0;
  }

  else if (argc == 4) {
    // Addition operation
    if (argv[3][0] == 'a')
      cout << endl << (atoi(argv[1]) + atoi(argv[2])) << endl;

    // Subtraction operation
    else if (argv[3][0] == 's')
      cout << endl << (atof(argv[1]) - atof(argv[2])) << endl;

    // Multiplication operation
    else if (argv[3][0] == 'm')
      cout << endl << (atof(argv[1]) * atof(argv[2])) << endl;

    // Division operation
    else if (argv[3][0] == 'd')
      if (argv[2][0] == '0') {
        cout << endl << "error";
        return 0;
      } else {
        cout << endl << (atof(argv[1]) / atof(argv[2])) << endl;
      }

    // Exponential operation
    else if (argv[3][0] == 'p')
      if (argv[2][0] > -1.00 && argv[2][0] < 1.00) {
        cout << endl << "Y";
        return 0;
      } else if (argv[1][0] == '-') {
        cout << endl << "Y";
        return 0;
      }

      else
        cout << endl << pow(atof(argv[1]), atof(argv[2])) << endl;

    else
      cout << endl << "V" << endl;
    // Any other operator
  }
}

Comment: This is clearly C++ code. Don't use the C tag, that's a different language.
Comment: Please don't spam the tags, this question has nothing to do with `c`
Answer: atof will stop when it finds characters that cannot be part of the floating point number, and this includes an extra '.'. Unfortunately it does not tell you this happened.
Smarter conversion functions like  std::stof or strtof will notify you if the entire string was not consumed when parsing.
Example:
size_t end;
float val = std::stof(argv[1], &end);
if (end != strlen(argv[1]))
{
    cout << "Bad input: " << argv[1] << "\n";
    return -1;
}

will return from main and exit the program if the entire argument is not consumed when parsing or throw an exception if the number was out of range or  no number could be parsed, ending the program if uncaught.
char * endp;
errno = 0;
float val = strtof(argv[1], &endp);
if (*endp != '\0' || errno = ERANGE)
{
    cout << "Bad input: " << argv[1] << "\n";
    return -1;
}

will return from main and exit the program if the entire argument is not consumed when parsing or the number was out of range. I personally prefer this option because I don't like throwing exceptions over user input. Users getting the input wrong is not exceptional enough to be worth an exception.
If your compiler is up to date, std::from_chars can be extremely helpful. The linked documentation provides excellent examples of its usage.
Answer: One way for checking the validity of a string is to use regular expressions, for example, you can use this.
You can write something like this to extract your operands:
float op1, op2;
std::string p1 = argv[1];
std::string p2 = argv[2];
std::regex pattern("[+-]?([0-9]*[.])?[0-9]+");

if (std::regex_match(p1, pattern) &&
    std::regex_match(p2, pattern)) {
  op1 = atof(argv[1]);
  op2 = atof(argv[2]);
  // ...
} else {
  cout << "Error!" << std::endl;
}

Alternatively, you could use the return value of atof to check if an error happened:

Return value
Floating point value corresponding to the contents of str
on success. If the converted value falls out of range of corresponding
return type, range error occurs and HUGE_VAL, HUGE_VALF or HUGE_VALL
is returned. If no conversion can be performed, 0 is returned and
*str_end is set to str.


There is a group made of 25 people made of 10 men and 15 women....

Question: There is a group made of $25$ people made of $10$ men and $15$ women. How many
committees of $2$ men and $3$ women ($5$ people total) can be chosen from this
group?
I know you are supposed to use some kind of $(^n_k)$ type calculation but this seems so trivial... wouldn't you just have $5$ committees ? So wouldn't there be $2^5*3^5 = 7776$
Comment: No answer is not $7776$
Answer: From 10 men, they choose 2, so that's exactly $\binom{10}{2}$ and from 15 women, they choose 3, so that's exactly $\binom{15}{3}$ possibilities. You can multiply them for the final answer(they are independent events).
The final answer is $45 \cdot 455$.
Comment: Ohhh they are independent. so $\frac{15!}{(12!*3!)} * \frac{10!}{(8!*2!)}$
Comment: Yeah, that is the correct formula
Comment: You can obtain the binomial coefficient $\binom{n}{k}$ by typing \binom{n}{k} between dollar signs.
Comment: Except the curly braces around n and k are not needed if they are only a single character like the number 5.  So if you wanted 10 choose 5 displayed for example, you would put the curly braces around the 10 but they are not needed around the 5.  So for example, \binom {10} 5 between dollar signs.  You could do \binom {10} {5} but it wastes characters and if your comment is very long like over the limit or close to it, these few characters can make a significant difference.
Comment: You can also just do (^n_k) to get $(^n_k)$ less typing ;)
Answer: $5$ because there are only $5$ pair of men available and $5$ triples of women available.
Comment: I think that is not correct, since one pair is different from the other if at least one member is other.
Comment: The question asked is not how many different committees, it is how many committees.  Bad wording if you meant something else.  One "missing" word changes my answer.
Comment: I don't know, maybe the one who asked it knows what is the correct wording, I understood it in an other way.
Comment: No, Atvin is correct, the wording is correct. See David I thought what you thought at first, but I think it is implying what Atvin has said
Comment: The task can be asked in this way too: In how many ways you can choose $2$ from $10$, and $3$ from $15$? And that is exactly the combination without repetition.
Comment: As worded, my answer of 5 is correct.  The person who asked the question didn't say how many different committees (with replacement) so I did not assume that and answered as worded.  For example, after you select committee # 1, there are only 20 people left to choose from, otherwise you are counting the same people multiple times in multiple committees.
Comment: "How many committees of 2 men and 3 women (5 people total) can be chosen from this group?" I think is implying how many different combinations...If it isn't then you are most definitely correct but that is how my teacher worded it so I guess I'll have to ask him. I'm almost certain he wouldn't give us something so trivial though, but who knows. Thanks anyways for the help David
Comment: Tell your teacher if he meant different possible committees that he has to state that, otherwise the trivial answer of 5 is correct.
Comment: I will do that for sure.
Comment: If he was my teacher I would answer 5 and if he marked it wrong I would complain.  If he still didn't give me full credit then I would escalate it to a higher authority to expose his possible incompetence in properly wording questions.  Then maybe he will think twice about the next time he asks a similar type question.  Too many people (even on this site) do not word questions properly/clearly, thus leaving the "door open" for multiple interpretations, each of which might be argued as "correct" as was the case here.  Without clarification, multiple interpretations are possible and likely.
Comment: So what did your teacher say about the questionable wording?  Just because the question has the word chosen in it doesn't mean you automatically use something like $\binom {10} 2$ * $\binom {15} 3$.
Comment: He paused for about a good 10 seconds, then looked at the way I did it (not the trivial way) and said I did it correctly. So I just said well hell with it, and turned it in. I think you are correct that he worded it incorrectly but he is foreign so maybe he didn't realize it.
Comment: It is not that he worded it incorrectly, he worded it in a way that is open for multiple interpretations so it is ambiguous.  That alone opens up room for multiple "correct" answers if someone argues that the question was ambiguous (which it is).  Ask him after you choose the first committee of 5, there are only 20 people remaining to chose from.  Where does it say in his question that the 5 people already chosen can go back into the "pool" of possible choices?  That is where the problem with the wording comes in.
Comment: Also he didn't ask for different committees so if the chosen people can go back into the pool, I can keep choosing until the end of time and get way more than $20,000$ or so choices.  Even if he did say different he would have to define what he means by that such as if they all had letters assigned to them from A thru Y ($25$ of them), how many choices are possible such that each committee of $5$ chosen has a unique combination of $5$ letters vs. every other chosen committee of $5$.  He would also have to state if order is important or not such as is ABCDE considered different than ACEBD.


Major Mediant of F Major Scale

Question: I'm writing a solo over a progression in F Major. However, the progression uses a major mediant instead of the usual minor. Therefore, my progression in F major is IV-III-vi-ii-I (Bbmaj-Amaj-Dmin-Gmin-Fmaj). Currently, I'm only soloing using the F Major scale and would like to expand upon that. I'm looking for scale suggestions and further musical theory information about what I'm doing where I am making the mediant chord of a major scale major instead of minor.
Comment: Duplicate of [Why the chord on the third degree is major in this progression?](https://music.stackexchange.com/questions/34479/why-the-chord-on-the-third-degree-is-major-in-this-progression). It's nearly an exact dupe. [Check this one out, too.](https://music.stackexchange.com/q/61694/45266)
Comment: I think you meant 'mediant' in the title not 'submediant?'
Answer: Bbmaj-Amaj-Dmin-Gmin-Fmaj
Instead of IV-III-vi-ii-I
You can write that with secondary dominants as...
IV-[V/vi-vi]-ii-I
...the meaning of that is to say Amaj is the dominant of Dmin. Temporarily that moment is like being in D minor. Actually, you can extend it and say all of the chords are from D minor! But, probably in practical terms you have a shift back and forth from F major to D minor.
You can try switching between F major and D minor for the solo.
The D harmonic minor scale will technically fit all the chords. It's the same collection of notes as F major with one change: the C becomes C#. (Of course the scale tonic changes from F to D.) Make that one change to use C# around the Amaj-Dmin part and it should make the scale fit the chords.
If you aren't familiar with minor key harmony, keep in mind there is a big difference between the 'natural minor' scale and proper minor key harmony. You use of the Amaj chord makes the difference and gives this progression the flavor of minor key harmony.
Answer: The III (a iii Major) is the V of the relative minor, in this case Dmin.  Though if such a modulation were present (i.e. strong) you might use the III7 chord.  But the point is that the major third of the III chord is the leading tone to the vi.  You could play D harmonic or melodic minor.  Don't worry it won't sound too Yngwie-ish, jazz players do this.  Really it all depends on what feel you are going for.

Major Mediant of F Major Scale


Generation of a group with order of the product of primes

Question: Suppose that the order of a group $G$ is of the form $|G| = pqr$ where $p$, $q$, $r$ are primes, not necessarily distinct. Prove that $G$ can be generated by at most three elements of $G$.
One proposition from Lagrange's theorem that i thought could be used to apply this is:
Suppose that the order of the group G is a prime number. Thenonly has {$e$} and $G$ as subgroups, in particular $G = \langle g \rangle$ for any $g \neq e$ in $g$ is cyclic.
However this is only for when the order is a prime, which $pqr$ is not, So I'm kind of lost on how to show this is true.
Comment: Do you mean that there exists a set with no more than three elements that generates $G$?
Comment: @ajotatxe This is a past exam paper question, that i'm trying to wrap my head around, I just copied it word for word
Comment: Looks like you are not the only one working with this past exam: https://math.stackexchange.com/questions/3241897/generators-of-a-group-with-prime-product-order
Comment: @RobinCarlier Yeah I've seen a few but with no success, it's an odd question
Comment: Do you have Cauchy's theorem in your toolbox? If $p$ is a prime number dividing $|G|$, then there exist an element of order $p$ in $G$.
Comment: I didn't know about that theorem, the closest one i have similar is: If $d$ is the power of a prime that divides |$G$| then there is a subgroup order $d$, but i doubt that is that helpful
Comment: Another suggestive (of at least one method of proof) way of stating this is that a group which cannot be generated by fewer than four elements has order the product of at least four primes (not necessarily distinct). Here we can replace four by any positive integer.
Answer: Consider a minimal set of generators: $\{a, b ,c , d \dots \}$
If $a$ is the identity, we discard it and the set is not minimal. If it generates the whole group we are done. The order of the subgroup generated by $a$ is $p, q, r, pq, pr \text{ or } qr$. It has order divisible by the product of at least one of the primes. Since they are primes, these are the only possible choices (Lagrange). Some of them may be equal.
Note that phrase "divisible by the product of at least one of the primes" - does that give you a clue as to how you might proceed?

Now $a$ and $b$ together generate a subgoup. It is not the whole group (else we have a two generator set). If it has the same order as the group generated by $a$ it is the same subgroup and we discard $b$ from the set. Otherwise the subgroup generated by $a$ and $b$ is larger than the subgroup generated by $a$, and contains it, and it must therefore have order divisible by at least two of the primes (and hence exactly two, since three is excluded).

You should be able to conclude and generalise from there.
Answer:
Let $a \not = e$ be one generator. Then let $n_a$ be the order of $a$.
If $a$ generates the whole of $G$ then we are done. If $a$ does not generate the whole of $G$, let $b$ be any element of $G$ not generated by $a$. Then let $n_{ab}$ be the order of the group generated by $a,b$.
If $a$ and $b$ together generate the whole of $G$ then we are done. If $a$ and $b$ together do not generate the whole of $G$, let $c$ be any element of $G$ not generated by $a$ and $b$. Then let $n_{abc}$ be the order of the group generated by $a,b,c$ together.

Note that [assuming that $a$ and $b$ together do not generate the whole of $G$] the string of inequalities (A) $1 < n_a < n_{ab} < n_{abc} \le pqr$ hold. Furthermore, note that (B) $n_a|n_{ab}|n_{abc}|pqr$. As $p,q,r$ are all primes the only possibility for both (A) and (B) to hold simultaneously is if $n_{abc} = pqr$ [make sure you see this] and therefore $a,b,c$ together generate $G$.
So not only does a set of at most 3 elements generate $G$ but algorithmically it is also quite easy to find such a set.

What if $|G| = \prod_{i=1}^k p^{e_i}_i$? Can you give an upper bound for the number of generators in this case?


Fast search of doubled numbers in array

Question: I'm trying to search doubled occurrences of numbers in a list. But for big arrays (like >1000 items this taking quite a long time). Is there any method for speeding it up?
lis = [1, 6, 9, 3, 27, 50, 12, 2]

def isAnyThere (lis):
    for m in lis:
        for m in lis:
            if m == 2 * k:
                return m
    return 0

Comment: What do you mean by doubled  occurrence ? is that mean that the 2 times of k is there in the list or not ?
Comment: you can check NumPy librabry which is fast to work on arrays for python
Answer: Python's set type provides O(1) lookup and insert performance unless the set becomes spectacularly large. The following algorithm:

insert the elements of the list into a set
for each even element x of the list check to see if x // 2 is in the set

takes 2*n steps for a list of length n.
from typing import Sequence

def find_doubled(seq: Sequence[int]) -> Sequence[tuple[int, int]]:
    return [(x, x // 2) for x in seq if x % 2 == 0 and x // 2 in set(seq)]

if __name__ == '__main__':
    l = find_doubled([1, 6, 9, 3, 27, 50, 12, 2])
    print(l)
    # prints [(6, 3), (12, 6), (2, 1)]

Duplicates are dealt with by ignoring them.
Answer: It wasn't super clear from the question but I think you want to check if there are any pairs of numbers in the list such that one is double the other?
If you sort the list first, you would only need to check each pair of elements once so that immediately halves the number of comparisons.
Also work on the set of list elements to remove duplicated values in large lists.
def isAnyThere (lis):
    lis = sorted(set(lis))
    for i in range(len(lis)):
        for j in range(i+1, len(lis)):
            if lis[j] == 2*lis[i]:
                return lis[j]
    else:
        return 0

Fast search of doubled numbers in array


Why t distribution in confidence level for the mean?

Question: This is a basic question, but when I was asked about it I only could give a weak answer. That's why I am asking it here.
If we want to calculate the confidence level for the mean there is the formula:
$(\bar{x}-t_{n-1}s_{\bar{x}},\bar{x}+t_{n-1}s_{\bar{x}})$
I know that the t distribution comes in, when the variance is unkown and has to be estimated. So the assumption that sample means are normally distributed is violated. The sample means follow the t distribution. But why? For me there is a point missing or at least it is not intuitive to me.
Answer: This explanation consists of two parts.

The distribution of a t-statistic under the assumption of normality
The construction of confidence intervals using pivotal quantities

The distribution of a t-statistic under the assumption of normality
Consider $X_1, X_2, ..., X_n\stackrel{\text{iid}}{\sim}\text{N}(\mu,\sigma^2)$
Then $$Q=\frac{\bar{x}-\mu}{s_\bar{x}} = \frac{\bar{x}-\mu}{s/\sqrt{n}}$$ has a t-distribution with $n-1$ degrees of freedom.
I presume you are familiar with this part. (If not, we might need to explore that in another question.)
The construction of confidence intervals using pivotal quantities
A pivotal quantity is a function of the data and parameter(s) whose distribution doesn't depend on the parameter(s)
Because of that, we can write down a probability statement relating to an interval for the pivotal quantity.
So if we can write down a pivotal quantity involving the data and the parameter $\mu$ in the above iid normal situation, then we can write an interval for that pivotal quantity. From that we can back out an interval for the parameter.
In this case, the t-statistic above ($Q$) is a pivotal quantity; it is a function of the parameter $\mu$ and the data and its distribution is $t_{n-1}$, which doesn't depend on $\mu$. If $t_{1-\alpha/2}$ is the ${1-\alpha/2}$ quantile of a t-distribution (with $n-1$ d.f. being understood as given), then we can write $$P(-t_{1-\alpha/2}<Q<t_{1-\alpha/2})=1-\alpha$$
From there we can write $\frac{\bar{x}-\mu}{s_\bar{x}}$ for $Q$ and manipulate the probability statement above to obtain an expression giving an interval for $\mu$ with the desired coverage, which is the interval you stated.


How do I migrate user passwords?

Question: I have refactored an old Drupal 6 site to Drupal 8 and my only problem is, i migrated the users but the password is incorrect. i know that the password in Drupal 6 is a MD5 hash, but i cannot find a solution to convert this password, that Drupal 8 can read it.
Is there any solution for the password migration yet? can i give the MD5 hash a prefix inside of the database to make it readable?
Answer: Security wise it would make sense to import them in Drupal and then use the Mass Password Reset module to reset all passwords.
Answer: User and user password migration is part of the Migrate and Migrate Drupal modules that come with Drupal 8 and that can easily be accessed using the Migration Drupal UI.
One word of warning though, from the guide on Upgrading using the migration user interface:

Due to password encryption, user accounts take particularly long to
  import.
Comment: The UI is actually just the UI, it's the migrations themself that deal with this. Basically, it is the same logic as the Drupal 7 upgrade path, the md5 hashes are hashed again using the new API, and when such a user tries to log in, we first hash the password with md5(), and then again, compare it, if it matches, we generate a new hash that doesn't rely on md5 and persist that.
Answer: See Migrating MD5 hashed passwords
There is also a D6 migration example in /core/modules/user/migration_templates/d6_user.yml:
id: d6_user
label: User accounts
migration_tags:
  - Drupal 6
source:
  plugin: d6_user
process:
  ...
  pass: pass
  ...
...
destination:
  plugin: entity:user
  md5_passwords: true
...

Key solution here to correctly migrate the passwords is to use the md5_passwords: true option for the destination user entity. So make sure you include that option in your user migration config.

How do I migrate user passwords?


Split HTML into separate files based on a string

Question: I have a Joomla article which is long, but I need to separate it into individual articles. First stage would be to separate the HTML code into separate files.
Any way to do this, based on a string (for example: Date in the HTML code)?
Comment: You could do this with PHP. The approach would be somehting like this: Create a loop with a regular expression that finds the needle in the haystack and puts everything until the needle in a variable. Remove everything until that needle from the haystack and write the variable to a file. Name the file 'untill_needle_[iteration_number].html'. When your loop is finished, you will have many files.
Answer: To separate into individual small articles you can use PageBreak. You can read this article
Splitting a long Article into multiple linked pages
https://docs.joomla.org/Splitting_a_long_Article_into_multiple_linked_pages
You can also read a nice article on customising the pagebreak plugin, so you can create your own style:
https://www.ostraining.com/blog/joomla/page-break-viral/
If thats not enough than there is a free plugin which can customise the Pagebreak the way you want
http://extensions.joomla.org/extension/pagebreakmyjspace


How fast should I push myself with Hanon

Question: I'm currently playing Hanon (1-20) at the target tempo as suggested by the book (108).
My question is if there any reason to push myself playing it faster.
I can certainly raise the tempo if I put some effort to it, but I'm questioning the benefit of doing so. Should I push the temp with other stuff instead (Arpeggios / Scales) ?
Answer: Go as fast as you like IF you're sure your playing is clean and accurate.  The technique will transfer to scales etc.
Answer: To determine if you have reasons to practice your Hanon exercises faster than the recommended tempo markings, it is helpful to consider your individual goals, and which aspects of your skills that you're trying to improve during a given practice session. Depending on your skill level, you might find that you could even double the recommended tempo, although that could introduce some bad habits or cause injury if you're not sufficiently skilled, and it may not be worth the risk to push yourself too far.
Some potential reasons for edging the tempo higher on your Hanon practice regimen might include:

To find your physical and mental limits (which will likely change daily) of clean and even technique to determine where improvement is needed
Mental training, to improve how the mind can "follow" fast passages, tracking to a metronome, in coordination with what is happening physically
Fine-tuning the strength of the muscles involved
Providing a boost of motivation, in that pushing your limits can result in finding out you can handle more than you thought. That can build the momentum to keep you advancing (but again, be careful not to push so far as to hurt yourself, or your style and technique.)

If you choose to go faster, just be mindful about how and why you're doing it.
The other part of your question was whether you should instead push the tempo with scales and arpeggios, and I believe that the same principles apply. That being said, about 25 years ago, I was in the audience where Ellis Marsalis, Jr. was giving an amazing jazz concert, and he answered some questions afterwards. One person asked about whether he spent a lot of time practicing scales and arpeggios, and Ellis alluded that he got all the practice of those elements that he needed just by playing the music.  I think that's a valuable guiding principle.
Answer: As long as your playing is completely clean I'd keep on going until you reach your limit. Exercises like Hanon will help your overall dexterity especially in classical pieces. But the main thing is to make sure that you are playing extremely and completely clean. No overlapping notes, no wrong notes at all. Otherwise this will not help at all.
Answer: Primarily, you should follow what Laurence said, which is to play clean and accurately.

To answer your question, I think that it is of course helpful to push the tempo a bit faster as some songs require it. For example, Beethoven's Moonlight Sonata - 3rd movement.

The benefit of pushing the tempo is that you will be able to play other pieces much better, as most pieces incoporate scales/appegios, so playing it faster will make playing scales fast much more comfortable as you're more familiar with it. Besides, there's only a certain number of scales on the piano, it's not like chess where there are an infinite number of positions. You'll definitely come familiar scales that (by that time) you'll have managed to play it at a high speed.

Tl; Dr
Try to push the tempo if you're playing clean and accurately at the current tempo you're at.


Correct batch effects using R limma package

Question: I know that batch effects are variations in the data that are not biological, but from outside factors, like who took the samples, when was it taken (AM or PM), and so on.
My situation is the following: I'm gathering RNA-seq transcriptomic data about people who were treated with a certain cancer drug, but before they were treated. So I have the labeling if they responded or not, and I have their RNA-seq data before they were treated. After gathering the data, I conduct a cell type enrichement analysis for each dataset individually, to see if the people who responde and people who do not responde have different tumor cellular profile. The data is from different cancer types, different datasets, it's heterogenous. I have datasets of melanoma, lung cancer, renal cell carcinoma, gastro, and more cancer types.
After doing the cell type enrichement analysis for each dataset separatly, I combined all the scores into one comprehensive dataframe, called scores, and do batch effect correction with this code:
scores.batch = limma::removeBatchEffect(scores, batch = scores$cancertype)

what does this do exactly, and do you think I should also correct for data set?
This is the scores[1:15,1:15]:
structure(c(0, 0.0679901419400528, 0.0400496750811988, 0.0482367326065044,
0, 0.0311229574337865, 0, 0.230766724561802, 0.0130401911422858,
0.0340701040525204, 0.170909076828328, 0.01773848926898, 0.0644291992845225,
0, 0.00716656856094877, 0, 0.0256702878665956, 0.146618059188406,
0, 0, 0, 0, 0, 0.0137608540969118, 0, 0, 0.0100999977354592,
0, 0.014951880422075, 0, 0, 0.157670478795813, 0.626964572395372,
0, 0, 0, 0, 0.267217181299341, 0.0208607997305519, 0.0317512643538273,
0.216134089444667, 0, 0.133133976872855, 0.0509764894291432,
0, 0.00643390666442725, 0.0198563471760109, 0.0269546957969239,
0.00839612466157775, 0, 0, 0, 0.135792129150605, 0.0306791807449823,
0.0245322813632248, 0.0581232794898189, 0, 0.0113306571628598,
0.0736402473717223, 0, 0.0562788278940215, 0.0197365476488731,
0.510288824627519, 0, 0, 0, 0, 0, 0.00808293565225856, 0, 0.0120576870198705,
0, 0.0756065852977926, 0.033804095025975, 0, 0, 0, 0.0883095578108505,
0, 0, 0, 0, 0, 0.0152483703858198, 0, 0, 0, 0, 0.0180766544827361,
0, 0, 0.0453699522236652, 0.0862072776187677, 0.0135920854235664,
0, 0.0121970616856621, 0, 0.135535206654987, 0.0101591049475456,
0.0121784241136469, 0.128072268753123, 0.0210894284621647, 0.0194646121245035,
0.0540381655396803, 0, 0.18079139586031, 0.189254463003303, 0.029888048321481,
0.0541812778427424, 0, 0, 0, 0.215022381991572, 0.00969491427150976,
0.0223406673571106, 0.144924194478157, 0.0921982845361599, 0.0320096514933575,
0.0961220443664323, 0.0126588948335048, 0, 0.022785243112039,
0.0893620137600288, 0, 0, 0, 0, 0.0627768984349815, 0.0216749854839462,
0.0124888431122003, 0.0078666361898362, 0.0224340322794678, 0.00918758007722465,
0, 0, 0.0167099491258054, 0.0149569599862252, 0.225776419265983,
0.0296939571626858, 0, 0, 0, 0.0267052090394147, 0.0368229910899846,
0, 0, 0.0244839860392415, 0, 0.0125436970237014, 0.0372759973763743,
0.00618735419664188, 0.0710179399375031, 0.0723424649726667,
0, 0, 0, 0, 0, 0.0337322795006411, 0.0375867797836129, 0.0572019757148853,
0.0237748490504673, 0.0167169014275168, 0.0111345646016615, 0,
0, 0.046688139968337, 0.0351708018702931, 0, 0, 0, 0, 0.0591350872295602,
0.0219554939925585, 0, 0.0124552946680113, 0, 0.0313457001492319,
0.0318126127338407, 0, 0.0238070594883507, 0.0887393545717189,
0.0836483327726664, 0.00782113454476318, 0, 0, 0, 0.120060643116735,
0.0393210466824994, 0.0508059149670181, 0.10179828698662, 0,
0.0478576770902387, 0.0344903509973101, 0, 0.442372249995689,
0.0312811844417772, 0, 0.00563099608437556, 0, 0, 0, 0.0926041796109331,
0, 0, 0.0149318321524897, 0.0125028189664699, 0.0703454111710074,
0.26414814527198, 0.0187728466245726, 0, 0, 0, 0, 0, 0, 0, 0.133354279086491,
0.0211140306442408, 0.0174288870187779, 0, 0.0118475583427554,
0.0403579720283282, 0.0222583264159109, 0.00644966434608166), .Dim = c(15L,
15L), .Dimnames = list(c("Adipocytes", "B-cells", "Basophils",
"CD4+ memory T-cells", "CD4+ naive T-cells", "CD4+ T-cells",
"CD4+ Tcm", "CD4+ Tem", "CD8+ naive T-cells", "CD8+ T-cells",
"CD8+ Tcm", "Class-switched memory B-cells", "DC", "Endothelial cells",
"Eosinophils"), c("Pt1", "Pt10", "Pt103", "Pt106", "Pt11", "Pt17",
"Pt2", "Pt24", "Pt26", "Pt27", "Pt28", "Pt29", "Pt31", "Pt36",
"Pt37")))

Answer: From the limma help page for removeBatchEffect():

The function (in effect) fits a linear model to the data, including both batches and regular treatments, then removes the component due to the batch effects.

It expects data "containing log-expression values for a series of samples."
Batch-effect corrections with this function are done at the early stage of log-expression values. Your code indicates that you are trying to apply a batch-effect correction to the downstream results of your cell-type enrichment analysis, which presumably represent the fraction of each cell type estimated from the RNAseq data. That's not what the function is designed to do.
If you have multiple data sets for the same cancer type, then it might make sense to do a batch correction for data sets within that cancer type. But do that on the original log-expression values, not after the cell type enrichement analysis.
Comment: And by log-expression values you mean the transcriptomic data? The point is to make it general, not cancer specific.  So for example I want to see t-SNE for those scores without the effect of cancer type.
Comment: @L0987 yes, the function works with original transcriptomic data expressed on the log scale. You might be able to use its general approach to remove "batch effects" due to differences in expression among cancer types. But you are probably better off doing that with your own modeling rather than depend on a function, designed for a different purpose, whose inner workings you haven't yet fully investigated. Look at the code and see if it does what you need.


Using Python to find matching arrays and combine two arrays into one

Question: I would like to use Python to find the matching arrays of x[0] in set1 and x[0] in set2, for example such as [4012642, 0.10869565] in set 1 and [4012642, 2] in set 2. Then I would like to combine them into 1 array and divide set1[1] by set2[1], So it would become [4012642, (2/0.10869565)] or [4012642, 18.40]. I want to do this for each variable in set1 and set2 and put into a new array. Any help is greatly appreciated, sorry I may have worded this very confusingly.
set1 = [[4012640, 0.014925373], [4012642, 0.10869565], [4012644, 0.40298506], [4012646, 0.04477612], [4012616, 0.6264330499999999], [4012618, 1.128477924], [4012620, 0], [4012622, 0.12820514], [4012624, 0.16417910000000002], [4013328, 0.16666667], [4012626, 0.149253743], [4012658, 0], [4012628, 0.41791046], [4012630, 0.28493894000000003], [4012632, 1.999999953], [4012634, 0.08955224], [4012636, 0], [4012638, 0]]

set2 = [[4012640, 2], [4012642, 2], [4012644, 2], [4012646, 1], [4012616, 5], [4012618, 8], [4012620, 1], [4012622, 2], [4012624, 5], [4013328, 2], [4012626, 6], [4012658, 1], [4012628, 4], [4012630, 8], [4012632, 4], [4012634, 4], [4012636, 1], [4012638, 1]]

Comment: What have you tried so far? What do you consider to be "matching" arrays? In your example, it looks like they are "matching" based on the first element. I am not sure if this is what you intended or not though.
Comment: These are lists, not arrays. In Python, arrays are in numpy.
Comment: Convert `set1` to a dictionary. Then loop through `set2`, find the dictionary element whose key is the first element, and divide its value by the second element.
Answer: Personally, I preferr to use dataframe to handle this kind 'join' question
# build two dataframe from set1 and set2
df1=pd.DataFrame(columns=['x0','x1'])
df1['x0']=[x[0] for x in set1]
df1['x1']=[x[1] for x in set1]

df2=pd.DataFrame(columns=['x0','x2'])
df2['x0']=[x[0] for x in set2]
df2['x2']=[x[1] for x in set2]

Then call merge method in pandas to match two dataframe by column 'x0'
# Merge two dataframe on 'x0'
df=pd.merge(df1,df2,on=['x0'],how='left')

# Calculate a new columnn by 'x2'/'x1'
df['values']=df['x2']/df['x1']

Results:
    x0  x1  x2  values
0   4012640 0.014925    2   134.000001
1   4012642 0.108696    2   18.400000


Random Forest for regression--binary response

Question: Kind of a broad question here. But is it okay/possible in R to use a random forest for regression when the response variable is a binary outcome? Essentially what I'm looking for is a probability of something happening. Below is the code I've been using it run it and the warning message. Or am I better off using this in classification mode. My end goal is to predict the probability of something happening, not necessarily predict what "classification" it will be, 1 or 0.
m1RF <- randomForest(EOI_140 ~ .,
                     data = dfTRN,
                     importance = TRUE,
                     ntree = 2000)
Warning message:
In randomForest.default(m, y, ...) :
  The response has five or fewer unique values.  Are you sure you want to do regression?

I apologize if this question is in the wrong place.
Comment: @ArtemSokolov: agreed it's a duplicate, although "Can RF regression be used for binary response var?" is more fundamental than that wording, and they don't share any common words, so non-obvious :)
Comment: @ArtemSokolov: oh and also, just because RF can predict class probabilities, we might well want to modify that raw number, depending on the evaluation function (we might take log1p, sigmoid, square, square-root, etc.)
Answer: Try this with "prob" in predict(). It is done on mtcars predict vs column
library(randomForest)
mtcars$vs <- as.factor(mtcars$vs)
classifier <- randomForest( formula = vs~hp+drat, data=mtcars)
predict(classifier, type="prob")

I dont split to train and test sample but in reality you have to do this :)
You have to set factor to response variable in other case it will try to do Random Forest Regression :)
Answer: Let's start with something simpler, a decision tree, since random forests are forests of independent decision trees that are averaged. Decision tree is build by splitting your data into subsets conditionally on the features used. The splits are done by choosing the features, one at a time, and then choosing a split based on the values of the feature. In both cases we make our choices based on some loss function that is minimized. In regression case we minimize the variance, what is equivalent to minimizing squared loss. In classification case, we use entropy, or Gini impurity as a criterion. In the end your data gets packed into a number of subgroups and to make predictions, in classification case you predict the most frequent value within the subgroup, and in regression case you predict the mean of the subgroup. Obviously, if you calculate the mean of the binary values, you'd get the fraction, i.e. empirical probability. So basically in both cases you can calculate probabilities the same way, this problem reduces only to the criteria that is used for building the tree: mean squared error vs entropy (or Gini impurity). If you choose mean squared error, then you'd be minimizing the same loss as linear regression, while choosing entropy, leads to minimizing the same loss function as logistic regression.


Why do goalkeepers wear highly-visible strips?

Question: I understand the need to have a strip that differentiates goalkeepers from outfield players, but success in top-flight sport often depends on taking advantage of fine margins.
Surely being highly-visible gives an advantage to opposing players as they can see where the 'keeper is and aim shots / take up a position accordingly - even if the 'keeper is not in direct line of sight, there's a player's postional awareness and peripheral vision to consider.
Has there been any research comparing gaudy and muted colours?
Comment: Being highly visible also gives an advantage to the goalkeeper's teammates. If you're defending against a corner kick, for example, you don't want to accidentally barge into your own goalie because you didn't see them.
Comment: @F1Krazy Yep, I thought of including something along those lines in my post but couldn't seem to properly articulate the defence's cost / benefit. Thanks for the example.
Answer: The laws around the player equipment say this for clothing colours

Colours

The two teams must wear colours that distinguish them from each other and the match officials
Each goalkeeper must wear colours that are distinguishable from the other players and the match officials
If the two goalkeepers' shirts are the same colour and neither has another shirt, the referee allows the match to be played.

My reading of that is that a team cant dictate what their keeper wears. So when a team is designing their goalkeeper kit they'll cross out all the colours that clash with their home and away kit, cross out all the other teams colours, take into consideration the referee kits. You can see why you're left with the gaudier end of the spectrum.


Can I destructure a property into the same property of an object literal?

Question: This is at the Node.js REPL:
> action = {type: 'build', index: 42 }
{ type: 'build', index: 42 }
> { name: 99, {index : action} }
{ index: { type: 'build', index: 42 } }

Where did name: 99 go?
I was hoping for:  { name: 99, index: 42 }.  Obviously my attempt is wrong.
One way, without destructuring would be:
{ name: 99, index: action.index }

But, how do I get what I was hoping for { name: 99, index: 42 } using some kind of destructing...or more specifically, with economical syntax, and without having to mention index twice?
Comment: @skyboyer it's actually valid syntax. But it is a [code block](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/block) with a [label](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label) `name: 99` followed by a [comma operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator) and the object literal `{index : action}`.
Comment: how do you execute that? `{ name: 99, {index : action} }` is invalid syntax since there is key missing for `{index: action}` value
Comment: There is no destructuring here?
Comment: And to actually answer your question: nope. That's not yet possible.
Comment: @skyboyer no, that's a block statement, a label and a comma operator :)
Comment: Sorry if I have my terminology wrong regarding "destructuring".  If there's a more appropriate word for what I'm trying to do, please enlighten me.  Thanks, everyone, for breaking it down.  And wow, this was really mystifying that I stumbled upon that label + comma + literal oddity.  Makes sense now.
Comment: @JonasWilms, if you want to write a "nope, that's not yet possible" answer, I'd mark it as such.
Answer: No, it is not possible. The destructuring syntax evaluates to the value being destructured, so ({ a } = b) evaluates to b. Thus, there is no way to use destructuring inside object literals. Also there is yet no other way to do that.
A language proposal that would allow the syntax to be
 { action.index }

seems to be far away from being standardized.

As a sidenote: Your attempt did not work, cause it actually builds up only one object. The outer {} are interpreted as a block statement, the name: as a label, the following , as a comma operator, thus the following {} are in expression context and are interpreted as an object literal:
{ // block
  name: // label
  (99, {index : action}) // comma operator
}


Which php functions act directly upon the variable? (like sort() )

Question: Fer instance:
$fruits = array("lemon", "orange", "banana", "apple");
$sort = sort($fruits);
var_export($sort);
var_export($fruits);

returns
true
array ( 0 => 'apple', 1 => 'banana', 2 => 'lemon', 3 => 'orange', )

The sort() returns only a bool, if it worked or not.  The function works on the variable, itself.
Whereas:
$s = 'thestring';
$trim = trim($s,'ing');
var_export($trim);
var_export($s);

returns:
'thestr'
'thestring'

So, what gives?  Is there a rhyme or reason for this? Which functions act directly upon the variable?
edit:
'pass by reference', I see.  Thusly:
function mytrimmer(&$string){
    $string = trim($string,'ing');
    return $string;
}

$s = 'thestring';
var_export(mytrimmer($s));
var_export($s);

returns
'thestr'
'thestr'

Comment: Any function that is "pass by reference", depicted in the manual description as `&$varName`
Comment: It's called [`pass by reference`](http://php.net/manual/en/language.references.pass.php) And you see it on the signature of the function if they have an ampersand(&) in front: http://php.net/manual/en/function.sort.php -> See the: **&** `array`
Answer: In addition to sort(), rsort() and shuffle() also act on the array variable supplied to the function.
Comment: Axly, this does answer the question. At least it provides a partial answer, I just wish there was a reference to some list of php funcs that act on a var by reference. The main problem is the question sucked.  I'm not sure what to do about that, at this point.


AttributeError: module 'tensorflow.python.keras.engine.training' has no attribute '_disallow_inside_tf_function'

Question: I am trying to develop a chatbot with rasa, and when I run rasa init to train the bot I have this error. I have TensorFlow 2.3.2, Keras 2.3.1, python 3.8.5.
I don't know if there is a compatibility problem. I am trying also to use a virtual environment.
AttributeError: module 'tensorflow.python.keras.engine.training' has no attribute '_disallow_inside_tf_function'

Comment: Please provide some snap shots..
Answer: which rasa version are you using? It would also be helpful if you could provide the full stacktrace.
I also had a look at the Rasa poetry.lock file, the latest rasa version should work with tensorflow 2.3.2, python 3.8.5, keras-preprocessing should be 1.1.2. If you want to use rasa with all its dependencies, you could try pip3 install rasa[full] as stated in the docs.
Please note that if you want to train a model, you should run rasa train command, instead of rasa init.


How to render / preprocess list of entity reference nodes?

Question: I hove a content type that editors can 'attach' related nodes to.
When I 'theme' / 'style' nodes of this content type through view mode everything is basically fine: the related nodes are rendered as teasers and I can style them as I like.
Now I need to wrap the list of related nodes in an extra class e.g. 'related-nodes' according to the output of another field. For example the editor chooses 'round corners' from a list field, then the css class "rounded" should be added to the wrapper of the list of related nodes should.
I am aware I can remove the entity reference field from the display settings and preprocess it through template.php. But then how do I preprocess the list in template.php? So far I just don't know how to actually access / handle it.
In devel tab I do get the array of related items. I could of course loop through that array and re-build node by node thruogh node_load – but since I only want to wrap that loop re-rendering each node feels wrong.  Any suggestions?
Comment: [Fences](https://www.drupal.org/project/fences) may be able to help with that
Comment: Thank you! But I actually need to add classes according to conditions previously read from another field…
Comment: Ah ok - a quite straightforward option would be to implement `hook_node_view()` in a custom module and add a `#prefix` and `#suffix` to the field element (prefix of ``, suffix of ``)
Answer: As per @Clive comment, Fences module may be able to help with that.
A quite straightforward option would be to implement hook_node_view() in a custom module and add a #prefix and #suffix to the field element (prefix of
, suffix of
)


Spring JDBC batch update query without prepared statements

Question: I have a legacy code where I am not allowed to use prepared statements.
Its using Spring JDBC and update query. The requirement is to update 100,000 rows.
I have a Map which has row number and the value that needs to be updated in specific column.
Here is my current code:
<code>            for(String seq: recordIdMap.keySet()){

            Object[] parameters = new Object[2];
            parameters[0] = seq;
            parameters[1] = recordIdMap.get(seq);
//<setting the params in query using manual string replace- earlier query has (1) (2) ... in query . This is not prepared statement>
                getJdbcTemplate().update(query);
        }
</code>
I need to change this to execute as a batch so that after the for loop i can execute it in a single DB hit.
What is the best way to use spring JDBC batch update for this requirement?
Comment: Why are you not allowed to use prepared statements? Running a 100k individual updates will be much slower than running the same prepared statement 100k times. Also, a batch size of 100k seems a bit too much; splitting the total into batches of 500/1000 rows might be a better idea.
Comment: The query is already written by someone else and I am not supposed to update it.
Answer: I would read everything and convert it into a list of object array and then run batchUpdate.
<code>List<Object[]> params = new ArrayList<Object[]>();
for(Entry<String,String> entry : recordIdMap.entrySet())
    params.add(new Object[] {entry.getKey(), entry.getValue()});

getJdbcTemplate().batchUpdate(query, params);
</code>
Hope that helps
Comment: do i need to update the query for this requirement, i don't have access to query string as it is read from external module.
Comment: as long as the query has the '?' place holder it should be fine... eg. update tbContact set firstname = ?, lastname  =?
Comment: Thanks, let me check if i can make it work. Thanks for the help.
Comment: If the query has bind parameters (`?` or `:param` placeholders), then by definition, it's a prepared statement, which OP was not allowed to use.


Strategy for breaking up a vector product

Question: Given is the equality
$$\vec{A}\times\vec{B}=\vec{C}$$ What is the strategy for breaking up the vector product and expressing $\vec{B}$? Given this equality, what does $\vec{B}$ alone equal to?
I know one strategy, say $\vec{A}$ is a constant vector and $\vec{B}$ is the position vector $\vec{x}$:$$\vec{A}\times\vec{x}=\vec{C}$$ Take curl of both sides: $$\nabla\times(\vec{A}\times\vec{x})=\nabla \times \vec{C},$$ then $$2\vec{A}=\nabla \times \vec{C}, $$ or
$$\vec{A}=\frac{1}{2}\left( \nabla \times \vec{C} \right)$$
Do you have a strategy for expressing either A or B when both $\vec{A}$ and $\vec{B}$ are not constant? How do we eliminate $\vec{A}$ form the LHS to express $\vec{B}$.
Answer: Attempted answer:
If $$\vec{A}\times\vec{B}=\vec{C},$$ then $$\vec{B}=-\frac{\vec{A}\times\vec{C}}{|A|^2}+\lambda\vec{A},$$ where $\lambda$ is an arbitrary constant.
Check if true:
$$\vec{A}\times\vec{B}=$$
$$=-\frac{1}{|A|^2}\vec{A}\times(\vec{A}\times\vec{C})+\lambda(\vec{A}\times\vec{A})$$
$$=-\frac{1}{|A|^2}\vec{A}\times(\vec{A}\times\vec{C})$$
$$=-\frac{1}{|A|^2}\left[(\vec{A}\cdot\vec{C})\vec{A}-(\vec{A}\cdot\vec{A})\vec{C} \right]$$
since $\vec{A}\times\vec{B}=\vec{C},$ the vectors A and C are orthogonal, $(\vec{A}\cdot\vec{C})=0$ and we are getting
$$=\vec{C}$$
Comment: Since the cross product is linear in each variable, you're right in asserting that once you have one solution to $A \times X = C$ you can find the others by adding solutions to $A \times X = 0$. Those solutions really are the scalar multiples $\lambda A$ of $A$. But the first term in your answer isn't right. The denominator makes no sense, and $A \times (A \times C)$ isn't necessarily a multiple of $C$.
Comment: I added the derivation
Answer: Short answer to

How do we eliminate $A$   form the LHS to express $B$?

is that you can't.
Geometrically, the cross product $A \times B$ is a vector perpendicular to both $A$ and $B$ whose length is the area of the parallelogram determined by $A$ and $B$. Then it's clear that there are many vectors $X$ for which $A \times B = A \times X$.
Comment: I tried to give an answer, could you comment


For $z \in \mathbb{C}$ s.t. $|z| > 1$, show that $z_n = \frac{z^n}{n}$ diverges to $\infty$.

Question: Let $z \in \mathbb{C}$ s.t. $|z| > 1$.
It is required to show that $z_n = \frac{z^n}{n}$ diverges to $\infty$.
I already tried to show that for $w \in \mathbb{C}$, there is $\epsilon > 0$ s.t. for every $N \in \mathbb{N}$, there is $n \ge N$ s.t. $|z_n - w| \ge \epsilon$, but I couldn't find the requested values.
I also tried that $d(\sigma(z_n), \infty) \to 0$ as $n \to \infty$, where $\sigma: \mathbb{C} \to \mathbb{S}^2$ is the Stereographic projection, but I failed too.
Also is not easy to show $\Re{(z)} \to \infty$ and $\Im{(z)} \to \infty$, since I don't know which is the appropriate form of $z$ one should take.
I also look for some result similar to the Monotone Convergent Sequences, but couldn't fine a similar result for complex numbers, since there is no orden in $\mathbb{C}$.
Any help is appreciated.
Answer: The real sequence $|z_n|=|z|^n/n$ is not bounded if $|z|>1$ so the complex sequence $(z_n)$ diverges to $\infty$.
Comment: @BlueTomato that's correct as pointed out by Yathiraj, unboundness give us divergence only and not divergence to $\infty$
Comment: Yes. Unbounded is not sufficient to tell that the sequence diverges to infinity.
Comment: @donovan The correct way to prove the sequence divergence with this idea is to show that there is a natural $N$ such that for every $n \ge N$, $\frac{|z^n|}{n} > r$, for $r$ an arbitrary real. This condition is stronger than the non-boundness of the sequence. For example $(1,0,2,0,3,0,4,…)$ is not bounded but the limit is not determined. But I really appreciate it sir.
Comment: By this way, it is required to prove that $|z_n|$ is monotone, right?
Comment: it is not sufficient because a monotone positive sequence could converge, it has to be shown that $|z_n| \to \infty$ for $n \to \infty$
Comment: I mean, it should be required to prove that $|z_n|$ is monotone and non-bounded.
Answer: For any real $a>1$, consider the function:
$$f(x) = \frac{a^x}{x}.$$
By L'Hospital's, we can easily see that
$$\lim\limits_{x\to \infty} f(x) = \lim\limits_{x\to \infty} \frac{a^x \log_e a}{1} = \infty.$$
Note that $a> 1$ is required for $\log a>0$. What does this imply? You choose any sequence approaching infinity, say $\{n\}$, then $\{f(a_n)\}$ should also approach infinity.
Answer: Let $c=|z|-1$. Then $c>0$ and by the binomial theorem, $|z_n|=\left|\frac{z^n}{n}\right|=\frac{(1+c)^n}{n}>\frac{\binom{n}{2}c^2}{n}=\frac{(n-1)c^2}{2}$ when $n\geq2$. Therefore $\lim_{n\to\infty}|z_n|=\infty$, i.e., $\lim_{n\to\infty}z_n=\infty$.
Answer: Let $\displaystyle f(z)=\sum_{n=0}^{\infty} \dfrac{1}{z^n}$. Then $f$ is holomorphic for $|z|>1$, being the sum of a geometric series.
Therefore, $f'$ is holomorphic for $|z|>1$ and $\displaystyle f'(z)=-\sum_{n=0}^{\infty} \dfrac{n}{z^{n+1}}$ and so $\displaystyle-zf'(z)=\sum_{n=0}^{\infty} \dfrac{n}{z^{n}}$.
Since the series converges, we have $\displaystyle\lim_{n\to\infty} \dfrac{n}{z^n} =0$, which proves the claim.


System.Net.Http.HttpClient Timeout seems to be ignored

Question: I am using Xamarin.iOS Version: 22.214.171.124 (Indie Edition) and facing a very strange behaviour with timing out requests sent with HttpClient():
The following code tries to get a result from an url, and has 60 seconds timeout (1 minutes), but when the request is fired it is taking around 90 seconds for time out. When call is made, I manually turn off the network connectivity to check the time out. It is observed that it is taking more than 60 seconds.
CODE
public async Task<Dictionary<string,object>> GetPatientDataASync (string lUsername)
    {
        var lDict = new Dictionary<string,object> ();
        try {
            string lQuerystring = "{Email: '" + lUsername + "'}";
            String lUrl = String.Format (Constants.mURLPatient + "?where={0}", JObject.Parse (lQuerystring));
            var lClient = new HttpClient ();
            lClient.BaseAddress = new Uri (lUrl);
            lClient.DefaultRequestHeaders
                .Accept
                .Add (new MediaTypeWithQualityHeaderValue ("application/json"));
            lClient.DefaultRequestHeaders.Add ("X-Parse-Application-Id", Constants.mKeyParseAppId);
            lClient.DefaultRequestHeaders.Add ("X-Parse-REST-API-Key", Constants.mKeyRestAPIKey);
            lClient.Timeout = new TimeSpan (0, 1, 0);
            var request = new HttpRequestMessage ();
            request.Method = HttpMethod.Get;
            if (Utility.isNetworkConnected ()) {
                bool responseStatus = false;
                await lClient.SendAsync (request)
                    .ContinueWith (responseTask => {
                    if (responseTask != null) {
                        var response = responseTask.Result;
                        if (response != null) {
                        if (response.IsSuccessStatusCode) {
                                var responseContent = response.Content;
                                if (responseContent != null) {
                                    string responseString = responseContent.ReadAsStringAsync ().Result;
                                    if (!string.IsNullOrWhiteSpace (responseString)) {
                                        JObject json = JObject.Parse (responseString);
                                        if (json != null) {
                                            if (json ["results"].Any ()) {
                                                Patient user = Patient.Instance;
                                                user.objectId = json.SelectToken (@"results[0].objectId").Value<string> ();
                                                user.Email = json.SelectToken (@"results[0].Email").Value<string> ();
                                                user.Name = json.SelectToken (@"results[0].Name").Value<string> ();
                                                user.IsNotificationsEnabled = json.SelectToken (@"results[0].IsNotificationsEnabled").Value<string> ();

                                                Application.Current.Properties ["IsNotificationsEnabled"] = json.SelectToken (@"results[0].IsNotificationsEnabled").Value<string> ();

                                                if (json.SelectToken (@"results[0].DeviceToken") != null) {
                                                    var deviceToken = json.SelectToken (@"results[0].DeviceToken").Value<JArray> ();
                                                    if (deviceToken != null)
                                                        user.DeviceToken = deviceToken.ToObject < List<string>> ();
                                                } else {
                                                    user.DeviceToken = new List<string> ();
                                                }

                                                var doctors = json.SelectToken (@"results[0].MyDoctors").Value<JArray> ();
                                                user.AllergicTo = json.SelectToken (@"results[0].AllergicTo").Value<string> ();
                                                user.ContactNo = json.SelectToken (@"results[0].ContactNo").Value<string> ();
                                                user.BloodGroup = json.SelectToken (@"results[0].BloodGroup").Value<string> ();
                                                user.MyDoctors = doctors != null ? doctors.ToObject<List<string>> () : new List<string> ();
                                                responseStatus = true;
                                            } else
                                                responseStatus = false;
                                        }
                                    }
                                }
                            }
                        }
                    }
                });
              lDict.Add (SUCCESS_CODE, responseStatus);
                return lDict;
            } else {
                lDict.Add (NO_INTERNET, Constants.mStringNoInternetMessage);
                return lDict;
            }
        } catch (Exception e) {
            Debug.WriteLine (e.Message + "\n " + e.StackTrace);
            lDict.Add (EXCEPTION_OCCURED, e);
            return lDict;
        }
    }

If there's some mistake in my code , please do let me know.
Also the same issues are reported here :-

First link
Second Link
Answer: This is a know bug which was opened, closed and re-opened several times over the years. It is already reported here and here.
Answer: There is work-around solution:

Define CancellationTokenSource and Set Token to http request;
Invoke cancel by timeout on CancellationTokenSource like this cts.CancelAfter(timeout);:
Don't forgot catch exception, like this.

try
{
}
catch(TaskCanceledException)
{
    if(!cts.Token.IsCancellationRequested)
    {// timeout
    }
    else
    {//other reason
    }
}


How to implement extension method yielding two results for each input value?

Question: I am currently building an extension method which processes an IEnumerable<TSource>. For each item in the source collection I need to yield one or two items of the resulting type.
This is my first approach, which fails, since the method is being left on the first return statement, and forgets about its state when the second return statement is being hit.
public static IEnumerable<TResult> DoSomething<TSource>(this IEnumerable<TSource> source)
    where TResult : new()
{
    foreach(item in source)
    {
        if (item.SomeSpecialCondition)
        {
            yield return new TResult();
        }
        yield return new TResult();
    }
}

How would I implement this scenario correctly?
Comment: I don't see why that doesn't work... I must be misunderstanding.
Comment: Yeah, I actually tested it on a trivial example and it works.
Comment: `DoSomething` and `foreach(var item in source)`. Everything else is ok.
Comment: I don't see any problems, but for one iteration can be two items yielded, so there is a possibility that the number of items isn't the same.
Comment: Hmpf. I will try to create an example demonstrating the problem...
Answer: Your solution should work. Here is a full sample program which demonstrates that approach working:
using System;
using System.Collections.Generic;
using System.Linq;

namespace Demo
{
    class Program
    {
        void run()
        {
            var test = DuplicateOddNumbers(Enumerable.Range(1, 10));

            foreach (var n in test)
                Console.WriteLine(n);
        }

        public IEnumerable<int> DuplicateOddNumbers(IEnumerable<int> sequence)
        {
            foreach (int n in sequence)
            {
                if ((n & 1) == 1)
                    yield return n;

                yield return n;
            }
        }

        static void Main(string[] args)
        {
            new Program().run();
        }
    }
}

Also, note Dmitry Dovgopoly's comment about using the correct TSource and TResult.
Comment: You are right - I obviously missed something in my first ("slightly" more complicated) implementation...


How to display a Superscript in C# Dropdownlist, using html tags

Question: Hope someone can tell me how I should get a Superscript tag like ² to display correctly in the text of a Dropdownlist option?
Thanks.
Answer: Probably using HTML entities:
²

instead of the actual character. But it's probably better to let C# take care of it:
string safeString = HttpUtility.HtmlEncode("your string²");
// Use the result as the displayed value in your Dropdownlist

This method will also find other problematic characters such as & and replace them accordingly. See MSDN HttpUtility.HtmlEncode for more information on this.
Edit: be advised; the resulting string from HtmlEncode will show (when used in HTML) exactly that what you have input in the method. So do not use HTML entities in your input, because then that's exactly what you'll see in the resulting page.
If you want to show m² then just enter that inside the method. .NET will take care of the rest.
Comment: Tried this, HttpUtility.HtmlEncode("m²") gives me m² in the Dropdownlist option
Comment: Yes that's logical! You should use the actual text you want to display. So if you want to show "m²", then use exactly that as your input.
Comment: That did it. Sometimes just do exactly what you want it to do instead of making it more complicated. Thanks.
Answer: Maybe unicode symbols would do the trick for you: http://tlt.its.psu.edu/suggestions/international/bylanguage/mathchart.html#super
For the superscripted two you would use ² resulting in: ²
Comment: I have tried this, but it seems to just print out ² in the option.
Comment: Then it is already html-encoding it for you, resulting in the `&` being converted to `&` in the result and thus displaying it as text.
Answer: You can write this way,
string item=HttpUtility.HtmlDecode("ml/min/1.73m&#178;")

for more info on superscript you can see this link
http://symbolcodes.tlt.psu.edu/bylanguage/mathchart.html#super


Permutation of the vertexes of an irregular hexagon

Question: The question is: ¿In how many ways the vertexes $P,Q,R,T,S$ and $W$ can be assigned to an hexagon, where all the sides are different?.
My doubt is if I have to use circular permutation or linear permutation. If we consider a regular hexagon, we can inscribe it in a circle. Therefore, the permutation will be circular. But in this case, I don't know how to proceed, and why I have to use one of them and not the other.
Comment: What does that mean "where all the sides are different"? Once PQ is used, you can never have PQ be a side again?
Comment: @InterstellarProbe It means that, if you take the hexagon $PQRTSW$, $PQ\ne QR \ne RT \cdots \ne PW$, etc.
Comment: @InterstellarProbe that is, 1 way. Then you can take another hexagon e.g $PQRTWS$. That will mean $PQ \ne RT \ne \cdots \ne PS$.
Answer: Since all of the sides are different, it is safe to assume that any non-identity relabeling will result in a different hexagon. Example: $PQRTSW$ is different from the circle permutation $WPQRTS$ because the sides between the vertices are all distinct. So, no matter what permutation you choose, there are no symmetries to worry about.
You use circular permutations when outcomes with rotational symmetries are consider identical outcomes.


Nginx doesn't listen to HTTPS requests for subdomains

Question: I have a Nginx server that is hosting both the main domain foo.com and a subdomain bar.foo.com for a website. I only have a certificate for my main domain, so I only want HTTP requests for the subdomain. I have configured both server blocks, and all requests work well: http://foo.com will be redirected to https://foo.com, and http://bar.foo.com just stays on HTTP.
However, a problem rises when I tried to connect https://bar.foo.com, although I have not configured the subdomain server block to listen for 443 or ssl requests, the request is still handled, and after getting a warning from the browser that the certificate has a different host name than the one I am requesting, the page I get is from the main domain foo.com.
So, apparently, the server block that was supposed to only listen to HTTPS requests of my main domain, somehow is also listening to HTTPS requests of the subdomain, I don't want this to happen.
Here is my configuration for the main domain:
server {
  listen       80;
  server_name  foo.com www.foo.com;

  return 301 https://$server_name$request_uri;
}

server {
  listen       443 ssl;
  server_name  foo.com www.foo.com;

  ssl                  on;
  ssl_certificate      /etc/nginx/cert/foo.com.pem;
  ssl_certificate_key  /etc/nginx/cert/foo.com.key;
  ...

  location / {
    root   /var/www/foo.com/public_html;
    index  index.html index.htm;
  }
}

Here is my configuration for the subdomain:
server {
  listen       80;
  server_name  bar.foo.com www.bar.foo.com;

  location / {
    root   /var/www/bar.foo.com/public_html;
    index  index.html index.htm;
  }
}

And here is a snippet of the Nginx configuration file:
server {
  listen       80 default_server;
  listen       [::]:80 default_server;
  server_name  _;
  root         /usr/share/nginx/html;

  location / {
}

I have tried deleting foo.com after listen in the 443 server block of my main domain, but it doesn't help.
I would like Nginx either not listen to requests such as https://bar.foo.com or to simply return 404 or 444.
Comment: Configure a default server to `return 444` for unmatched SSL certificate names. This answer contains more details: https://serverfault.com/q/373929/131019 This relies on your visitors implementing SNI, which you can [mostly rely on these days](https://caniuse.com/#feat=sni).
Comment: @CosmicOssifrage Sorry, I am new to Nginx, may you tell me exactly how to configure such server? I have looked at the answer you provided but are still confused. Thanks a lot!
Comment: Does the file really end with `.conf`. Just curious, because it seems to be ignored.
Answer: Since you have only one server block configured for port 443, it is the default virtual server used by nginx to service all requests to port 443.
To add a default server for port 443 (TLS), you can add the following virtual host:
server {
    listen 443 default_server;
    server_name _;
    return 444;
}

Answer: I have figured out the solution. Just like @Tero and @Cosmic correctly pointed out, my only 443 server block for the main domain is being set to the default server block for all 443 requests.
I commented the server block in the Nginx configuration file /etc/nginx/nginx.conf and added the following two server blocks:
server {
  listen      80 default_server;
  server_name  _;
  return 444;
}

server {
  listen       443 ssl default_server;
  server_name  _;
  ssl_certificate      /etc/nginx/cert/foo.bar.pem;
  ssl_certificate_key  /etc/nginx/cert/foo.bar.key;
  return 444;
}

The first one will be set to the default server block for any HTTP requests, dropping any unmatched requests, and similarly the second one will drop any unmatched 443 or HTTPS requests.
The solution that @Tero provided won't work, because Nginx expects a certificate for any SSL server blocks, so you will need to provide it with a certificate.

Nginx doesn’t listen to HTTPS requests for subdomains


SSH into a shared text editor for phone screen code tests?

Question: Is there a simple way to have someone ssh into a machine and edit a text file while I view text they are writing?
I am interested in using this for phone screen interviews. Basically, I would tell the candidate to ssh into a particular machine and edit/compile a source file to test programming ability. Ideally, I would like to see what they are typing in real time rather than only when they save.
Is there a simple solution for this?
Answer: screen is the solution to this conundrum; see the -x option to create a shared session.  You can create the session beforehand and have the dialin [ :) ] account invoke screen -x -R to attach to it.  (I habitually use screen -A -U -R -x.)
Answer: You could use GNU Screen's multiuser feature (also called session sharing). http://aperiodic.net/screen/multiuser
It might be easier to setup a VNC & watch them that way. TightVNC allows you to run a 'web' server that they can connect to via a browser. http://www.tightvnc.com/winst.php#start_java
Answer: I've had a nothing but good experiences using a Google Doc for this. Realtime updating and collaboration for both parties, realtime cursor positions and highlighting for both parties, and it's stored somewhere really easy to get to afterwards, with revision history.
No syntax highlighting or auto-formatting, however, but honestly it's fine without it.
Comment: I think the OP was looking for the candidate to be able to compile as well.


to get the list of hostname, IP address, subnet mask

Question: want to write a Vb Script to get the full information on all the host name, and ip address and sub net mask of computer that has been added to the domain control.
Comment: Your 'question' goes a bit beyond the scope of what can be reasonable answered.  Also there are many existing tools which can do this.  Most people will not write this for you.  If still want to write it yourself you may want to start working on it and post specific questions about what you are having problems doing on stackoverflow.
Answer: Your best bet is to check out the microsoft script center where much of that has been written for you.  The script center has tutorials as well as the script repository where windows admins share scripts.  You should also take a look at the scriptomatic, an HTA application that can generate wmi reader code for you
Answer: Here is a VBS script, adapted from this page (look for "list Domain, computer and IP of all computers in AD"):
<code>' Modify these vars to match your enviroment
' requires Windows 2003 DNS

strDomain = "MyWindowsDomain"     ' Windows Domain NetBIOS Name
strDNSSVR = "DNSserver"           ' DNS Server's name or IP
strDNSDomain = ".mydomain.com"    ' Note the . at the beginning!
strFILENAME = "AD-Computers.txt"   ' Output File Name

'------------------------------------------------
'
' File stuff
Dim filesys, testfile
Set filesys = CreateObject("Scripting.FileSystemObject")
Set OUTfile= filesys.CreateTextFile(strFILENAME, True)

Const ADS_SCOPE_SUBTREE = 2

Set objConnection = CreateObject("ADODB.Connection")
Set objCommand =   CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"

Set objCOmmand.ActiveConnection = objConnection
objCommand.CommandText = _
    "Select Name, Location from 'LDAP://" & strDomain & "' " _
        & "Where objectCategory='computer'"
objCommand.Properties("Page Size") = 1000
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE
Set objRecordSet = objCommand.Execute
objRecordSet.MoveFirst

'debug stuff   Comment if you want to see it during execution
'Wscript.Echo "My DNS Server is: " & strDNSSVR
'Wscript.Echo "My Windows Domain is: " & strDomain
'Wscript.Echo "My DNS Suffix is: " & strDNSDomain
'Wscript.echo "Writing output to File: " & strFILENAME

'output
Do Until objRecordSet.EOF
    strHOST = objRecordSet.Fields("Name").Value
    strHOSTFQDN = strHOST & strDNSDomain
    strIP = GetIPFromDNS(strHOSTFQDN,strDNSSVR)
    OUTfile.WriteLine strDomain & " " & strHOST & " " & strIP
    'Comment line below to not dump output to screen
    Wscript.Echo strDomain & " " & strHOST & " " & strIP
     objRecordSet.MoveNext
Loop

Function GetIPFromDNS(sFQDN, strDNS)
  Set objWMI=GetObject("WinMgmts://" & strDNS & "\root\microsoftDNS")
  Set colIP=objWMI.ExecQuery("Select * from MicrosoftDNS_AType where ownerName='" & sFQDN & "'")
    For Each item In colIP
        GetIPFromDNS = item.RecordData
    Next
End Function

Outfile.Close
</code>


Solution verification of Exercise 8.2.6 Terence Tao Vol1

Question: I will use the lemma 8.2.7. I have written proof of this lemma, and want to verify, any comment or suggestion will be helpful.
Lemma 8.2.7. Let $\Sigma_{n = 0}^{\infty}a_n$ be a series of real numbers which is conditionally convegent, but not absolutely convergent. Define the sets $A_+ := \{n \in \mathbb{N} : a_n \geq 0\}$ and $A_{-} := \{n \in \mathbb{N}: a_n < 0 \}$ Thus $A_{+} \cup A_{-} = \mathbb{N}$ and $A_{+} \cap A_{-} = \emptyset$. Then both of the series $\Sigma_{n \in A_{+}} a_n$ and $\Sigma_{n \in A_{-}} a_n$ are not absolutely convergent.
Solution:
By Lemma 8.2.7 we know that $\Sigma_{n \in A_{+}} a_n$ is divergent. We are dealing with positive elements,so for $n \in A_{+}$ we have that $\Sigma_{n \in A_{+}} a_n = \infty$. We know that $A_{+}$ is infinite, so we have increasing bijection $f : \mathbb{N} \rightarrow A_{+} \subset \mathbb{N}$, therefore it follows:
$$\Sigma_{j \in \mathbb{N} : j \in A_{+}} a_j = \Sigma_{j = 0}^{\infty} a_{f(j)} = \infty $$
Thanks in advance.
Comment: What is your question?
Comment: Please write the text of the exercise in your post as well, otherwise only people who actually own the book can reply!
Comment: proof verification
Comment: why am I getting negative votes for verifying my proof for self-study ?
Comment: Please edit your question or title to make it clear
Comment: I did include the text as well.
Answer: Proposition $8.2.6(c)$ in the book states that if $X = X_{1}\cup X_{2}$ for some disjoint sets $X_{1}$ and $X_{2}$ and $f:X\rightarrow\mathbb{R}$ then $\sum_{x\in X}f(x)$ is absolutely convergent if and only if $\sum_{x\in X_{1}}f(x)$ and $\sum_{x\in X_{2}}f(x)$ are absolutely convergent and
$$\sum_{x\in X}f(x) = \sum_{x\in X_{1}}f(x)+\sum_{x\in X_{2}}f(x).$$
Suppose both $\sum_{n\in A_{+}}a_{n}$ and $\sum_{n\in A_{-}}a_{n}$ are absolutely convergent then using the proposition stated above $\sum_{n\in\mathbb{N}}a_{n}$ is absolutely convergent and using the identity map $\text{id}:\mathbb{N}\rightarrow\mathbb{N}$ we have $\sum_{n=
 0}^{\infty}a_{n}$ is absolutely convergent which is a contradiction (note that I have used the definition for series on countable sets which states that if $X$ is countable and $f:X\rightarrow\mathbb{R}$ and if $\sum_{x\in X}f(x)$ is absolutely convergent then $\sum_{x\in X}f(x) = \sum_{n = 0}^{\infty}f(g(n))$ for any bijection $g:\mathbb{N}\rightarrow X$).
Suppose we assume that exactly one of the series, say $\sum_{n\in A_{+}}a_{n}$ is absolutely convergent. Let
$$\sum_{n\in A_{+}}a_{n} = \sup\left\{\sum_{n\in B}a_{n}:B\subseteq A_{+},\:B\:\text{finite}\right\} = L.$$
Since $\sum_{n\in A_{-}}a_{n}$ is not absolutely convergent for the real number $M-L$ (where $M$ is some arbitrary real number) there exists a finite subset $C$ of $A_{-}$ such that
$$\sum_{n\in C}|a_{n}| = -\sum_{n\in A_{-}}a_{n} > -(M-L)\implies \sum_{n\in C}a_{n} < M-L.$$
Since $C$ is finite there exists a natural number $N$ such that $C\subseteq\{n\in\mathbb{N}:0\leq n\leq N\}$. Therefore,
$$\sum_{n = 0}^{N}a_{n} = \sum_{n\in\{n\in\mathbb{N}:0\leq n\leq N\}\cap A_{+}}a_{n}+\sum_{n\in\{n\in\mathbb{N}:0\leq n\leq N\}\cap A_{-}}a_{n}\\
\leq L+\sum_{n\in\{n\in\mathbb{N}:0\leq n\leq N\}\cap A_{-}}a_{n}<L+\sum_{n\in C}a_{n}< L+(M-L) < M.$$
Therefore, the partial sums of $\sum_{n = 0}^{\infty}a_{n}$ are not bounded below which implies that $\sum_{n = 0}^{\infty}a_{n}$ is not conditionally convergent which is a contradiction.


Using omniauth-google-oauth2 gem in rails 2.3.8 and ruby 1.8.7

Question: How to do authentication using omniauth-google-oauth2 gem in rails 2.3.8?
I have installed omniauth-google-oauth2 gem of version 0.1.15. But i dont know how to proceed further.
Answer: Here is the nice blog post on Google Authentication for ruby on rails app, just follow the simple steps.
Hope this will help you.
Comment: that blog is for google authentication in rails version >=4.2
Comment: Don't worry steps are same
Comment: I tried that but it is giving error as "undefined method `application' for Rails:Module"
Comment: this error is related to rails not `omniauth-google-oauth2`


Check access to entity for logged in user in Drupal 8

Question: I have added private message module for one of my project which has it's own entity. I need to check whether the user is having access to that entity content or not. The module has it's menu item defined in the module's routing.yml
e.g.:
<code>entity.private_message_thread.canonical:
  path: '/private_messages/{private_message_thread}'
  defaults:
    _entity_view: 'private_message_thread'
    _title: 'Private Messages'
  requirements:
    _entity_access: 'private_message_thread.view'
</code>
How could I check whether the user has view access to the above menu path?
Answer: I have tested the entity access and $entity->access('view', $account); that worked in my case. I earlier used the optional $account parameter so that it could check the currently logged in user.
I loaded my entity with:
<code>$entity_manager = \Drupal::entityTypeManager();
$thread_entity = $entity_manager->getStorage('private_message_thread')->load('private_message_thread_id');
</code>
I wanted to check whether the user has permission to view entity by code. Below is the code for the same I did in my case:
<code>$account = \Drupal::currentUser();
$entity_manager = \Drupal::entityTypeManager();
$entity = $entity_manager->getStorage('private_message_thread')->load('private_message_thread_id');
$check = $entity->access('view', $account);
</code>
Please let me know if you have a better answer over the same.
Answer: You can check annotations of those entities and find access handler.
e.g.
<code>/**
 * Defines the Private Message Thread entity.
 *
 * @ContentEntityType(
 *   id = "private_message_thread",
 *   label = @Translation("Private Message Thread"),
 *   handlers = {
 *     "view_builder" = "Drupal\private_message\Entity\Builder\PrivateMessageThreadViewBuilder",
 *     "views_data" = "Drupal\views\EntityViewsData",
 *     "access" = "Drupal\private_message\Entity\Access\PrivateMessageThreadAccessControlHandler",
 ...
</code>
As you can see, there is access handler. Now you know how it works.
<code>  protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) {
    if ($account->hasPermission('use private messaging system')) {
      switch ($operation) {
        case 'view':
          if ($entity->isMember($account->id())) {
            $messages = $entity->filterUserDeletedMessages($account);
            if (count($messages)) {
              return AccessResult::allowed();
            }
          }
          ...
</code>


Get sentences from transcript file

Question: I have files of transcripts where the format is

(name 1): (sentence)\n (<-- There can be multiples of this pattern)
(name 2): (sentence)\n (sentence)\n

and so on. I need all of the sentences. So far I have gotten it to work by hard-coding the names in the file, but I need it to be generic.
utterances = re.findall(r'(?:CALLER: |\nCALLER:\nCRO: |\nCALLER:\nOPERATOR: |\nCALLER:\nRECORDER: |RECORDER: |CRO: |OPERATOR: )(.*?)(?:CALLER: |RECORDER : |CRO: |OPERATOR: |\nCALLER:\n)', raw_calls, re.DOTALL)
Python 3.6 using re. Or if anyone knows how to do this using spacy, that would be a great help, thanks.
I want to just grab the \n after an empty statement, and put it in its own string. And I suppose I will just have to grab the tape information given at the end of this, for example, since I can't think of a way to distinguish if the line is part of someone's speech or not. Also sometimes, there's more than one word between start of line and colon.
Mock data:
CRO: How far are you from the World Trade Center, how many blocks, about? Three or four blocks?
63FDNY 911 Calls Transcript - EMS - Part 1 9-11-01
CALLER:
CRO: You're welcome. Thank you.
OPERATOR: Bye.
CRO: Bye.
RECORDER: The preceding portion of tape concludes at 0913 hours, 36 seconds.
This tape will continue on side B.
OPERATOR NEWELL: blah blah.
GUY IN DESK: I speak words!

Comment: But what is the output you intend to get?
Answer: You can use a lookahead expression that looks for the same pattern of a name at the beginning of a line and is followed by a colon:
s = '''CRO: How far are you from the World Trade Center, how many blocks, about? Three or four blocks?
63FDNY 911 Calls Transcript - EMS - Part 1 9-11-01
CALLER:
CRO: You're welcome. Thank you.
OPERATOR: Bye.
CRO: Bye.
RECORDER: The preceding portion of tape concludes at 0913 hours, 36 seconds.
This tape will continue on side B.
OPERATOR NEWELL: blah blah.
GUY IN DESK: I speak words!'''
import re
from pprint import pprint
pprint(re.findall(r'^([^:\n]+):\s*(.*?)(?=^[^:\n]+?:|\Z)', s, flags=re.MULTILINE | re.DOTALL), width=200)

This outputs:
[('CRO', 'How far are you from the World Trade Center, how many blocks, about? Three or four blocks?\n63FDNY 911 Calls Transcript - EMS - Part 1 9-11-01\n'),
 ('CALLER', ''),
 ('CRO', "You're welcome. Thank you.\n"),
 ('OPERATOR', 'Bye.\n'),
 ('CRO', 'Bye.\n'),
 ('RECORDER', 'The preceding portion of tape concludes at 0913 hours, 36 seconds.\nThis tape will continue on side B.\n'),
 ('OPERATOR NEWELL', 'blah blah.\n'),
 ('GUY IN DESK', 'I speak words!')]

Answer: I would use regular expressions and nested for loops in a list comprehension to grab all the sentences as illustrated in the code below.
s ='''(name 1): (sentence1 here)\n (<-- There can be multiples of this pattern)

(name 2): (sentence2 here)\n (sentence3 here)\n'''

[y.strip('()') for x in re.split('\(name \d+\):', s) for y in re.findall('\([^\)]+\)', x)]

>>> ['sentence1 here',
    '<-- There can be multiples of this pattern',
    'sentence2 here',
    'sentence3 here']

Get sentences from transcript file


Using Linux's netfilter to reflect packets

Question: I've got a pair of hosts with very bad routing between the two, but I have a third host that has very good ping to each. To work around the bad routing, I'm setting up the third host to bounce packets back and forth between the two.
This third host has an IP address that isn't used for anything else. My ideal configuration would be, when host 1 sends a packet to host 3, host 3 automatically NATs the source and destination addresses, replacing source=host3 and destination=host2, then forwards the packet.
The inverse should be true: If host2 tries to respond, the packet should go back to host3, which will NAT it back to source=host3, destination=host1. No connection tracking is required -- this can be done entirely statelessly.
Where I'm stuck is in getting both DNAT and SNAT to work at the same time. It seems like, if a packet is handled by DNAT, it's automatically marked to skip the SNAT rules: the DNAT works fine, but the source address isn't getting translated.
What is the proper iptables configuration to achieve this?
Comment: The proper way to do this is to make the third host a VPN server.
Comment: Normally I would agree. However, this is a special case where neither end-host is VPN-aware, so the redirection must be completely transparent.
Comment: SNAT and DNAT rules work fine together, you just have to write the rules correctly, which can be a bit tricky because of the order of operations.   One must happen before a routing and filtering is done, the other must be done afterwards.
Answer: The strange behavior was due to CONNTRACK. SNAT and DNAT indeed work fine together if nothing else gets in the way.
Also, I've only configured the SNAT and DNAT in one direction. Because there is traffic constantly going through, SNAT and DNAT's automatic reverse translation take care of the return path for me.