What does "splitting naturally" mean in the Universal Coefficients Theorem

Question: The Universal Coefficients Theorem states that
$0\rightarrow H_n(X)\otimes G\rightarrow H_n(X;G)\rightarrow\operatorname{Tor}(H_{n-1}(X),G)\rightarrow 0$
splits, but not naturally. In all the algebraic topology contexts I've come across, "natural" implies commutativity, but I don't see what a "natural split" means. Can someone give me an explicit definition?
Edit:
From what I've read... if I understand this correctly, splitting naturally implies that if
$0\rightarrow A\rightarrow A\oplus C\rightarrow C\rightarrow 0$
and
$0\rightarrow A'\rightarrow A'\oplus C'\rightarrow C'\rightarrow 0$
and given maps $a:A\rightarrow A'$ and $c:C\rightarrow C'$, the map $A\oplus C\rightarrow A'\oplus C'$ has to be the map $(a,c)$ in order for the diagram to commute.
Comment: **Yes,** what you say is correct. However, it becomes clearer if you write $0 \to A(X) \to B(X) \to C(X) \to 0$ and $0 \to A'(X) \to B'(X) \to C'(X) \to 0$ (the sequences *depend naturally* on $X$). Now they split. That is to say, $B(X) \cong A(X) \oplus C(X)$, for *some* isomorphism, but this isomorphism does *not* depend naturally on $X$.
Comment: Here's a [relevant discussion](http://mathoverflow.net/questions/59938/examples-for-non-naturality-of-universal-coefficients-theorem) on math.MO
Comment: I already did see that discussion, but I still don't understand how the OP's question relates to the Universal Coefficients Theorem. I don't see how those induced maps on homology and homology with coefficients relate to the exact sequence in the UCT. (Also, I don't know what $\Sigma$ means, so that may help me.)
Comment: Ok, so here's the thing. The sequence splits, that is to say that the middle term is the direct sum of the two outer terms. If this splitting were natural in $X$, the map in the middle would have to be the direct sum of the outer maps for all maps $f: X \to Y$. Dylan asks about a map that induces the identity on the two outer terms in the UCT, but fails to be the identity in the middle, so this shows that the splitting isn't natural in $X$.
Comment: The $\Sigma$ means the suspension, denoted $S$ on [wikipedia](http://en.wikipedia.org/wiki/Suspension_(topology)).
Comment: I edited my question. Am I correct? If so, the rest of it makes sense.
Answer: $\require{AMScd} \newcommand{\RP}{\mathbb{RP}}$
Note:  The splitting is actually natural in $G$ contrary to what is written in many texts.  What she is referring to is the following:$\newcommand{\z}{\mathbb{Z}}$. Lets fix $G=\z/2$.
Thm:  There is no possibility of a natural transformation from the functor $H_*(-,\z/2)$ to $(H_{*}(-,\z))^* \oplus Ext(H_{*-1}(-,\z),\z/2)$.
Proof:  Suppose if possible that for all spaces $X,Y$ and every continuous map $X \to Y$, there is an induced a commuting square
$ \begin{CD}
H_*(X,\z/2) @>\cong>> Tor(H_{*-1}(X),\z/2) \oplus H_*(X) \otimes \z/2 \\
@VVV @VVV\\
H_*(Y,\z/2) @>\cong>> Tor(H_{*-1}(Y),\z/2) \oplus H_*(Y) \otimes \z/2 \\
\end{CD}$
.
Then there would have to be a commuting square induced by $\RP^2 \to \RP^2/\RP^1 \to S^2$:
$ \begin{CD}
H_2(\RP^2,\z/2) @>\cong>> Tor(H_{1}(\RP^2),\z/2) \oplus H_2(\RP^2) \otimes \z/2 \\
@| @V0VV\\
H_2(S^2,\z/2) @>\cong>> Tor(H_{2-1}(S^2),\z/2) \oplus H_2(S^2) \otimes \z/2 \\
\end{CD}$.  Contradiction since the 0 map would need to be an isomorphism.
Note: One could not have expected there to be such a natural transformation because $H_*(X)$ splits into objects of different homogenous degree, while the induced maps of topological maps map elements of the same degree onto elements of the same degree.
Note 2: The diagram $$ \begin{CD}
H^2(\RP^2,\z/2) @>\cong>> Ext(H_{1}(\RP^2),\z/2) \oplus H_2(\RP^2)^*  \\
@| @V0VV\\
H^2(S^2,\z/2) @>\cong>> Ext(H_{1}(S^2),\z/2) \oplus H_2(S^2)^*  \\
\end{CD}$$ shows that the exact sequence of the cohomological universal coefficient theorem does not split naturally with respect to the topological space.
Answer: It doesn't seem like anyone has said it the following way, yet, which might help clear things up:
What does it mean for an exact sequence to split? It means, among other things, that you have given a section of the last map in the sequence. Now, we have a functor from spaces to short exact sequences and we might ask whether or not we can lift this to a functor from spaces to short exact sequences together with a section (i.e. split short exact sequences.)
However, we cannot. The reason is that there are endomorphisms of spaces that induce the identity map on $H_*(X)$ but not on $H_*(X;G)$. This means, in particular, that the functor would give an endomorphism of exact sequences that is the identity on the ends but not in the middle. It is easy to check that no such endomorphism of a split exact sequence exists, and so the functor does not lift.
So perhaps a better thing to say is that the sequence does not split "functorially."
Comment: Rather, one should remark that the word 'natural' here is being used in the same technical sense as in 'natural transformation' or 'natural isomorphism'.
Comment: @ZhenLin: Ah but to say that I would have to reformulate slightly. A natural transformation is some morphism of functors. In this case we have one morphism of functors, namely from $H_n(X;G)$ to $Tor(H_{n-1}(X), G)$. The claim is that there is no natural transformation the other way such that one of the compositions is the identity natural transformation.
Answer: Here is the definition for a natural splitting.
Given an abelian category C, for each element A in C, there is a short exact splitting sequence $$0 \to A' \to A \cong A' \oplus A'' \to A'' \to 0$$, such that $j_A \circ i_A = id_{A'}$, $\pi_A \circ \gamma_{A} =id_{A''} $
Given $f: A \to B$, define a functor T from C to C, such that
T(A) is $A' \oplus A''$, $T(f): A' \oplus A'' \to B' \oplus B''$, such that $$T(f) = f' \oplus f''$$
$$f' : A' \to B', f' = j_B \circ f \circ ia$$
$$f'':A'' \to B'', f'' = \pi_B \circ f \circ \gamma_{A} $$
Go check that T is indeed a functor.
Then natural splitting means that there is a natural isomorphism from identity functor to this T. The components of the natural isomorphism are given by the isomorphism from $A \to A' \oplus A''$


$ \left\lfloor 10^{\lfloor n \rfloor} \pi \bmod 10 \right\rfloor $ - does this function give the nth decimal place of pi?

Question: Function to round the nth decimal place of pi to the nearest integer. For example, for pi, n = 0, y = 3. n = 1, y = 1. n = 2, y = 4. And so on and so forth.
Gives me good results until n = 17, which yields 8 instead of the expected 3. Then it's unfortunately kind of all over the place. It only gives me even numbers?
Is my function correct, or is this a Desmos error?
https://www.desmos.com/calculator/bekze2iayc
Comment: Yes, this function is correct, computer software tends to only have a finite number of digits represented.
Comment: Please avoid having your subject line consist of nothing but MathJax. It messes up some navigation shortcuts.
Comment: Dealt with, thanks.
Comment: Oops, my mistake.
Comment: As $n$ is an integer you will have $\lfloor n \rfloor = n$ so you could write this more simply as $\lfloor 10^n\pi \pmod{10}\rfloor$.  Also $\pmod {10}$ is not actually a mathematical function but a notation for equivalence classes it'd probably cleaner and stylistically to write it as $\lfloor 10^n\pi\rfloor \pmod{10}$.  You function is almost by definition the $n$th digit of $\pi$.  This is simply Desmos's rounding error.
Answer: Your function is mathematically correct, but not computerically correct.  $64$ bit floating point numbers have about $16$ decimal digits of precision.  You don't need the floor on $n$, but you are trying to extract decimal digits that are not there.


Algorithms for time stretching/pitch shifting

Question: I want to change the pitch of an audio track and try to keep the highest quality possible, so when I click on processor algorithm setup, I have few options :
Standard method (time stretches and pitch shifts without the aid of beat markers)
Smooth method
HQ Universal
ect ect...
can someone explain to me what beat markers mean in pitch shifting ? and what would be the best quality ? is it the standard or the HQ Universal ?
Comment: Exactly what these things mean will depend on what software you are using - which product are you referring to?
Comment: @CarlWitthoft I think the OP is referring to the fact that there are often different options available as to the precise algorithm to use - e.g. leaning towards not 'smearing' beats, or towards minimising artifacts in pitched sounds.
Comment: Any decent digital processing tool can perform pitch shift and time stretching independent of each other without throwing away the precision of the input data.  What is your fundamental question?
Answer:
can someone explain to me what beat markers mean in pitch shifting ?

Yes! I recommend reading the User's Manual.
From the user's point of view, there are basically two types of time-stretching algorithms: "sliced" and "elastic":
(1) Slice-and-move/repitch, like the Propellerheads ReCycle product with its REX file format. Best suited for individual isolated rhythmic instrument tracks: drum and percussion loops, guitar chord strumming loops, bassline loops, riffs, etc. Not really suitable for full mixes and vocals.
In the good old Propellerheads ReCycle system, the software detects note/hit attack transients and places beat markers on them (and you can adjust the detection sensitivity and IIRC you can also manually place markers), and then the audio is basically chopped up at the beat markers, creating audio "slices". Time-stretching is done by moving the slices on the timeline, and pitch shifting is done by playing the sound inside each slice slower or faster. If played at exactly the original timing and pitch, you wouldn't notice any differences, but when time-stretching, the slices are spread around, keeping the beat markers on the sequencer's beats (or other desired time locations), as if someone had played the slices as individual samples on a sampler. Playing the slices at a higher tempo is easier, but when you slow down the tempo, you move the slices further apart, and then you get silent gaps between the slices. For some drum tracks this might not be a problem, if every note slice fades out to silence anyway. But for more continuous tracks, what to do? One method is to fill the gaps by ping-pong looping each slice backwards/forwards until the next slice.
Slicing does not work very well for full mixes, slow pad-like sounds, or vocals, because the slice-and-move or slice-and-repitch method (with the gaps and all) usually makes the audio sound too choppy and vocals unnaturally hiccupy.
(2) "Elastic" algorithms (which themselves are further subdivided to time-domain overlap-add and frequency-domain spectral methods, but from the user's point of view they can be treated somewhat similarly). These algorithms are more suitable for full mixes and vocals, because they don't suffer from the hiccup problem. But for sharp attacks like drums, they might ruin the punchiness. You don't want to un-sharpen the attacks of your drums. The elastic algorithms also need more processing power than slicing, so they'll be heavier on your computer (CPU).
Elastic methods treat audio like an elastic rubber-band, smearing everything more or less equally, not making sharp cuts or slices anywhere but trying to smoothly slide from one spectrum (timbre) to another. Some algorithms might try to somehow automagically "understand" what's happening with the audio, and which spots are important to keep less smeared. Elastic algorithms are better for full mixes and vocals.
Beat markers are important for these algorithms as well, in order to preserve the proper rhythmic feel. Or to do things like audio quantization and "groove quantization".
From pitch shifting point of view, beat markers are the spots where the virtual keyboard player plays a new note on the sampler, if you imagine that it's like having chopped up the audio to individual samples in a sampler.

and what would be the best quality ? is it the standard or the HQ
  Universal ?

It really depends on many things, and you have to try it out. What works for some type of material might not work for another. There's no "universal" setting for everything.
Answer: The reason different algorithms exist is because there is no "best" - they all are good at different things. And the specific algorithms those names refer to may vary across products.
For the genre of music you want to create, your best bet is to try them all and see which works best. Does it cope with your beats, your highs and lows, rapid changes, etc.?
Answer: There are two general methods in digital signal processing for time/pitch modification: time domain and frequency domain.
Time domain methods generally stretch sustained note sound by whole pitch periods (add one or remove one time slice of 1.0/pitch_frequency in duration). This can throw off the precise timing of notes, and may remove few-millisecond-sized (but interesting) sound features due to deletion.
Frequency domain methods generally stretch everything equally in time, which does not throw off precise timing as much, but potentially can smear the timbre of note transients (attach and percussion) and distort voice formant.
So, it's a trade-off.  Choose your preferred artifact.
Comment: From a user's point of view, the division you present is not something you'd find in an application's user interface, and doesn't really classify the types of artifacts. Some time domain algorithms can cause smearing, and some of them can perfectly preserve the precise timing and attack transients of notes, but can introduce chopping-up artifacts at the tails of notes.


Change content of views_field_view field using hook_views_pre_render

Question: I am using the views_view_field module for embedding a view inside another view.
I want to concatenate some text with that field in hook_views_pre_render based on a condition.
But when I printed the $view->result array, that field is not there.
So How can I do this?
Comment: Is that other field hidden in the views UI?
Comment: Seeing that you're embedding a view, it might be that the view field isn't available yet. Did you try to run the pre_render on the view you are embedding instead? Another option could be to create a template for the embedded view field.
Comment: @NoSssweat which field? If you are talking about the view field then No, it is not hidden.
Comment: @seroton I need the parent view field value for the condition therefore I can't use pre_render on the child view.
Answer: Try using template_preprocess_views_view_fields
If you still can't access that field there then:

Ditch views_view_field
Add a "custom text field" (their field_name will be nothing).
In template_preprocess_views_view_fields programmatically add view to this "custom text field".

/sites/all/themes/THEMENAME/template.php
function THEMENAME_preprocess_views_view_fields(&$vars) {
  $view = $vars['view'];
  foreach ($view->field as $id => $field) {
    if ($something == 'some condition') {
      $vars['fields']['nothing']->content = 'some string' . '

' .
        views_embed_view('view_name', 'view_machine_name', $contextual_filter_value);
    }
    else {
      $vars['fields']['nothing']->content = views_embed_view('view_name', 'view_machine_name', $contextual_filter_value);
    }
  }
}

If your view does not need a contextual filter, then it's:
views_embed_view('view_name', 'view_machine_name');


Como alterar o nome da coluna do dataframe do pandas?

Question: Estou usando o pandas para processar um arquivo CSV na seguinte estrutura:
nome;idade
Fulano;28
Joao da Silva;27
Maria;29

A leitura do arquivo é feita da seguinte forma:
import pandas as pd

df = pd.read_csv('dados.csv', sep=';')

É gerado meu dataframe df com o conteúdo do CSV:
            nome  idade
0         Fulano     28
1  Joao da Silva     27
2          Maria     29

Sendo assim, eu gostaria de saber como eu posso alterar o nome das colunas no meu dataframe? Tentei usar a função rename desta forma:
df.rename(columns={'nome': 'nome_completo'})

mas, aparentemente não funcionou.
Gostaria de trocar o nome da coluna nome para nome_completo no dataframe.
Comment: Gato, se alguma resposta resolveu seu problema, você poderia marcar uma delas como aceita. Entenda importância disso nesse link: https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta
Answer: Segundo a documentação do comando rename, o retorno dessa função é um novo DataFrame com a(s) coluna(s) renomeada(s).  Para você chegar na resposta desejada, (1) basta atribuir o retorno da função em uma nova variável, ou (2) passar o comando inplace = True que ele atribuirá o novo nome da coluna direto no DataFrame que você possui.
df = df.rename(columns={'nome': 'nome_completo'})
#ou
df.rename(columns={'nome': 'nome_completo'}, inplace = True)

Também é possível mudar o nome das colunas passando apenas um dicionário para a função .rename() junto com o parametro axis=1, desta forma:
df = df.rename({'nome': 'nome_completo'}, axis = 1)

Answer: Você pode passar uma lista com os novos nomes que você deseja:
df.columns = ['nome_completo', 'idade']

Apenas um adendo, o comando df.rename(columns = {'nome':'nome_completo'}) está correto, mas para que a alteração seja implementada no df você precisa adicionar o argumento inplace = True.
Answer: Tente assim
import pandas as pd

df = pd.read_csv('dados.csv', sep=';', names=['nome_completo', 'idade'], header=0)

dependendo do seu arquivo csv, talvez seja necessário atribuir header=1 para omitir o cabeçalho anterior
assim não precisará adicionar mais nenhuma outra linha
Comment: Boa Guilherme, mas lembre que o `header` tem que ser `0` ;)
Comment: depende do seu arquivo csv, como não possuo não pude fazer o teste para verificar a forma mais correta para o seu problema, mas é um jeito de de alcançar seu objetivo sendo necessário adaptar de acordo com a sua saída esperada, mas se acha que ficaria melhor a reposta com __header=0__, posso deixa do jeito que melhor resolveu o seu problema
Answer: Você pode nomear as colunas assim que chamar a função read_csv do pandas:
df = pd.read_csv('dados.csv', delimiter=';', encoding='iso-8859-1', usecols=['nome_completo', 'idade'])

além de nomear, pode adicionar parâmetros extras como delimitador e encoding.
Answer: Você esqueceu apenas de colocar Unique = True no final.
df.rename(columns={'nome': 'nome_completo'}, Unique = True)
Prontinho, dessa forma irá funcionar!!
Answer: Você pode usar também:
df.rename({"nome": "nome_completo"}, axis=1, inplace=True)


Webform many dropdownlist results saved under one unique field

Question: I'm working with webform to collect information on car relliabilty level.
I've set one dropdownlist to allow user choosing a car brand. As a car brand is selected, only the coresponding dropdownlist, with car models, is showing up (done with Webform Conditional).
All is working fine, but I realize each model dropdownlist is saving data in its own field in the database.
I want to analyse results by car brand and car models.
What would be the best way to proceed?
Saving all models in one fields, when data are submitted? Maybe with a hook
Merging all car models after data submission in one unique field?
My test: http://fiabilidad-coche.blg.lt/?q=node/10
Any help or hint would be greatly appreciated.
Answer: Ok, I found a solution: I've used a presave hook. This hook is saving all values submitted by users in a hidden field called "model". A loop will be needed to read the 56 listboxes and save the only value the user have selected.
To do my test I've created a test webform, with only one listbox and one hidden field (this field created automatically my needed field "model" in my database). That speed up a little my tests:
First at all I've created a custom module with a "presave" hook
In a new directory named "duplicated_data", I have create two files:
data_duplicate.info
data_duplicate.module
In the info file I've declared my module
name = Data Duplicate
description = Duplication Data for Webform
core = 7.x
package = Webform
dependencies[] = webform

In the module file I've written my php code
<?php
function data_duplicate_webform_submission_presave($node, &$submission) {
  $component_id = 1; // dropdownlist cid = 1
  $mem = $submission->data[$component_id][0]; // retrieve the submitted value
  drupal_set_message('datos :'.$mem); // print the result
  $component_id = 2; // cid = 2
  $submission->data[$component_id][0] = $mem; // save the data in the hidden field
}
?>

Now I need to activate my custom module.
Each time I make a choice in my dropdownlist/listbox and click on submit, the results will be saved in the database in both fields.
For my production webform , I need to create the loop in order to read all the 56 listbox values and save in my field "model" only the value from the selected listbox. It will be easy to catch it, because it will be the only one, different from NULL.
Hope it will be help somebody else!
Answer: Here I leave the final code:
<?php
function data_duplicate_webform_submission_presave($node, & $submission) {
  if($node->title == 'Encuesta') { // the hook will only work with this node
  for ($component_id = 2; $component_id < 58; $component_id++) { //loop into all my listboxes
  $mem = $submission->data[$component_id][0];
  if ($mem != NULL) { // save only data <> NULL => the user selected data.
  $submission->data[100][0] = $mem; // save the data in my field "model"
  drupal_set_message('Model : '.$mem); // optional, message with the value of the user selection.
  }
  }
  }
}
?>


How is the direct product of two supersolvable groups again supersolvable?

Question: A supersolvable group is one with a normal series such that each factor is cyclic. In particular the last non-trivial term in the series has to be cyclic. But if we take take two of the same groups, the product of the last two terms wouldn't be cyclic. So the direct product ought to not be supersolvable. I don't understand what I'm missing here.
Answer: Say $A$ and $B$ are supersolvable with normal series $1=N_0\leq N_1\leq ...\leq N_i=A$ and $1=M_0\leq M_1\leq ...\leq M_j=B$. Then the series $$1=N_0\leq N_1\leq ...\leq N_i=A\leq A\times M_1\leq A\times M_2\leq ...\leq A\times M_j=A\times B$$ is a normal series of $A\times B$ with every quotient is cyclic.
Edit : What you are missing is that the series you need to consider for $A\times B$ is not formed by taking the product of the terms in the series of $A$ and $B$. In this case, as you said, the quotients will not be cyclic.


Equality situation in Jensen's inequality

Question: Let $(X,\Sigma,\mu)$ be a probability space, and let $g:X \to \mathbb [0,\infty)$ be measurable.
Let $\phi:\mathbb [0,\infty) \to [0,\infty)$ be a convex $C^1$ function.
Furthermore, assume that there exist an $a \in (0,\infty)$ such that

$\, \phi$ is strictly convex on $[a,\infty)$.
$c:=\int_X g d\mu \in [a,\infty)$.

Finally, we are given the fact that $\int_X \phi\circ g=\phi(\int_X g)$.

I am trying to prove that $g$ must be constant a.e.
In fact, it suffices to prove that $g(x) \ge a$ a.e, since then the strict convexity of $\phi$ can be applied directly. However, I don't see how to use that to obtain a simpler proof.
I think I found a proof, but I am not sure, and I wonder if there is an easier approach or lemma lying behind here:
First, as is proved here for instance, we deduce from the Jensen equality that
$$ \phi(g(x))-\phi(c)=\phi'(c)\big( g(x)-c\big) \tag{1}$$
for almost every $x \in X$.
Now let $x \in X$ be a generic point, where equation $(1)$ holds. We claim that $g(x) \le c$. Assume otherwise, that $g(x) > c$. Then the mean value theorem implies that $\phi'(c)=\phi'(m(x))$ for some $g(x) >m(x) > c$.
This contradicts the fact that $g$ is strictly convex on $[a,\infty)$, so its first derivative must be strictly increasing on that interval, and in particular $\phi'(c)<\phi'(m(x))$.
Thus , for a.e. $x \in X$, we have $g(x) \le c$. Integrating, we see that $g(x)=c$ a.e. as required.
Answer: First, note that the strict convexity of $\phi$ in $[a,\infty)$ implies that for $x>a\ge y$,
$$\phi(t x + (1-t) y) = t\phi(x) + (1-t)\phi(y)$$
implies $t\in \{0,1\}$.
Now, denote $A = g^{-1}([a,\infty))$. Obviously, $\mu(A)>0$. If $\mu(A) = 1$, we are done.
Otherwise, denote $x=(\mu(A))^{-1}\int_A g$, and $y=\mu(A^c)^{-1}\int_{A^c} g$.
We obviously have $y< a$ and $c= \mu(A)x + \mu(A^c)y$, hence $x>a$.
Thus, using the equality assumption and Jensen's inequality,
$$\phi(c) = \int_X \phi\circ g = \int_A \phi\circ g + \int_{A^c} \phi\circ g \ge \mu(A)\phi(x) + \mu(A^c)\phi(y)\ge \phi(c).$$
Therefore equality must hold, hence either $\mu(A)=1$ or $\mu(A^c)=1$, and both options result in a contradiction.


Entrada específica de informação

Question: O objetivo é fazer com que o programa aceite somente números no método numero() (não pode aceitar se for letra, ponto, interrogação, etc).
Já no método usuario(), somente letras (não pode aceitar números, ponto, interrogação, etc).
 public void numero() {
        System.out.println("Digite o número da conta: ");
        this.setNumeroConta(sc.nextInt());
        sc.nextLine();
        if (this.getNumeroConta() >= 0) {
            System.out.println("SUCESSO_NA_OPERÇÃO NUMERO_DA_CONTA");
        }
    } else {
        System.out.println("Somente números");
    }
}

 public void usuario() {
        System.out.println("Digite o nome de usuário: ");
        this.setDono(sc.nextLine());
        if (this.getDono() != null) {
            System.out.println("SUCESSO_NA_OPERÇÃO NOME_DO_USUARIO");
        }
    } else{
        System.out.println("Somente letras");
    }

}

Comment: Dê uma olhada nesta questão e na resposta dela: https://pt.stackoverflow.com/q/42351/132
Comment: Não entendi, o enunciado me pareceu muito confuso. Teria como por exemplos do que deve ser aceitado/recusado por esses métodos? E como você os chama no programa principal?
Answer: vai depender muito de onde esta vindo a informacao , se vier de uma tela (java web) voce pode usar atributo do html5 chamado pattern com o regex que pegue apenas letras pattern="[a-zA-Z]+/g" e assim  para apenas numeros pattern="[0-9]+/g", ou se vier do banco de dados voce pode usar um coalesce formatando do jeito que voce quer.
neste seu metodo voce pode colocar um construtor para garantir que ele receba so o tipo esperado e pode remover caracteres como no exemplo que fiz tambem com regex.

 public void usuario(String entrada.matches("^[a-zA-Z\s]+$")) {
            System.out.println("Digite o nome de usuário: ");
        this.setDono(sc.nextLine());
        if (this.getDono() != null) {
            System.out.println("SUCESSO_NA_OPERÇÃO NOME_DO_USUARIO");
        }
    } else{
        System.out.println("Somente letras");
    }

}

Entrada específica de informação


"Force check now" in zabbix 2.2.1

Question: If any of you know if there is a possibility of implementation "Force check now" just like in Nagios? the problem is that some check have a high update interval time for example 10 minutes, and sometimes there is a need to test something quickly.
In Zabbix Jira i found something like that's : https://support.zabbix.com/browse/ZBXNEXT-473
Please give me some advice
Regards
Mick
Comment: There is currently no such feature and ZBXNEXT-473 is the correct place to track its progress.
Answer: On the server, there is a command `zabbix_get' which exactly try the value of the key immediately.
<code>sudo zabbix_get -s hostNameOrIP -k keyName
</code>
So easy!
Comment: Yeah but there is some way to do this from GUI ?
Comment: @Mick, I don't know any way in graphical except setting time interval for 5 seconds or less or more in item's configurations.
Comment: This won't actually make the zabbix_server check the item, and put it in the database. It will only check it from the command line and return the data to the command line.
Answer: One (quirky) way might be to visit the configuration for your problematic host, then choose Triggers, then configure the alarming trigger, choose Expression constructor and from there Test.
I know this might not perform exactly what you are after for, but it's better than nothing.

"Force check now" in zabbix 2.2.1


Odds of two specific Hold'Em hands and an exact board?

Question: The goal is to solve the probability of a Texas Holdem hand occurring where at the river one player has quad $9$s and the other player has exactly a $9$-high straight flush.
(For non poker players - in holdem each player has $2$ cards and the board has 5 cards - players make the best hand of $5$ by any combination using their hole cards and the board)
This requires that:

(A) Player 1 holds 2 nines but not the nine of diamonds
(B) Player 2 holds any two of the $5,6,7$ and $8$ of diamonds
(C) The board by the river contains the other two diamonds not held by player 2 AND must not have the 10 of diamonds on the board, plus must have the last 9.

I know the final probability is A * B * C
A = 3/52 * 2/51
B = 4/50 * 3/49 (since we know A we can lower the card count right?)
How do we solve C?
I think it's something like: (4/48 + 3/47 + 2/46 + 1/45 + 1/44) - (odds of 10d) but ... I'm not sure if that math is right or how to calculate the odds of just the 10d.
(Edit - forgot the 4th 9 needed to be on the board)
Comment: A, B, and C are not independent.
Comment: That's why for B I used 50 and 49 cards, not 52 and 51 cards...  and similar for C.  Is that what you're getting at or am I missing you? @Gaffney
Comment: Knowing the probabilities in hold em' only makes the game more frustrating.  When the "fish" with 2 outs gets there on the river, you want to bang your head on the table.
Comment: True.  However, the reason behind this question has nothing to do with fish.  This is actually a requirement for the only bad-beat jackpot offered by a local card-room.  I'm curious about the precise odds, because I'd like to illustrate to the room just how moronic it is to think that this has any chance of bringing in players to the room in hopes of hitting it.
Comment: My guess for the probability of $C$ given $A$ and $B$ is $\frac{2}{48}\cdot\frac{1}{47}\cdot\frac{1}{46}\cdot\left(1-\frac{2}{44}\right) \cdot \left(\begin{array}{l}5\\3\end{array}\right)$
Comment: Ok.  Why?  How did you arrive at this?
Answer: The chances for $C$ are $43/{48\choose 5}=43*120/(44*45*46*47*48)$  There are $48\choose5$ possible tables.  It needs the other two diamonds, the other two nines, and one other card which is not the ten.  So there are 43 possible tables that work.
Overall, chances of it happening with diamonds is 43/154521166800; happening at all is 43/38630291700, slightly better than one in a billion.  Double that if player 1 and player 2 can swap places.
Comment: How do you arrive at 43, and where does the *120 come from?
Comment: After the nines and the other diamonds, there are 44 cards left.  The fifth slot is one of those, but not the ten of diamonds.  ${48\choose 5}=48*47*46*45*44/(5*4*3*2*1)$ is the number of possible tables; success requires two specific diamonds, two specific nines and one of 43 other cards.
Comment: Ok, I get the 48.  Where'd the * 120 come from?
Comment: 120=5*4*3*2*1, so ${48\choose 5}=48*47*46*45*44/120$ and $43/{48\choose5}=43*120/(48*47*46*45*44)$
Comment: Ah of course - duh.  Thanks!
Comment: I get a much different number for (48/5) = 1712304.


keeping the clean code in java while performing git operation

Question: How to validate the code(like removing unused headers/code, duplicate lines/methods etc) during git operation like commit/push?
Comment: Look into using Git hooks.  You could actually create both client side and server side hooks.  But note that a few of your asks (e.g. remove unused headers) often falls to the responsibility of the IDE to remove.
Answer: If you modify the code, that means you should not do it on the server side (with post-receive hook)
You might have a pre-receive hook (still on the server side) which would reject improper commits.
But you can set a pre-commit hook on the client side, or you setup a clean script, that is a content filter driver, which would do the same on checkin.


can't find symbol, what am i doing wrong?

Question: So basically I am calling a class into my main and then trying to print out the final line at the bottom but it keeps saying that it can't find the symbol for int x and int y.  Im pretty sure I assigned them accordingly to the right console input.  Does anyone know what am i doing wrong.  Im new to java.
import java.util.*;

public class mainRational {
    public static void main(String[] args) {

        Scanner console = new Scanner(System.in);
        Scanner console2 = new Scanner(System.in);

        System.out.println("Enter a number for the numerator and denominator: ");

        //creates the first class object
        rationalNumbers rational = new rationalNumbers(console.nextInt(), console2.nextInt());

        int x = console.nextInt;
        int y = console2.nextInt;

        System.out.println("Rational Number is: " +x+ "/" +y);
    }
}

PUBLIC CLASS
public class rationalNumbers {

private int Numerator;
private int Denominator;
private String String;

public rationalNumbers(int Numerator, int Denominator){

    if (Denominator==0)
        throw new IllegalArgumentException();
    this.Numerator=Numerator;
    this.Denominator=Denominator;

}

public void rationalNumber(){

}

public int getDenominator(){
    return Denominator;

}

public int getNumerator(){
    return Numerator;
}

public String toString(){
    return String;
}

}
Comment: 1. Why do use two separate Scanner objects to access the same standart input stream? It's not neccessary, you'd bettr use one Scanner.

2. May be you meant somethong like:
int x = rational.x;
int y = rational.y;
?
Because now you read two numbers, store them in rational and never use thar rational. Then you read additional two numbers from console and print them.

3. Conventions are to use Uppercase letter first in classes names
Comment: is it even going to work with 2 scanners ?
Comment: yes it runs and compile with two scanner because in my class is an int numerator and int denominator so best way i know how is to use two separate scanner for each because i need different inputs each time
Comment: just added my class file, it shows the reason why i added two scanner
Answer: instead of console.nextInt it should be console.nextInt()
You are unnecessarily creating two Scanner object
This should make more sense
System.out.println("Enter a number for the numerator");
int x = console.nextInt();
System.out.println("Enter a number for the denominator");
int y = console.nextInt();
rationalNumbers rational = new rationalNumbers(x,y); //follow class naming convention
System.out.println("Rational Number is: " +x+ "/" +y);

Comment: This is a bad idea. You should take the order of the method calls into consideration. If OP just edits his code according to your answer, he won't get the expected result
Comment: @stealthjong but what is the expected output?
Comment: Yup, that's what I meant.
Comment: i just added my class file, this is why i am using two scanner
Comment: so what is the problem if you do like what I told? btw where is your division logic you are just initializing the fields using constructor
Answer: nextInt() is a method of your Scanner objects (which has the side effect of blocking until a line is entered). In the call to the constructor of your rationalNumbers class, you reference it accordingly, so that's fine. In the definitions of x and y, you reference a nextInt member variable, which doesn't exist. You could call the method again, as in
int x = console.nextInt();
int y = console2.nextInt();

In this case, the user would have to enter two more numbers. You could do this before constructing the rationalNumbers object, and reuse x and y for your constructor arguments, in order to print the same numbers you passed to the rational object.
By the way, there's no need for two different Scanner objects in your example; you could replace every use of console2 with console for the same effect.


Understanding Dogbone contour example

Question: I am trying to understand example $6$ on the Wikipedia page http://en.wikipedia.org/wiki/Methods_of_contour_integration,
but one particular point has mystified me for hours. After it is shown that the line integral representing the left and right circles vanish as the radii get small, there is a skipped step that concludes that
$$\oint_{C}\frac{f(z)}{5-z} dz = (1-i)\int_{0}^{3}\frac{x^\frac{3}{4}(3-x)^{\frac{1}{4}}}{5-x}dx.$$
I understand that this is related to the fact that as the radii approach zero, the horizontal curves approach the branch cut and takes on different values, but I do not understand how to arrive at $1$ and $-i$ respectively.
I have read other examples of this such as the following link:
Evaluating the integral $\int_{-1}^{1} \frac{\sqrt{1-x^{2}}}{1+x^{2}} \, dx$ using a dumbbell-shaped contour
but there is consistently enough detail missing when discussing the branch point to leave me confused at my current level of knowledge in the subject.
Comment: Are you wondering where the "i" and "" in "$\mathrm{i} r^{3/4}(3-r)^{1/4}$" and "$r^{3/4}(3-r)^{1/4}$" are coming from?  ... or how they become "-iI" and "I", respectively?
Comment: The former. I don't know where the $i$ and the $1$ come from, I understand why it becomes $-I$ and $I$.
Answer: For $z^{3/4}$ the chosen branch of the logarithm admits arguments of zero and nearby, so this will contribute:  Set $z \rightarrow r \mathrm{e}^{\mathrm{i}\theta}$.  Then on $[0,3]$ we find $z^{3/4} \rightarrow r^{3/4}\mathrm{e}^{\mathrm{i}3\theta/4} \xrightarrow[\theta \rightarrow 0]{}r^{3/4} \cdot 1$.
However, this can't work for $(3-z)^{1/4}$ since we only allow arguments $\geq 0$ or $\leq 2\pi$.  Notice we have chosen to pay attention to $\arg(3-z)$ so the angles run "backwards" from the normal order, as indicated in the diagram with the "$2\pi$" and "$0$" seemingly in the wrong places around the loop at $z=3$.  For the upper branch, $\arg(3-z)$ is near $2\pi$ and we compute $(3-r)^{1/4}\exp(\frac{1}{4}\cdot \mathrm{i} \cdot 2\pi) = (3-r)^{1/4}\cdot \mathrm{i}$.  For the lower branch, $\arg(3-z)$ is near $0 = 0\pi$ and we compute $(3-r)^{1/4}\exp(\frac{1}{4}\cdot \mathrm{i} \cdot 0\pi) = (3-r)^{1/4} \cdot 1$.  We're literally plugging the $r \mathrm{e}^{\mathrm{i}\theta}$ into the branch choices, moving out the $\log(3-r)$ because $3-r$ is real and seeing what the $\frac{1}{4}$ does to the $\mathrm{i}\theta$ that didn't get moved out.
Not using the shortcut in the first paragraph, we would compute $r^{3/4}\exp(\frac{3}{4} \cdot \mathrm{i} \cdot (+0\pi)) = r^{3/4}\cdot 1$ and $r^{3/4}\exp(\frac{3}{4} \cdot \mathrm{i} \cdot (-0\pi)) = r^{3/4}\cdot 1$ by the same method as in the second paragraph.
Taking the products of the upper part with the upper part and the lower part with the lower part gives the stated results.
I'm pretty sure that the article's "$r^\frac{3}{4}\exp(3\frac{0\pi \mathrm{i}}{4})$" is a typo.  Or the "$r^\frac{3}{4}\exp(\frac{0\pi \mathrm{i}}{4})$" is.  Either they should both bear the "$\frac{3}{4}$" from the power of $z$ from which they come or neither should.  Perhaps the stray "3" should be a minus sign to indicate small negative arguments.  I'm not sure.  Either way, the result is dominated by the zero in the numerator, so the result is indistinguishable.
Comment: @JessicaK:  Yeah.  The "-z" causing the angles to run backwards bit me some years ago.  I'll *never* forget it now...  :-)
Comment: That used to confuse me as well. But it's not so much that the angle is running backwards as cutting out where $(3-z)$ is real and positive. And it's a little less confusing if you let $ \displaystyle f(z) = \frac{z^{3/4} (z-3)^{1/4}}{5-z} $ and use $0 < \arg(z), \arg(z-3) \le 2 \pi$. This also has the benefit of forcing $f(z)$ to be real valued on the real axis to the right of $z=1$, removing any ambiguities about the residue at infinity.
Comment: This explanation motivates the choice of the second branch cut much more now. I totally misinterpreted the image until you explained the angle running backwards. Everything is crystal clear now, thank you.

Understanding Dogbone contour example


Creating a drop down menu? How would i do it with my current code?

Question: The current html

    <link rel='stylesheet' type='text/css' href='css/styles.css' />

Home

Team

Team

Team2

Sponsors

First

Contact Us

Handouts

The css
#cssmenu ul {
  list-style-type: none;
  position: relative;
  display: block;
  height: 33px;
  font-size: 12px;
  background: url(../images/bg.png) repeat-x top left;
  font-family: Verdana, Helvetica, Arial, sans-serif;
  border: 1px solid #000;
  margin: 0;
  padding: 0;
  width: auto;
}
 #cssmenu li {
  display: block;
  float: left;
  margin: 0;
  padding: 0;
}
#cssmenu li a {
  float: left;
  color: #A79787;
  text-decoration: none;
  height: 24px;
  padding: 9px 15px 0;
 font-weight: normal;
}
#cssmenu li a:hover,
#cssmenu .active {
  color: #fff;
  background: url(../images/bg.png) repeat-x top left;
  text-decoration: none;
}
#cssmenu .active a {
  color: #fff;
  font-weight: 700;
}
#cssmenu ul {
  background-color: #B11718;
}
#cssmenu li a:hover,
#cssmenu li.active {
  background-color: #DE3330;
}

I tried following a tutorial online on how to do this and i heard that its hidden then appears in block.

Somewhat like this format if im not correct....
Can anyone help me turn the current menu into a possible drop down. I followed the tutorial but it wouldn't line up O.o
Please help. Sorry for the horrible question. Its more of how i would go about doing it.
Answer: Something like this?
#cssmenu ul {
  list-style-type: none;
  position: relative;
  display: block;
  font-size: 12px;
  background: url(../images/bg.png) repeat-x top left;
  font-family: Verdana, Helvetica, Arial, sans-serif;
  border: 1px solid #000;
  margin: 0;
  padding: 0;
  width: auto;
}
 #cssmenu li {
  display: inline-block;
  margin: 0;
  padding: 0;
}
 #cssmenu li ul {
     position: absolute;
    display: none;
}
/* Uncomment for vertical dropdown */
/*#cssmenu li ul li {
    display: block;
}*/
 #cssmenu li:hover ul {
    display: block;
}
#cssmenu li a {
    display: block;
  color: #A79787;
  text-decoration: none;
  padding: 9px 15px;
 font-weight: normal;
}
#cssmenu li a:hover,
#cssmenu .active {
  color: #fff;
  background: url(../images/bg.png) repeat-x top left;
  text-decoration: none;
}
#cssmenu .active a {
  color: #fff;
  font-weight: 700;
}
#cssmenu ul {
  background-color: #B11718;
}
#cssmenu li a:hover,
#cssmenu li.active {
  background-color: #DE3330;
}

http://jsfiddle.net/VUpFj/1/
Answer: Add this to your CSS
#cssmenu ul li ul {
  position: absolute;
  top: 33px;
  height: auto;
  margin-left: 0;
  display: none;
}
#cssmenu ul li:hover ul {
  display: block;
}
#cssmenu ul li ul li {
  display: block;
  float: left;
  clear: both;
}

and close
 inside

Team1

Team2


Interpreting Fourier transform frequency graph

Question: I've been trying to understand Fourier transform for some time now and I think I've perhaps finally got the idea now. What I would like to do now is to make an example of Fourier transform  for example for a time series signal and interpret the results and have someone confirm that I've got the idea correctly =)
I have sketched an example pictures of a time series for temperature and its Fourier transform :) Don't mind whether the numbers or graphs actually make any sense or not, that's not my point here. So here they are:

On the left I have a time series of temperature of something and on the right I have its frequency graph. Lets say the unit time in the time series is one hour $1h$. Now is my interpretation of the frequency graph here now correct:
The straight line in the frequency graph at point $(1Hz, 30)$ means that the temperature in the time series graph reaches a temperature of $30 \;C^{\circ}$ every hour, whereas the point $(3Hz, 60)$ means that the temperature in the time series reaches a temperature of $60 \;C^{\circ}$ every three hours? etc. Well actually this doesn't make any sense, but lets say it's from different galaxy ;D
Is my interpretation correct? Or how would one interpret the frequency graph? What would it tell us about the temperature time series?
Answer: If I remember things correctly, the interpretation would be that the temperature curve can be described as 4 functions:
<code>T1 = 30*sin(2*pi * t)
T2 = 15*sin(pi * t)
T3 = 60*sin(2*pi/3 * t)
T4 = 15*sin(pi/2 * t)
</code>
and the total temperature is T = T1 + T2 + T3 + T4
this, however, does not mean that the temperature reaches 60 degrees, it could be canceled out by one of the other functions, or alternatively surpass 60 degrees should the waves coincide. So your interpretation is partially correct, if the temp only followed T3 then yes the temp would reach 60 degrees every 3rd hour, but is not necessarily true in the general case because of the summation of the other functions. Hope you understand :)
// Jonathan
Comment: Glad I could help! yes it is the total sum that gives the temperature =) Yes there is a cyclical behaviour as you said but this is summed up with the rest of the cyclical temperatures
Comment: +1 Thank you for your help =) I think I got it =) I forgot the effect of summation of the terms x) What does for example the point $(1Hz, 30)$ then mean? Does it just say that there is a cyclical behaviour of temperature 30 degrees happening every hour?


How can I start a .NET application from Java on Linux, Mac and Windows?

Question: I want to start a .NET application (compatible with Mono) from the context of a Java environment.
My guess would be that I'd have to somehow figure out if mono is installed, find the location and start that using the .NET application path as a parameter.
But what is a robust way to do it? Or is there a better way?
Perhaps I should clarify the context: the Java part is running as a plugin in an environment with limited interaction possible, so I would really prefer to find a way without having to need a configuration file or an user-interface.
Comment: Does "have the path to the mono executor as a configuration option in the app" count?
Comment: Would really prefer it to be automatically.
Answer: If you already have .net/mono already installed and  you can double click on the exe file and it runs, then you could just use Desktop.open()
As easy as:
Desktop.getDesktop().open(file);

See here for more details: Using the Desktop API in Java SE 6

EDIT
I had to boot my Linux box where I have a mono application and this worked just great:
class Launch {
   public static void main( String ... arg ) {
      new ProcessBuilder("/usr/bin/myapp").start();
   }
}

Repeat, worked just great!
Comment: :-o  Oh, in that case you just have to: `new ProcessBuilder("/path/to/mono", "app").start();` and that's it. You cannot just guess where it could be installed. If you don't want to use a config file, then just hard code it.  As matter of fact, if the executable is in your $PATH invoking `new ProcessBuilder("monoexecutable", "app").start();` should be enough. Have you tried that already?
Comment: well this depends on your mono install, on my Linux system, you have to call mono and pass the app as argument.
Comment: +1 for mentioning how simple this could be if the mono executable is expected to be on the PATH. This should be preferred to having hard-coded paths in the Java app.
Answer: Interesting question! The answer is not that straightforward anyway
If you are running Linux
you definitely need Mono to run a CLR executable
If you are running Windows
you can run the CLR executable via shell OR use a local Mono installation (since Mono runs on Windows too), but there are very few reasons to run Mono on Windows
So, I think you should first detect the OS in Java (please don't ask me how to), and then if you are running Linux find Mono.
Mono's main executable is usually in /usr/bin, but is always in the $PATH so you can run mono Executable.exe from console. If you can't run such a command in Java, or Mono is not in path, then you need to run whereis mono to get the path to the executable.
No other ideas.
Comment: Is not that hard, mono and .net executables can be run with "ProcessBuilder" class, see my answer
Comment: Yes but Mono works like Java: you must run "mono App.exe" like "java -jar App.jar", so that's why he needs the path to mono executable
Answer: I don't know anything about .Net or Mono, but I would assume, it isn't much different to start a .Net application than regular one, or?
The class used to interface with the environment is java.lang.Runtime. It also allows you to execute commands. (.exec-methods)
In order to construct an appropriate command, the various functionality on java.lang.System will probably come in handy.
If this option is insufficient for the requirements of your particular situation, JNI might be your only option...


How to estimate the growth of the following sequence.

Question: $a_1=1,\forall n\ge 2(a_n=\sqrt{n+a_{n-1}})$.I want to find the smallest natural number n such that $a_n>10$.I find that the sequence is increasing,and I guess:For natural number k,there are only 2k items $a_{j+1},a_{j+2},\cdots,a_{j+2k}$ such that $k\le a_i<k+1,i=j+1,j+2,\cdots,j+2k$,but I have no idea how to prove it.I tried Mathematical induction but I failed ,Please help!I found the answer is 91  using python,but I can't prove it yet.I think the problem differs from Asymptotic behavior of the sequence $a_n=\sqrt{n+a_{n-1}}$ i focus on the specific properties while that problem cares about asymptotic behavior.
Comment: Check this: https://math.stackexchange.com/q/3304064/42969, or this: https://math.stackexchange.com/q/1237171/42969.
Comment: I think the inequalities in that question is not accurate enough for my question,as I only need to estimate finite items in the sequence.
Answer: I find another way to solve the problem.
Suppose $n\ge 91$,$$a_n = \sqrt{91+a_{n-1}}=\sqrt{91+\sqrt{90+a_{n-2}}}>\sqrt{91+\sqrt{90}}>10.$$Suppose $n \le 90$, $a_{90}=\sqrt{90+a_{98}}>a_{98}\Rightarrow a_{98}<10$.hence,$a_{90}=\sqrt{90+a_{98}}<\sqrt{90+10}=10$.
Though I know how to solve the problem, i wonder how to prove my guess that there are only 2k items in the sequence such that  integer part of them are k.


Can a single neural network be trained to play both sides of a board game?

Question: I am training a neural network to play tic-tac-toe. The input is the board (a vector of 9 doubles) and the output is a vector of Q-values (9 doubles).
The input vector is analyzed as follows: If a cell in the input vector is below -0.5 the cell is occupied by the Nought. If the cell is over 0.5 it is occupied by Cross and otherwise the cell is empty.
My goal is to create an AI that can play against a human as a Nought or as a Cross. I see several ways of trying to achieve this:

We are going to train only one model. The AI does not know if it is a Nought or a Cross. The training is executed as follows: The AI is going to play against itself by first picking an action according to the output of the current model. To get the reward for the action we have to predict how the opponent would respond to our action. We use our current model and pick an action to our opponent. After the opponent action is chosen we can calculate the reward and fit the model.
Same as above but instead of using the new state (state after our action) as such, we invert the new state (Noughts become Crosses and vice versa) before predicting the opponents action.
We are going to train two models. The AI knows which side it is playing and can use the specific model trained to play that side. The training is executed as follows: The Model for the Cross gets to start and pick an action. The action is appended to the state which is passed to the Noughts model so it can decide on an action. After Nougths model has chosen an action the reward can be calculated for Cross' model and the model can be fit against the new learned weights. Nought's model can be fit similarly after it has learned how Cross responded to its action.
Same as 1 but we fit the model for opponent moves too.
Same as 2 but we fit the model for opponent moves too.

Strategy 1 seems hopeless to me because the training happens from one side only and because of this I suspect that the chosen actions for the opponent are garbage.
I see strategy 2 as a little bit better than strategy 1 because the opponent moves are chosen from the inverted board, but this has the problem that the board states are never same as the states which the model was fitted for. (There is never a case where Cross would choose an action on a board having more noughts than crosses and be fitted for the chosen action. However the opponent actions are predicted on states like this)
Only minus I can think of with the strategy 3 is that AI has to know which side it is playing on to know which model to use to choose it's actions.
Strategies 4 and 5 seem like best choices (I don't know if one is better than other) and now we come to the question in the title. Is it possible for the AI to use only one model to play both sides or should I use two models? In addition: Which of the strategies would be the best choice? Or is there a strategy I have not thought of?
Answer: Your game is zero-sum - i.e. if one player wins, the other loses. Therefore if player A's reward is +1, player B's reward must be -1 and vice-versa.
This allows you to take a variant of your approach (2). But instead of inverting the board or all the reward values when the player turn switches, just have the network switch between maximising or minimising the action value. The agent does need to know whose turn it is taking in that case in order to know whether it wants to take the argmax or argmin action. But this does achieve your goal of having a single model which the agent is able to use to play as either X or O.
This is a common game theory approach, called minimax, and is used in many self-play reinforcement learning environments.
Technically minimax is a separate algorithm to RL, and can be used in tree search for game solutions with any heuristic. In the case of tic-tac-toe a minimax tree search will work fine without any interim heuristic at all, just the eventual win/draw/loss rewards, due to small size of search tree. Effectively RL learns useful heuristics so that a tree search can have less depth or be more efficient.
If you use just single-step greedy look ahead (an action value or afterstate value), then you can use minimax with RL and rely on the RL to learn accurate heuristics, no need for a tree search. In more complex games, then RL, minimax and tree search - plus alpha-beta pruning of the search for efficiency - can be used together.
Regarding the neural network, try first using a tabular Q-learning approach (enumerating all after states, and estimating value of each one separately), as that is more reliable and perfectly suitable when there are not many possible game states. This will demonstrate that you have the Q-learning set up correctly before you add the extra complication of a neural network. Neural networks used in Q-learning can be unstable and need careful tuning of hyper-parameters to work, so you'll want to be sure you are adding one into a process that already works.

Here is some pseudocode for a basic Q-learning algorithm that could be applied to any two player zero-sum game with perfect information, using notation similar to Sutton & Barto:

Input: Reward function $R(s) \in \mathbb{R}$, returning reward to player A when state changes to $s$
Input: Move function $M(s,p) \subset \mathcal{S}^{+}$, allowed next states when starting in state $s$ for player $p$
Parameters: learning rate $\alpha$, exploration rate $\epsilon$, discount factor $\gamma$
Initialise: $V(s) \in \mathbb{R}, \forall s \in \mathcal{S}$
Initialise: $V(s) \leftarrow R(s)$ for all terminal states.
Repeat (episode):
$\qquad$ Init state $S$
$\qquad$ Init player $P \leftarrow playerA$
$\qquad$ Repeat (step):
$\qquad\qquad$ If $P = playerA$, then:
$\qquad\qquad\qquad$ $S^* \leftarrow \text{argmax}_{s' \in M(S,P)} V(s')$
$\qquad\qquad$ Else:
$\qquad\qquad\qquad$ $S^* \leftarrow \text{argmin}_{s' \in M(S,P)} V(s')$
$\qquad\qquad$ $V(S) \leftarrow V(S) + \alpha(R(S) + \gamma V(S^*) - V(S))$
$\qquad\qquad$ $S' \leftarrow S^*$
$\qquad\qquad$ With probability $\epsilon$, $S' \leftarrow \text{random sample from } M(S,P)$
$\qquad\qquad$ Take the action:
$\qquad\qquad\qquad$ $S \leftarrow S'$
$\qquad\qquad\qquad$ If $P = playerA$, then:
$\qquad\qquad\qquad\qquad$ $P \leftarrow playerB$
$\qquad\qquad\qquad$ Else:
$\qquad\qquad\qquad\qquad$ $P \leftarrow playerA$
$\qquad$ Until $S$ is terminal

The reward function can just be +1 if player A wins, 0 for a draw, -1 if player B wins, occurring on the terminal state. Also, you can just set $V(s) \leftarrow 0$ for all states initially. Typically for a simple game like tic-tac-toe you might set $\epsilon = 0.1, \alpha = 1.0, \gamma = 1.0$
Comment: @Horttanainen: I put together a tabular Q-Learning TicTacToe agent in Python (because game-playing bots is something I am interested in, but for many things I have only done the theory). It works using the principle of alternating argmax/argmin as described in my answer. https://github.com/neilslater/game_playing_scripts/blob/master/tictactoe_q.py - feel free to use any parts of it to study or for your project. I think it proves the validity of the approach without NNs. Adding NNs will make your project harder initially, but extends better to more complex games later on.
Comment: I will checkout this minimax you mentioned and accept this as an answer if that turns out to be solution I need. If not I will be contacting you for further discussion. About first using Q-tables: I have everything else in place (batch replays, etc..) except for this learning strategy, so I would like to try out this first.


Problem with IF command in comment.html.twig

Question: I create a "select" field (field_points) in comment section that users rating my content and in "manage display" I set "key" for my field format.
5|Excellent
4|Good
3|No Idea
2|Bad
1|Very Bad

Now I use this code in comment.html.twig:
{% if content.field_points == 5 %}
   *****
{% elseif content.field_points == 4 %}
    ****
{% elseif content.field_points == 3 %}
    ***
{% elseif content.field_points == 2 %}
    **
{% elseif content.field_points == 1 %}
    *
{% endif %}

When I use this code nothing is displayed But when I use {{ content.field_points }} , print for example 5 ( 5 is field key ).
How can I fix this problem in drupal 8?
Answer: Use the comment entity to get the raw field value instead:
{% if comment.field_points.value == 5 %}
   *****
{% elseif comment.field_points.value == 4 %}
   ****

...

{% endif %}

This doesn't work with {{ content }}, because it contains a build array to render the fields.
Comment: This is only an example how to use the field value, I didn't code the complete logic.
Comment: Thanks but when I use {% if comment.field_points.value == 5 %} just show last comment rating and others not print. And when I use {% if comment.field_points == 5 %} all comment just show * in rating section


variavel intervalo hora php

Question: Gostaria de acrescentar esta variável intervalo a este código mas não estou conseguindo , se puderem me ajudar serei muito grato.
Achei este código na Internet e adaptei pro meu sistema, porém esbarrei nesta questão do intervalo.
date_default_timezone_set("Brazil/East");
$con=@mysql_connect("localhost","root","");
$bd=mysql_select_db("test",$con);
//$hora_inicio = $_POST['hora_inicio'];
//$hora_final = $_POST['hora_final'];
$hora_inicio = "07:00";
$hora_final = "10:00";
$int ="00:30";// variavel que define o intervalo
$ini = strtotime($hora_inicio);
$fim = strtotime($hora_final);
$atu = $ini;
$i = 1;
for ($atu = $ini ;  $atu <= $fim; $atu = strtotime('+30 minutes', $atu)) {
    $hr_agendamento = date('H:i', $atu);
    $sql = mysql_query("INSERT INTO agenda (id_agenda,hr_agendamento) VALUES('','$hr_agendamento')");
}
echo "agenda criada";

Comment: Possível duplicata de [Grade de horarios com PHP](https://pt.stackoverflow.com/questions/230713/grade-de-horarios-com-php)
Comment: mesmo assim a pergunta editada não sei bem o que pretendes queres inserir com um intervalo de tempo ?
Comment: precisa ser mais claro e específico no que queres
Comment: Creio que seja diferente pelo fato de estar querendo acrescentar o intervalo. mas de fato é o mesmo código.
Answer: Tente dessa forma:
<?php
date_default_timezone_set("Brazil/East");
$con = mysqli_connect("localhost", "root", "");
$bd  = mysqli_select_db("test", $con);

$hora_inicio = new DateTime('07:00');
$hora_final  = new DateTime('10:00');

while($hora_inicio->add(new DateInterval('PT30M')) < $hora_final) {
    $sql = mysql_query("INSERT INTO agenda(hr_agendamento) VALUES('".$hora_inicio->format('H:i')."')");
}

echo "Agenda criada!";

Answer: Para tornar dinâmico o intervalo basta utilizar a variável com apenas a quantidade de minutos, desta forma:
$int ="30";// variavel que define o intervalo em minutos

E no seu For, deve utilizar a variável $int no lugar do "30", concatenando com o +,  desta forma:
for ($atu = $ini ;  $atu <= $fim; $atu = strtotime('+'.$int.' minutes', $atu)) {

Substitua as linhas indicadas e faça o teste. Agora você pode trocar o valor da variável e irá gerar os horários no intervalo desejado.
Todo o código:
date_default_timezone_set("Brazil/East");
$con=@mysql_connect("localhost","root","");
$bd=mysql_select_db("test",$con);
//$hora_inicio = $_POST['hora_inicio'];
//$hora_final = $_POST['hora_final'];
$hora_inicio = "07:00";
$hora_final = "10:00";
$int ="30";// variavel que define o intervalo em minutos
$ini = strtotime($hora_inicio);
$fim = strtotime($hora_final);
$atu = $ini;
$i = 1;
for ($atu = $ini ;  $atu <= $fim; $atu = strtotime('+'.$int.' minutes', $atu)) {
    $hr_agendamento = date('H:i', $atu);
    $sql = mysql_query("INSERT INTO agenda (id_agenda,hr_agendamento) VALUES('','$hr_agendamento')");
}
echo "agenda criada";

Answer: Pode simplificar a criação dos periodos de datas ou horas com a classe DatePeriod no construção são necessários três argumentos o início do período, o intervalo e o fim.
Se possível migre seu código com as funções mysql_ para as mysqli_.
$inicio = new DateTime(@"07:00");
$fim = new DateTime(@"10:00");
$fim->modify('+30 minutes');

$periodo = new DatePeriod($inicio, new DateInterval('PT30M'), $fim);

foreach ($periodo as $item) {
    $sql = sprintf("INSERT INTO agenda (hr_agendamento) VALUES('%s')", $item->format('H:i'));
    mysql_query($sql) or print 'falha em: '. mysql_error();
}

variavel intervalo hora php


Force Java compiler not to inline final static fields

Question: I found that sometimes, if not always, static final fields will be inlined at the bytecode level. For some reason, I don't like this to happen. How do I switch this compile option off? Especially within Eclipse 4. (Without touching the source code.)
Thanks
Comment: What are you trying to accomplish by doing this?
Comment: You want the compiler to stop from replacing statically analyzable unmutable code? What for?
Comment: @Smutjie For part of some software engineering study using dynamic analysis. Using a static final field is different from hard-coding a constant in the program at source code level.
Comment: @NeplatnyUdaj I consider changing the compiler option and changing the source code are different...
Answer: I don't know of a compile-time options.
Puzzle 93: Class Warfare,  in the Java Puzzlers book discusses this.  There can be bugs produced since null does not get "inlined".
There's a workaround to refer to them via a do-nothing function, e.g.:
<code>public class Words {

    private Words() { }; // Uninstantiable
    public static final String FIRST  = ident("the");
    public static final String SECOND = ident(null);
    public static final String THIRD  = ident("set");

    private static String ident(String s) {
       return s;
    }

}
</code>
Obviously, this requires modifying your source code extensively.  Not what you wanted...
Either buy the book, or see here for a more complete discussion
Comment: Thanks. But I am just considering the compiler options if possible.


How many random cards picks with replacement are required?

Question:
You pick 1 card from a standard deck of 52 cards. Then put it back in, and pick a card again. Then put it back in and pick a card. etc...
How many times do you have to repeat in order to have a 90% chance of having picked (at least) 39 (75% of 52) different cards? [Or a deck of $k$ cards, a $P$ chance of picking at least $p$ x $k$ different numbers]
Alternatively (same math, but different visual): How many times do you have to roll a standard 6-sided die in order to have a 90% chance of having rolled (at least) 4 different numbers (66% of 6). [Or a $k$ sided die, $P$ chance of rolling at least $p$ x $k$ different numbers]

I'm at a complete loss as to how to figure out a formula (if one exists).  I was toying with this and the closest I can get to (through a decision tree) is where the amount of rolls "n" necessary are the solution to:

$$\frac{((1/6)^{n+1}-1)*((2/6)^{n+1}-1)*((3/6)^{n+1}-1)}{((1/6)-1)*((2/6)-1)*((3/6)-1)}>0.90$$

But there are already many problems:
(a) I have no idea if that's even remotely close
(b) I came across this "solution" by intuition/toying with decision trees
(c) I have no idea how to solve it, and most important of all,
(d) It would be unwieldy to use for a deck of $k$ cards...
So what's the actual mathematical solution here?
Comment: A simulation came up with values of 8 throws for the dice (about 0.92), and 82 picks for the cards (about 0.9), for the given requirement.
Comment: Yeah, that's what I got for dice using a decision tree; 8 rolls for 0.92.  My formula at the top is so very wrong.  The big question now is:  Can a formula be figured out that will allow to calculate based on any variables?  Also how are you simulating?  Doing a decision tree for 8 rolls of a die took me forever; can't imagine doing that for a deck....!
Comment: Hi, I tried getting a formula, going wrong somewhere. I simulated in J, an array programming language. Here's my [simulation code](http://pastebin.com/HN7HjuZB).
Answer: We can do this using exponential generating functions, and extract the $n^{th}$ coefficient to obtain an explicit formula.
For the simpler dice problem showing at least 4 distinct, the egf is:
$$
f(x)=(e^x-1)^4\, \binom{6}{4}+(e^x-1)^5\, \binom{6}{5}+(e^x-1)^6\, \binom{6}{6}
$$
From that, we need the $n^{th}$ coefficient, times $n!$ to get the number of possible permutations of dice rolled having at least
4 distinct numbers.
The explicit formula for the probability is then:
$
\mathbb{P}_{\text{dice}}(n)=\dfrac{6^{n} - 20 \cdot 3^{n} + 45 \cdot 2^{n} - 36}{6^n}
$
We may verify with the simulation value in the comment:
$$
\mathbb{P}_{\text{dice}}(8)=\dfrac{21665}{23328}\approx 0.928712277091907
$$
Similarly, the egf for the cards showing up at least 39 distinct is:
$$
g(x)=(e^x-1)^{39}\, \binom{52}{39}+(e^x-1)^{40}\, \binom{52}{40}+(e^x-1)^{41}\, \binom{52}{41}+\cdots +(e^x-1)^{52}\, \binom{52}{52}
$$
This also yields a formula, a big one though.
$\displaystyle
\mathbb{P}_{\text{cards}}(n) = \left(52^{n} - 1768966344600 \cdot 38^{n} + 62739339688480 \cdot 37^{n} -\\
1088135422722075 \cdot 36^{n} + 12289529480155200 \cdot 35^{n} -\\
101559306120727000 \cdot 34^{n} + 654255740482999200 \cdot 33^{n} -\\
3418486244023670820 \cdot 32^{n} + 14883205416157478400 \cdot 31^{n} -\\
55050947306355218400 \cdot 30^{n} + 175524759527509392000 \cdot 29^{n} -\\
487812560853536518600 \cdot 28^{n} + 1192036512340278329088 \cdot 27^{n} -\\
2578925146890025231200 \cdot 26^{n} + 4966818801417826371200 \cdot 25^{n} -\\
8552557885094471430000 \cdot 24^{n} + 13212227353525252416000 \cdot 23^{n} -\\
18359490926669465336400 \cdot 22^{n} + 22992910837954169112000 \cdot 21^{n} -\\
25986779436646118215125 \cdot 20^{n} + 26525580286209753840000 \cdot 19^{n} -\\
24458145352137523026000 \cdot 18^{n} + 20365149599330835499200 \cdot 17^{n} -\\
15299575772224554447000 \cdot 16^{n} + 10355529547357630272000 \cdot 15^{n} -\\
6301884757438031580000 \cdot 14^{n} + 3438566862520033641600 \cdot 13^{n} -\\
1676301345478516400280 \cdot 12^{n} + 726851531914803859200 \cdot 11^{n} -\\
278750034773449439200 \cdot 10^{n} + 93885336491458512000 \cdot 9^{n} -\\
27525473653177609200 \cdot 8^{n} + 6945495860873489920 \cdot 7^{n} -\\
1486298366966813400 \cdot 6^{n} + 264486363173978400 \cdot 5^{n} -\\
38084739795272625 \cdot 4^{n} + 4263714309441600 \cdot 3^{n} - \\
348203335271064 \cdot 2^{n} + 18452746967200\right)/52^n
$
and
$$\mathbb{P}_{\text{cards}}(82)\approx 0.903730370831740$$
Update:
We may rewrite the formula in general form and get the probability for the values in the asked in the comment:
$\displaystyle a(k,m,n) = \binom{k}{m}\cdot \sum_{i=0}^{m} (-1)^i \, \binom{m}{i}\cdot (m-i)^n$
$\displaystyle \mathbb{P}_{cards}(811)=\dfrac{1}{640^{811}}\sum_{m=450}^{640}a(640,m,811)\approx 0.901973726672271$
Comment: E.g. consider a n letter permutation from 4 characters, where at least each of them are to be present, the egf for that $(e^x-1)^4$, and those 4 characters are chosen from 6 available characters. Hence the $6 \choose 4$ part in that.
Comment: So in other words, there is no specific formula, and the formula that needs to be generated gets exponentially bigger?  So there's no way of calculating 90% chance of getting 450 different cards out of a 640-card deck?
Comment: Due to the nature of the problem, I don't think there is a simple formula. Though it's possible to rewrite it as a summation involving binomials. See my update to the answer.
Comment: can you add a sentence or two on how you got the formula for the egf, f(x)?


The poles of order $m$ of $g$ are zeros of order $2m$ of $f$

Question: Suppose that $\phi _{i},$ $\left( i=1,2,3\right) $ triple of holomorphic
complex functions satisfy $\left\{
\begin{array}{c}
\phi _{1}^{2}+\phi _{2}^{2}+\phi _{3}^{2}=0 \\
\left\vert \phi _{1}\right\vert ^{2}+\left\vert \phi _{2}\right\vert
^{2}+\left\vert \phi _{3}\right\vert ^{2}\neq 0%
\end{array}%
\right. $.
Define $\left\{
\begin{array}{c}
f=\left( \phi _{1}-i\phi _{2}\right)  \\
g=\frac{\phi _{3}}{\phi _{1}-i\phi _{2}}
\end{array}
\right. $
and show that $g$ is meromorphic and $f$ is holomorphic and that the poles of
order $m$ of $g$ are zeros of order $2m$ of $f$.
I already tried using the equivalences for poles and zero of a function but
I could not.
Comment: If $g$ is holomorphic then surely it has no poles? Do you mean meromorphic?
Comment: @George Sorry, the text is misspelled. I'll edit.
Comment: While you're editing maybe also take care of "trilpe"
Answer: We compute
$$g^2f=\frac{\phi_3^2}{\phi_1-i\phi_2}=-\frac{\phi_1^2+\phi_2^2}{\phi_1-i\phi_2}=-(\phi_1+i\phi_2) $$
and see that this is holomorphic. To show that every pole of order $m$ of $g$ is a root of order $2m$ of $f$, it suffices to show that the right hand side has no zero that is also a pole of $g$.
Indeed, if $\phi_1(z)+i\phi_2(z)=0$ and $\phi_1(z)-i\phi_2(z)=0$, then $\phi_1(z)=\phi_2(z)=0$, hence $\phi_3(z)=0$ by the first condition, contradicting the second condition.
Comment: I'm sorry, but because that to show that every pole of order is a root of order $2m$ of $f$ it suffices to show that the right hand side has no zero that is also a pole of $g$?
Comment: @ Hagen, are you there?


Create a RSS using Views of a content type

Question: How to configure Views to display a RSS feed of certain content types, which contains several articles?
I would like the RSS to have 1 news feed for 1 content type. How to config it?
I can only set the feed to display all article titles in 1 news feed, which does not make sense.
The sample XML is like this:
<news>

        <title>Some Title Here</title>
        <content><![CDATA[Some Contents here]]></content>
        <pubDate>2011-09-20 10:01</pubDate>

        <title>Another Title Here</title>
        <content><![CDATA[Other Contents here]]></content>
        <pubDate>2011-09-20 11:01</pubDate>

</news>

where the 2 articles above is in certain content type.
Comment: Not very clear. Could you provide a better description (or an example) of what you're trying to achieve?
Comment: @MaciejZgadzaj: I have updated the question for further explanation. Please see if it is clear or not.
Comment: Personally I'm still not sure what you're looking for. You're saying you "would like the RSS to have 1 news feed for 1 article", but from your example it seems to me that you want do have one feed for one content type (listing all/specific number of nodes from this content type).
Comment: @MaciejZgadzaj: Yes, to correct my question, I would like to have 1 news feed for 1 content type. Can you explain to me how can I do it?
Answer: Following comment exchange under the question - just add a new view showing "content" of type <your_type>, tick "Create a page" and "Include an RSS feed" underneath. This will give you a feed with list of all nodes of a specific type. Then just play with all other settings to get what you need, and that's it.
Answer: Currently there is only to create a custom RSS templates from views.  Unfortunately not allot of data is passed on, but I believe content types do pass on, though you would want to order the RSS view by content type first.


Unexpected use of polynomials in combinatorics

Question: Can someone please post some (relatively easy, say high school level) combinatorial problems which can be solved with polynomials but NOT generating functions.
Related to this post in ME.SE.
Comment: @Aqua: Not sure. Generally, applications of the Combinatorial Nullstellensatz can be restated in terms of finite differences, but someone will have to find the time to actually do that :)
Comment: Could you post that as an answer with a solution please? @lulu
Comment: For example, consider the complete graph with $3$ nodes. It is easy to see that it is not $2$-colorable. The problem can be reduced to solving [this](https://i.stack.imgur.com/qqwfC.png) system of linear and quadratic equations. If one removes one edge, one obtains a system with one fewer linear equation than before and one can plot the planes and quadratic surfaces to show that it has a solution.
Comment: How about:  "Is it possible to weight two dice (possibly unequally) in such a way that every sum from $2$ to $12$ is equally likely?"  You can do that via polynomials.
Comment: Gladly, but not now (about to sit down to dinner).  I'll post problem and solution this evening, a couple hours from now.
Comment: Is deciding graph-colorability via systems of polynomial equations too advanced? High school students should be used to solving systems of *linear* equations.
Comment: Uhh, please post that !!! I'm not sure, have to see. I know nothing about it but sounds very interesting. @RodrigodeAzevedo
Comment: You may also want to take a look at this [answer](https://math.stackexchange.com/a/1985206/339790) on permutations and systems of polynomial equations. Pretty figures included.
Comment: Do you accept the trick where you bijectively prove a binomial identity for positive $n$ and then apply it to negative $n$ because both sides are polynomials in $n$ ? If so, I have several examples.
Comment: Yes of coruse @darijgrinberg And I have a question for you. Can this be writen in more HS manner? https://artofproblemsolving.com/community/c6h147163p11655231
Comment: I mean it looks very nice but I don't understand a thing. @darijgrinberg
Comment: @Aqua sorry, I've been busy. have you seen the proof of finite field kakeya? or the resolution of the cap set problem?
Comment: A fine question, but I think site/network hygiene necessitates cross linking.
Answer: Problem:  Is it possible to weight two dice (possibly unequally) in such a way that every sum from $2$ to $12$ is equally probable?
The Answer is No.
Comment:  I set this problem for high school students a few years back. These were students who did well at competition style problems. They found this one difficult, but were able to make very good progress on it, and arrived at the first proof entirely on their own. They got the second after the basic idea was proposed to them. It's not intended to be an easy problem and it may well be more difficult than you were looking for.
Motivating Example:  to see that you can not do this with equally weighted dice, suppose you could and let $p_i$ be the probability a given die comes up $i$.  Then $p_1^2=p_6^2=\frac 1{11}\implies p_1=p_6=\sqrt {\frac 1{11}}$ But then the probability of getting a $7$ is at least $2p_1p_6=\frac 2{11}$, a contradiction.
Direct proof (no polynomials):  Say the probabilities for the first die are $p_i$ and for the second $q_i$.  Then $p_1q_1=\frac 1{11}=p_6q_6$.  But then we can get a lower bound on the probability of throwing a $7$ as $$\text {Prob}(Sum = 7)≥p_1q_6+p_6q_1=p_1\times \frac {1}{11p_6}+p_6\times \frac {1}{11p_1}=\frac 1{11}\times \left(\frac {p_1}{p_6}+\frac {p_6}{p_1}\right)≥\frac 2{11}$$ so we reach the same contradiction as in the equally weighted case.  Here, of course, we have used the fact that $x+\frac 1x≥2$.
Proof using polynomials:  Let the $p's$ and $q's$ be as above.  Define two polynomials $$P(x)=\sum_{i=1}^6p_ix^i\quad \&\quad Q(x)=\sum_{i=1}^6q_ix^i$$
Note that both $P(x), Q(x)$ are divisible by $x$ and that $P(1)=Q(1)=1$.
If the weightings were to work we'd have the product $$P(x)Q(x)=\frac 1{11}\sum_{i=2}^{12}x^i=\frac {x^2}{11}\frac {x^{11}-1}{x-1}$$
However, this is impossible.  Indeed, factoring out the factors of $x$ from $P(x),Q(x)$ we get two polynomials of degree $5$ each (noting that neither $p_6$ nor $q_6$ can be $0$).  As $5$ is odd, these must have at least one real root each...but $x^{11}-1$ has no real root other than $1$ (which is not a root of $P(x)$ nor $Q(x)$).
Comment: Neat but this _is_ a generating function...  :)
Comment: This is really great.
Comment: @JeanMarie  Well, sure.  If, say:  One die is normal and the other comes up $1,6$ with equal odds then everything is equiprobable except for $7=6+1=1+6$ which is twice as likely. The first proof I provided sort of shows that this is optimal, at least in some sense.  And, of course, you can try to optimize for, say, least squared distance to $\frac 1{11}$...I forget what dice look best for that
Comment: @JeanMarie  To be clear, the pair I mentioned might be optimal for least square, I just forget.  Been a while since I thought about it.
Comment: I have a subsidiary question : nevertheless, is it possible to be rather close to equidistribution ?
Comment: @lulu Thanks for your replies.
Answer: Here is an example I was talking about:
We have $2n$ different numbers $a_1,...a_n, b_1,...b_n$. A table $n\times n$ is divided on $n^2$ unit cells and in cell $(i,j)$ we write a number $a_i+b_j$. Suppose that all products of numbers written in cells in each column are the same. Prove that then all products of numbers written in cells in each row are the same.
Idea for a solution: Observe a polynomial $$P(x) = (x+a_1)...(x+a_n)-(x-b_1)...(x-b_n)$$
Answer: There is a classical trick for deriving combinatorial identities that proceeds as follows:

Find some combinatorial identity that you can prove for all $n \in \mathbb{N}$ and that has the form $P\left(n\right) = Q\left(n\right)$, where $P$ and $Q$ are two fixed polynomials. For example, the identity $\dbinom{n}{a}\dbinom{a}{b} = \dbinom{n}{b}\dbinom{n-b}{a-b}$ (for fixed nonnegative integers $a$ and $b$) fits this description (with the polynomials $P$ and $Q$ given by $P\left(x\right) = \dbinom{x}{a}\dbinom{a}{b}$ and $Q\left(x\right) = \dbinom{x}{b}\dbinom{x-b}{a-b}$); it can be proved for all $n \in \mathbb{N}$ by double-counting the number of ways to choose two nested subsets $B \subseteq A \subseteq \left\{1,2,\ldots,n\right\}$ with $\left|A\right| = a$ and $\left|B\right| = b$.
Recall the fact that if two polynomials (over $\mathbb{Q}$ or $\mathbb{R}$) are equal on infinitely many points, then they are identical. In Step 1, you have shown that the polynomials $P$ and $Q$ are equal on infinitely many points (namely, on all $n \in \mathbb{N}$). Thus, they are identical. Hence, $P\left(n\right) = Q\left(n\right)$ holds not only for all $n \in \mathbb{N}$, but also for all $n \in \mathbb{R}$.
(Optional) This allows you to substitute $-n$ for $n$ in the identity. If you want, you can rewrite the resulting identity by getting rid of negative numbers on top of binomial coefficients (using the upper negation formula $\dbinom{-n}{k} = \left(-1\right)^k\dbinom{n+k-1}{k}$ for all $k \in \mathbb{Z}$). For example, if you substitute $-n$ for $n$ in the above-mentioned identity $\dbinom{n}{a}\dbinom{a}{b} = \dbinom{n}{b}\dbinom{n-b}{a-b}$, then you obtain $\dbinom{-n}{a}\dbinom{a}{b} = \dbinom{-n}{b}\dbinom{-n-b}{a-b}$; then, using upper negation, you can rewrite this as $\left(-1\right)^a \dbinom{n+a-1}{a} \dbinom{a}{b} = \left(-1\right)^b \dbinom{n+b-1}{b} \left(-1\right)^{a-b} \dbinom{n+b+a-b-1}{a-b}$. Okay, this time you haven't found anything new (you can easily derive this new identity directly from the original one), but often you do.

Here is another example. For any nonnegative integers $m$ and $i$, we let $\operatorname{sur}\left(m,i\right)$ denote the number of surjective maps from $\left\{1,2,\ldots,m\right\}$ to $\left\{1,2,\ldots,i\right\}$. (The cognoscienti will recognize this number as $i! {m \brace i}$, where ${m \brace i}$ is a Stirling number of the second kind. More important to us is the obvious fact that $\operatorname{sur}\left(m,i\right)$ counts not only the surjective maps from $\left\{1,2,\ldots,m\right\}$ to $\left\{1,2,\ldots,i\right\}$, but also the surjective maps from any given $m$-element set to any given $i$-element set.) It is easy to prove (by double-counting) that
\begin{align}
n^m = \sum_{i=0}^m \operatorname{sur}\left(m,i\right) \dbinom{n}{i}
\label{darij1.eq.nmsur1}
\tag{1}
\end{align}
for any $n \in \mathbb{N}$ and $m \in \mathbb{N}$.
(Indeed, you can double-count the number of all maps from $\left\{1,2,\ldots,m\right\}$ to $\left\{1,2,\ldots,n\right\}$. The left hand side is the obvious count; the right hand side counts them by first choosing their image and then mapping $\left\{1,2,\ldots,m\right\}$ surjectively onto that image.)
Now, the identity \eqref{darij1.eq.nmsur1} has the form $P\left(n\right) = Q\left(n\right)$ for two polynomials $P$ and $Q$: namely, for $P\left(x\right) = x^m$ and for $Q\left(x\right) = \sum_{i=0}^m \operatorname{sur}\left(m,i\right) \dbinom{x}{i}$. Therefore, the above trick (specifically, its step 2) shows that it must hold not only for all $n \in \mathbb{N}$, but also for all $n \in \mathbb{R}$. In particular, we can substitute $-n$ for $n$ into it, and thus obtain
\begin{align}
\left(-n\right)^m = \sum_{i=0}^m \operatorname{sur}\left(m,i\right) \dbinom{-n}{i} .
\end{align}
In light of the upper negation formula $\dbinom{-n}{i} = \left(-1\right)^i\dbinom{n+i-1}{i}$, we can rewrite this as
\begin{align}
\left(-n\right)^m = \sum_{i=0}^m \operatorname{sur}\left(m,i\right) \left(-1\right)^i \dbinom{n+i-1}{i} .
\end{align}
Multiplying this by $\left(-1\right)^m$, we obtain
\begin{align}
n^m = \sum_{i=0}^m \operatorname{sur}\left(m,i\right) \left(-1\right)^{m-i} \dbinom{n+i-1}{i} .
\end{align}
Do you see how to prove this combinatorially? (Note that the particular case $n = 1$ of this identity takes the particularly simple form $\left(-1\right)^m = \sum_{i=0}^m \operatorname{sur}\left(m,i\right) \left(-1\right)^{m-i}$, since $\dbinom{1+i-1}{i}=\dbinom{i}{i}=1$. This identity is equivalent to Theorem 2.2.2 in Bruce Sagan, Combinatorics: The Art of Counting, version 2020-01-20, where it is proved using a sign-reversing involution. Perhaps the same method applies to the general case; but it is not as easy as ours!)
Note that, while we have generalized \eqref{darij1.eq.nmsur1} to all $n \in \mathbb{R}$, we cannot generalize \eqref{darij1.eq.nmsur1} to all $m \in \mathbb{R}$, since $\operatorname{sur}\left(m,i\right)$ is not a polynomial in $m$ (and also because $m$ appears as a summation bound and as an exponent in \eqref{darij1.eq.nmsur1}).
More examples of how this trick can (and cannot) be used are found in §2.6 (particularly §2.6.4 and §2.6.5) of my Enumerative Combinatorics notes.
Comment: Yes, this is very nice trick to prove formulas
Answer: I would consider the chromatic polynomial of a graph a combinatorial use of a polynomial, since it counts the number of colourings in a graph.
Given a graph, $G$, the chromatic polynomial, $P(G, k)$ counts the number of ways you can $k$-colour $G$. This is not a generating function because the values of $P(G, k)$ encode the counts not the coefficients.
Answer: Here is another example:
We start with any finite list of distinct positive integers. We may replace any pair $n$, $n + 1$ (not necessarily adjacent in the list) by the single integer $n−2$, now allowing negatives and repeats in the list. We may also replace any pair $n$, $n + 4$ by $n − 1$. We may repeat these operations as many times as we wish. Either determine the most negative integer which can appear in a list, or prove that there is no such minimum.
Answer: Have You heard about rook polynomials?
Link to wikipedia: https://en.wikipedia.org/wiki/Rook_polynomial
Link to reasonable question on mathstack:
Use of rook polynomials
One more link with nice explanation:
https://www.d.umn.edu/~jgreene/Combinatorics/Fall_2015/Rook_polynomials.pdf
Answer: I'm very surprised no one has named Vandermonde's Identity.
$$\sum_{j=0}^m \binom{a}{j}\binom{b}{m-j} = \binom{a+b}{m}$$
It is quite a beautiful exercise to convince a high-school student that polynomials can be a powerful tool in combinatorics.
Of course, proving that the above identity is true can be done combinatorially interpreting that you have to count the number of ways of picking $m$ balls, of which exactly $a$ are red and $b$ are blue (and they are all labeled, say).
The polynomials may arise naturally if the students already know the Binomial Theorem. If you try to compute $(1+x)^{a+b}$ using that, then the coefficient of $x^m$ is exactly $\binom{a+b}{m}$. Also, if you do the same with $(1+x)^a (1+x)^b$ and use the convolution formula for the product of polynomials, this gives you the "polynomial proof".
Answer: Here is another one:

Given two sequences of natural numbers $\{a_k\}$ and $\{b_k\}$, $k=1,\ldots,n$ (with non-identical sets of elements) such that the sets of their pairwise sums $$\{a_1+a_2,a_1 + a_3,\ldots, a_{n-1}+a_n\}$$ and $$\{b_1+b_2,b_1 + b_3,\ldots, b_{n-1}+b_n\}$$ coincide, show that $n=2^m,\ m\in\mathbb{N}.$
Comment: Thank you, yes this is also very nice and unexpected (at least for me) application of polynomials.
Answer: See Lucas's Theorem. There is one proof with groups and another with polynomials. Both are very nice. (There is a third by induction but it is pretty bad.)
Comment: Please expand on the theorem and the proof(s) you have in mind.


Clonar Header LocalStorage

Question: Tenho um HEADER e quero clonar ele em outras paginas HTML, estou Tentando pela função cloneNode();
porém não estou conseguindo resgatar o valor dele na outra pagina HTML usando o localStorage
Comment: Não use o processo sugerido na resposta pois abre brechas de segurança a ataques cross-site scripting (XSS), esse processo deve ser automatizado no lado do servidor. Para cada servidor sua linguagem hospedeira oferece ferramentas para realizar essa tarefa.
Comment: Pergunto, existe algum motivo para fazer isso do lado do cliente? **Se o motivo for razoável** posso criar uma resposta mostrando como fazer isso usando Webcomponents.
Answer: Não é possível clonar um node mas podes clonar o HTML desse elemento.

    Hello

Comment: Não que seja o processo correto de fazer isso, o que não é. Mas for para fazer essa gambiarra não precisa clonar o elemento se o que interessa é apenas o fragmento de código HTML, https://jsfiddle.net/fnamuche/

Clonar Header LocalStorage


Possible to point wildcard subdomain to top level domain via DNS settings?

Question: Is it possible to point wildcard subdomains to a top level domain via DNS settings alone?
I would like to have *.mydomain.com redirected to mydomain.com.
mydomain.com is hosted on a 3rd service. I do not have access to any of my site's apache configuration files.
Thank you,
Malcolm
Comment: Can you clarify what the desired result is? You can have a wildcard in DNS but that will just make all those names resolve to some address. In the context of a web site you would still most likely want to do a http permanent redirect to have everyone sent to the same address.
Answer: At a DNS technical level, sure you can have:
*.example.com. IN CNAME example.com.

Although a better configuration would be:
$ORIGIN example.com.
@      IN SOA ( ... )
       IN A n.n.n.n     ; put your server IP here
www    IN A n.n.n.n     ; and here
*      IN CNAME www

That will ensure that people doing a lookup for the SOA or MX records of foo.example.com don't get an unexpected answer.
However if your web server isn't set up to expect the wildcarded host names that people start using to point at, they'll just get error pages.
For that to work you need something like:
<VirtualHost .....>
ServerName wwww.example.com
ServerAlias example.com
ServerAlias *.example.com

</VirtualHost>

and that has to be in the main config, not in a .htaccess file.
Alternatively, if the intent is that all wildcard subdomains end up at the same site, use an HTTP-level redirect such that all URLs end up with the client redirected to a preferred canonical URL (e.g. either www or the one without any prefix)
Comment: Doing as explained here will leave visitors on whatever address they entered. Typically the desired result for web sites is to have  one canonical name.  (As for the "better configuration", why not skip the use of `CNAME` altogether?)
Comment: @HåkanLindqvist yes, a redirect to the canonical site might be better, but why downvote for otherwise still useful _supplemental information_.
Comment: In retrospect I think you're right, I was overly set on it being a complete answer. My bad.
Answer: Assuming that you can without fail set wildcard (*.example.com) in DNS on your domain (if not, you can move your domain to for example freedns service).
DNS service only translate domain to IP, i'ts not related to any service (http, ftp, smtp) so it can't redirect http request from one to different domain.
But you can:

Point *.example.com to some other web/http server that supports http wildcard and redirect.
Contact your http service provider to setup wildcard on their server

Additionally, most of the popular/used control panels (cPanel, DirectAdmin, ...) supports wildcard so maybe you can set this up yourself.
Answer: If your DNS provider supports wildcard CNAME then this should work. See Question 44618