Why are there multiple modern era styles?

Question: I was wondering why there are multiple genres of modern era music, for example Minimalism, Impressionism, Expressionism, Serialism and Futurism.
This variety of different styles wasn't present during the earlier periods, i.e. the Baroque, Classical and Romantic eras.
Why did this change in the 20th century?
Comment: I'd like to see you argue with an 18th-century resident that their era doesn't have a multitude of musical styles! They'd probably think you were having them on.
Comment: Among modern (or at least 20th-21st-century) genres, there's also jazz (music theory textbooks will occasionally actually give a shout-out to this one), pop, rock, heavy metal, ragtime, EDM, other electronic music genres, reggae, movie soundtrack, the list goes on....
Comment: I think that the sheer total population of the planet has to be given some credit here, too.
Answer: Why the 20th-century explosion of styles/genres
Four major developments happened as the 20th century approached and developed through WWII:

City-States gave way to the modern conception of Countries. Along with that, monarchies gave way to more democratic forms of rule.
Because of the "softening" of border, and the development of communication and travel, it became easier for composers to explore formerly unfamiliar types of music.
Among Western composers (and perhaps others, but my knowledge is limited to the West), there was a feeling that Tonality had run its course, and they were searching for new models for creating music.
Especially in the wake of WWII, Western composers (again, within the limits of my experience) were specifically looking to reject the tenets, musically and morally, of earlier music.

All of these factors combined to give composers immense flexibility to experiment and seek new, idiosyncratic ways of creating and organizing music,  pushing the boundaries of what could be considered music, and debating the underlying purpose of music.
Why the prior relative limitation of styles/genres
In earlier times, the conception of art, and what could be considered art, was more limited. There were specific aims toward "beauty" and "structure", and these were culturally defined on comparatively rigid terms.
In Western music, for many centuries, The Church gave strict guidelines for the parameters within which music could be created. The system which eventually emerged out of these strictures and traditions, Tonality, plus the pressures of fashion, status, and limited ability to absorb other musics, kept the genres relatively limited.
However, it is also the case, that differences between regional musics were more starkly defined. And what we now lump together as a sort of single "classical" genre, was, at the time, considered highly different musics. Sonatas, Oratorios, Chorales, Symphonies, many different types of dances, Masses, ... were all considered highly distinct, each adhering to certain conventions.
Conclusion
It's perhaps misleading to say that there are more different styles/genres today than "yesterday." While it may be true, there was still a plethora of differentiated musics historically. Historically, the styles/genres tended to be defined more by function and location, plus form; whereas, now genres are somewhat more defined by form, plus function and location.
So the number of styles/genres may be similar or different, but they are defined on different terms, and access to them is far more available now than "then".
Answer: You only have a point if you think that "baroque" is one style. In truth there are clear differences between English, French, Italian baroque. Both in writing and in performing.
But yeah, modern life is a lot faster paced, so styles can develop on the square millimeter. Also, people are a lot more obsessed with naming styles. Breakbeat vs broken beat, seriously?
Answer: The pace of change of musical styles has picked up over time.  Way back, a style lasted for 300 years.  Then 150 years.  Then 75 years.  I guess this is due, as Aaron explained, to increased cultural exchange over time.
It's not just music, though.  Music history is connected to the history of other arts, e.g. painting, architecture.
Note that as tonality expanded (e.g. more complex chords and harmonies), and as tonality started to be rejected, the possibilities became more varied and numerous.  This helps us understand that some composers leaned towards expressionism, some towards impressionism, etc.
Also take into account that a composer experimenting in a particular style had an easier time finding like-minded pioneering composers, due to increased travel and cultural exchange.
Comment: Rather like just about everything else has 'accelerated' (and diversified) - technology, industry, medical advances, etc. Labelled 'progress', not always literally so...
Answer: That's an interesting view, but perhaps this wouldn't be true if you looked across the globe.  Certainly the styles of music in Japan, China, Africa, etc. were quite different than the classical origins in Europe.
I also think there weren't the variety of instruments available that also lends itself to music development.  The mention of EDM makes me think that style of music wasn't even possible before the availability of electronic music and amplification.
Comment: They were different from European styles, but they were similar to each other, within each culture, AFAIK. Nowadays even within subcultures you can find genre and style competition.
Comment: Yes, likely a result more of travel and communication.  I suppose literature, science, etc. all would track something similar.  Languages can die out as populations are no longer isolated and absorb into a larger population, so less variety.


Multiple Y-axes with Spines on Multiple Bar Plot

Question: I have some data that I would like to represent on a multiple Y-axes bar plot. Currently, I am only able to represent them on a line plot as shown in fig 1.

Below is my code:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

def make_patch_spines_invisible(ax):
    ax.set_frame_on(True)
    ax.patch.set_visible(False)
    for sp in ax.spines.values():
        sp.set_visible(False)

dataset = pd.read_csv('Model Selection (Humidity)_csv.csv')

feature1 = dataset.iloc[:5, 2].values
feature2 = dataset.iloc[:5, 3].values
feature3 = dataset.iloc[:5, 4].values
feature4 = dataset.iloc[:5, 5].values
xaxis = dataset.iloc[:5,1].values

fig, f1 = plt.subplots(figsize= (25,15))
fig.subplots_adjust(right=0.75)

f2 = f1.twinx()
f3 = f1.twinx()
f4 = f1.twinx()

# Offset the right spine of par2.  The ticks and label have already been
# placed on the right by twinx above.
f3.spines["right"].set_position(("axes", 1.1))
f4.spines["left"].set_position(("axes", -0.1))

# Having been created by twinx, par2 has its frame off, so the line of its
# detached spine is invisible.  First, activate the frame but make the patch
# and spines invisible.
make_patch_spines_invisible(f3)
make_patch_spines_invisible(f4)

# Second, show the right spine.
f3.spines["right"].set_visible(True)
f4.spines["left"].set_visible(True)
f4.yaxis.set_label_position('left')
f4.yaxis.set_ticks_position('left')

p1, = f1.plot(xaxis, feature1, 'r-', label="Adjusted R2")
p2, = f2.plot(xaxis, feature2, 'g-', label="Max Absolute Error")
p3, = f3.plot(xaxis, feature3, 'b-', label="Max Error")
p4, = f4.plot(xaxis, feature4, 'y-', label="Root Mean Square Error")

f1.set_ylim(0, 1)
f2.set_ylim(0, 2)
f3.set_ylim(7, 25)
f4.set_ylim(1, 3)

f1.set_xlabel("Model")
f1.set_ylabel("Adjusted R2")
f2.set_ylabel("Max Absolute Error")
f3.set_ylabel("Max Error")
f4.set_ylabel("Root Mean Square Error")

f1.yaxis.label.set_color(p1.get_color())
f2.yaxis.label.set_color(p2.get_color())
f3.yaxis.label.set_color(p3.get_color())
f4.yaxis.label.set_color(p4.get_color())

tkw = dict(size=4, width=1.5)
f1.tick_params(axis='y', colors=p1.get_color(), **tkw)
f2.tick_params(axis='y', colors=p2.get_color(), **tkw)
f3.tick_params(axis='y', colors=p3.get_color(), **tkw)
f4.tick_params(axis='y', colors=p4.get_color(), **tkw)
f1.tick_params(axis='x', **tkw)

lines = [p1, p2, p3, p4]

f1.legend(lines, [l.get_label() for l in lines])

plt.show()

I would like to achieve something similar to Figure 2 below, but with multiple Y-axes each corresponding to their respective colored bars. Appreciate any help that I can get. Thanks!
Fig 2: Example of Multiple Bar Plot
Answer:
The issue stems from the way the matplotlib api returns different objects depending on the type of plot (e.g. plot & bar have different returns).
The line data was probably plotted using Multiple Yaxis With Spines, which doesn't work with bar
I offer you two options:

Plot the bar with one y-axis and then set it to log scale to compensate for the variation in the value range
Plot the bar using a secondary y-axis and set one it to a log scale.

Leave the data in the dataframe to make plotting easier.

Setup dataframe
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

# test data
np.random.seed(10)
rows = 5
feature1 = np.random.randint(10, size=(rows,)) / 10
feature2 = np.random.randint(20, size=(rows,)) / 10
feature3 = np.random.randint(8, 25, size=(rows,))
feature4 = np.random.randint(1, 3, size=(rows,))
xaxis = range(rows)

# create dataframe
df = pd.DataFrame({'Adj. R2': feature1, 'Max Abs. Error': feature2, 'Max Error': feature3, 'RMS Error': feature4},
                  index=['SVR', 'DTR', 'RFR', 'PR', 'MLR'])

# display(df)
     Adj. R2  Max Abs. Error  Max Error  RMS Error
SVR      0.9             1.6         18          2
DTR      0.4             1.7         16          2
RFR      0.0             0.8         12          1
PR       0.1             0.9         24          1
MLR      0.9             0.0         12          2

Plotting
secondary_y
ax = df.plot(secondary_y=['Max Error', 'RMS Error'], kind='bar')
ax.right_ax.set_yscale('log')
plt.show()

single y-axis
df.plot(kind='bar', logy=True)
plt.show()

Comment: Thanks a lot for the detailed explanation. Understood that the multiple Y-axes line plot doesn't work like the bar plot. However, is there a way to superimpose all 4 Y-axes on the plot separately?
Comment: @Skyhehe Not so much. I haven't found a single example where the bars can be added individually.


Como deixar variáveis de forma privada em JavaScript?

Question: Como deixar uma variável privada, pois tive problema em utilizar o mesmo nome de variável que já estava implementado em outro arquivo JS e que eu não lembrava.
Como criar essa variável privada para ser utilizar apenas no arquivo?
Answer: No arquivo basta usar um var pra declarar a variável. Ainda assim não é o ideal. Variáveis devem ser mais locais ainda. O ideal é declarar variáveis somente dentro de funções. Também pode fazer isso em objetos. Só que variáveis de objetos costuma ter visibilidade pública (ainda que o escopo seja privado).
Se quiser criar variáveis com visibilidade privado é possível com um truque. Isto é feito no construtor do objeto com variáveis locais ao construtor. Assim:

function Container(param) {
    function dec() {
        if (secret > 0) {
            secret -= 1;
            return true;
        } else {
            return false;
        }
    }
    this.service = function () {
        return dec() ? that.member : null;
    };
    this.member = param;
    var secret = 3;
    var that = this;
}
var obj = new Container('abc');
console.log(obj.service());
console.log(obj.service());
console.log(obj.service());
console.log(obj.service());
console.log(obj.secret); //isto dá erro

Coloquei no GitHub para referência futura.
A técnica com mais detalhes pode ser vista do artigo famoso do Douglas Crockford.
Todas as três variáveis são locais (o parâmetro é sempre local), e por definição só acessível dentro do construtor. O this.member é um membro público do objeto. O JS é ainda mais restrito do que outras linguagens. Esses membros do objeto só podem ser acessado por método privados. Nem mesmo métodos públicos do objeto podem acessá-los diretamente.
Métodos privados são as funções declaradas dentro do construtor. É o caso de dec(). Para fazer a comunicação entre métodos privados e públicos criamos um método dentro do construtor mas através do this, assim ele é ao mesmo tempo privado (ao construtor) e público (acessível pela referência do objeto), portanto é um método privilegiado. Este é o método service(). Ele pode chamar dec() e acessar that que são privados, e é acessível fora do objeto.
O mecanismo que permite isso pode ser melhor entendido na pergunta sobre closures.
Answer: Marcio, primeiro você precisa entender um pouco sobre o escopo das variáveis.
Então vamos começar pelo escopo global:
//se declarado fora de qual quer função/objeto.
var variavel = "Hello World!";
//se declarado em qual quer ponto do codigo.
window["variavel"] = "Hello World!";
window.variavel = "Hello World!";

as três declarações acima apontam para a mesma variavel, no caso a variavel global variavel.
se você deseja que a sua variável seja em todo o código, porém não possa ser editada, você pode fazer uso do Object.defineProperty:

Object.defineProperty(window, "variavel", {
  value: "Hello Wolrd!"
});

console.log(variavel); // "Hello Wolrd!"
variavel = "Tentativa de Editar";
console.log(variavel); // "Hello Wolrd!", a atribuição acima não surtiu efeito.

Porém, acredito que no seu caso, o melhor seja definir um escopo, para tal existem algumas tecnicas, como uma IIFE

(function () {
  var variavel = "Hello World";
  console.log("dentro do IIFE -> " + variavel); //"Hello World"
  window.setTimeout(function () {
    console.log("dentro do IIFE -> " + variavel); //"Hello World"
    console.log("global dentro do IIFE -> " + window.variavel); //"Tentativa de Editar"
  }, 2000);
})();

variavel = "Tentativa de Editar";
console.log("fora do IIFE -> " + variavel); //"Tentativa de Editar"
window.setTimeout(function () {
  console.log("fora do IIFE -> " + variavel); //"Tentativa de Editar"
}, 2000);

Note que dentro do IIFE a variavel continua com o valor Hello World, apesar de que no escopo global ela ter recebido o valor Tentativa de Editar


Mostrar valor do input ao clicar no botao

Question: Como faço pra mostrar valor que digitei no input após clicar no botão?
o meu sempre retorna vazio:

var x = document.getElementById("usuario").value;

var usuario = $("#usuario").value; //document.getElementById("user").value;  //  $("#user").value;
var senha = $("#pwd").value;

function Enviar() {
  $("#enviar").on('click', function() {
    alert(usuario)
  });

}

  <input id="term" type="text" value="" />
  <button id="hit" type="button" name="">Search</button>

<form>
  <fieldset>

      User ID:
      <input type="text" id="usuario" name="usuario" />
      Password:
      <input type="password" id="pwd" name="pwd" />
      <input type="submit" id="enviar" onclick="Enviar()" value="Submit" />

  </fieldset>
</form>
Comment: Utilize `$("#usuario").val()` e remova o `type` do botão *Submit*.
Comment: não tem sentido tirar submit se nao vai perder propriedade do buttom
Comment: Existe um type="button" nesse caso não seria melhor?
Comment: Não prestei atenção e achei que era um `button`. De qualquer forma, utilize `preventDefault` ou utilize um `button` (semanticamente é melhor).
Answer: Você está pegando o valor do campo fora da função, logo ele será vazio porque ao carregar a página o campo não tem nada, além de estar pegando o valor de forma incorreta. Em jQuery use-se .val() e não value:
$("#usuario").val();

E não precisa colocar o evento dentro de uma função e chamar a função através de um onclick. Basta criar um evento submit e pegar os valores dos campos dentro do evento:
$("form").on('submit', function() {
   var usuario = $("#usuario").val();
   var senha = $("#pwd").val();
   alert(usuario)
});

Ao submeter o formulário irá executar a função evento, pegando os valores atuais.
O HTML e script ficariam assim:

var x = $("usuario").val(); // não entendi pra que esta linha serve(?)

$("form").on('submit', function() {
   var usuario = $("#usuario").val(); //document.getElementById("user").value;  //  $("#user").value;
   var senha = $("#pwd").val();
   alert(usuario)
});

  <input id="term" type="text" value="" />
  <button id="hit" type="button" name="">Search</button>

<form>
  <fieldset>

      User ID:
      <input type="text" id="usuario" name="usuario" />
      Password:
      <input type="password" id="pwd" name="pwd" />
      <input type="submit" id="enviar" value="Submit" />

  </fieldset>
</form>
Comment: Fato *não tão curioso assim*: ao utilizar o evento `submit` no lugar do `click` o código ainda funcionará se o formulário for submetido através de outros meios que não sejam o clique. Como geralmente isso é desejado, costuma ser melhor usá-lo, de fato, no lugar do clique.
Answer: Altera a sua função pra pegar o valor atualizado:
function Enviar() {
  $("#enviar").on('click', function() {
    alert($("#usuario").val())
  });
}

Se você quiser que ele ainda continue na página mude o type="submit" para type"button" no seu botão.
Espero ter ajudado amigo.
Comment: Se ele tirar o `type='submit'` o campo ficará sem o atributo, fazendo com que o navegador o trate como um campo de texto. Qual a razão de fazer isso?
Comment: o problema é que quero armazenar em 2 varias como esta no códgo porque deposi vou comprar usuario e senha, e o valor que digito nao  sempre vem vario
Comment: Se você submitar esse form os valores irão se perder, independente de onde as varáveis estejam.
Comment: Desculpa galera me expressei errado, na realidade ele tem que alterar.
Answer: Várias coisas que deverão ser corrigidas:

Você tratou evento click duas vezes, tanto no atributo onclick do elemento quanto em jQuery com a função on, basta apenas uma delas;
Você acessou o atributo value com jQuery, mas isso se faz no JS vanilla. Para buscar o valor do elemento no jQuery, use a função val();
Você buscou os valores dos campos fora da função, o que fará com que eles serão executados quando a página for carregada - e quando é carregada os campos estão vazios. Você precisa obter os valores dentro da função;
Use a função preventDefault para evitar que o formulário seja submetido, já que está usando um botão submit;

Veja como ficaria:

$("#enviar").on('click', function(event) {
  event.preventDefault();
  var usuario = $("#usuario").val();
  var senha = $("#pwd").val();
  alert(usuario)
});

  <input id="term" type="text" value="" />
  <button id="hit" type="button" name="">Search</button>

<form>
  <fieldset>

      User ID:
      <input type="text" id="usuario" name="usuario" />
      Password:
      <input type="password" id="pwd" name="pwd" />
      <input type="submit" id="enviar" value="Submit" />

  </fieldset>
</form>


print data to twig file from custom form submit via controller

Question: I have created a custom form, and I'm passing data to twig file from submitForm function as follows
public function submitForm(array &$form, FormStateInterface $form_state)
{
$form_state->setRebuild();

$data = ['role' => $form_state->getValue('role'),
'date' => $form_state->getValue('date')
];
MyController::Detail($data);

}

and in controller passing data to twig
public static function Detail($data) {

return [
'#theme' => 'my_report',
'#data' => $data,
];

}

but not able to get/print data in twig file.
Answer: When you set rebuild in a form submit there is no controller involved. The next page displayed is the rebuilt form, where you can print the my_report twig template by adding it to the build array $form.
You don't need to transfer the values in $form_state, because they are available while rebuilding the form. You can check in the form build function whether these values are present. If not, you are building a new form. If they are, this is a form rebuild, then display the result template:
  public function buildForm(array $form, FormStateInterface $form_state) {

    // build form

    if ($form_state->hasValue('role')) {
      $form['my_report'] = [
        '#theme' => 'my_report',
        '#role' => $form_state->getValue('role'),
      ];
    }
    return $form;
  }

Comment: did you mean to call twig template in submitForm function? because I need to pass submitted data to twig
Comment: No, I mean the form build function. I add a code example.
Comment: I have added `$form['#theme'] = 'my_report';` in build function but it gives empty form means without fields, my requirement is to pass submitted data to twig
Comment: Sorry, I can't help you any further, because we are not allowed to extend the topic in the comments. My answer is for `$form_state->setRebuild();`. You can also use `$form_state->setRedirect('route.to.controller');`. Search for similar questions. If you can't find anything helpful ask a new question.
Comment: I m able to resolve the issue


Cor dinâmica em TextField em relatórios Jasper

Question: Quero mudar a cor do textfield de acordo com o valor do mesmo,
achei vários tutoriais que dizem pra criar um style e aplicar ao textfield, tem que marcar uma opção "styled text" que não encontrei nas propriedades do textfield no jasper, os tutoriais todos referem-se ao Ireport e eu uso o JasperReports, alguma dica?
Comment: Olá Julio, você poderia postar um [mvce](http://pt.stackoverflow.com/help/mcve) com um relatório de exemplo, a chamada para gerá-lo e o ponto em que você deseja aplicar o estilo dinamicamente?
Answer: Eu ja passei por esse mesmo problema, eu precisava pintar cada linha do par do relatorio de vermelho, então achei seguinte a solução:

aqui nesse trecho eu crio o Style que tem uma condição booleana:
(se o numero do contador da linha dividido por 2 for = 0 então ele é uma linha par e seu fundo vai ser vermelho)
new Boolean($V{REPORT_COUNT}.intValue() %2 == 0)

após criar esse style com o nome= style_fundo_vermelho eu adiciono ele ao atributo style do textField:
<textField>
    <reportElement style="style_fundo_vermelho" x="658" y="1" width="90" height="16" uuid="c118ccc6-4074-4f03-9bfa-cf6c3ae8a1b9">
    </reportElement>
</textField>

Assim você já pode resolver seu problema de cor de fundo dinâmica no text field, basta adaptar a  do style para a sua necessidade.
Answer: Caso não encontre, outra possível solução é sobrepor outro textfield com a cor que quer e faz o chaveamento para mostrar um ou outro :)
Comment: É, não queria usar esta mais vai ser o jeito! Kkkkkkkkkkkk Valeu cara!


Find all reals $x$,$y$ satisfying the following equation:

Question:
Find all positive reals $x,y \in \mathbb{R}^+$ satisfying:
  $$\frac{x^9}{y} + \frac{y^9}{x} = 10-\frac{8}{xy}$$

Since this involves higher exponents I am unable to tackle this problem. Please help me.
Comment: I don't think this qualifies as a [Diophantine equation](https://en.m.wikipedia.org/wiki/Diophantine_equation).
Comment: Oh! I have now known that a Diophantine has only integer solutions but it involves reals.
Comment: Well, if you multiply it by $xy$ you will get a polynomial equation in $2$ variables of degree $10$. Generally there is no algorithm to solve such equations. But in that particular case? Who knows, doesn't look easy.
Comment: It looks cleaner as $x^{10}+y^{10}=10xy-8$ but I am not sure that is progress.
Comment: How about you tell us some story about the equation? Where did you get it from? Perhaps there's some hint in it.
Comment: $(x,y) = (1,1)$ is a solution.
Comment: A desmos graph https://www.desmos.com/calculator/timng19bz2 reveals that the only solutions are $(1,1)$ and $(-1,-1)$ but how to prove that?
Comment: @JohnWaylandBales I already tried the graph way
Comment: @freakish I came across this while solving a reference book
Answer: Hint: Write it as:
$x^{10}+y^{10}=10xy-8$
Then use AM-GM:
$10xy-5=x^{10}+y^{10}+1+1+1\ge5\sqrt[5]{x^{10}y^{10}}=5x^2y^2$
Which gives $5(xy-1)^2\le0$, so $xy=1$
Then initial equation can be rewritten as $x^{10}+\frac{1}{x^{10}}=2$
Which by AM-GM again, (or by writing it as a $(x^{10}-1)^2=0$) has the solution, $x^{10}=1$, so $x=\pm1$
So $x=1,y=1$, or $x=-1,y=-1$
Comment: Wow! I never thought of using the AM-GM. What a brain! Thank for the answer.
Answer: Just to give a non-AM-GM answer, let $u=xy$, which must be positive in order for $x^{10}+y^{10}=10xy-8$ to have a solution, and note that $x^{10}+y^{10}=(x^5-y^5)^2+2(xy)^5$.  Thus
$$\begin{align}x^{10}+y^{10}-10xy+8
&=(x^5-y^5)^2+2(u^5-5u+4)\\
&=(x^5-y^5)^2+2(u-1)(u^4+u^3+u^2+u-4)\\
&=(x^5-y^5)^2+2(u-1)^2(u^3+2u^2+3u+4)\\
&\ge0
\end{align}$$
with equality if and only if $x^5=y^5$ and $xy=u=1$ (since $u\gt0$ implies $u^3+2u^2+3u+4\gt0$).  From this we see that $x=y=\pm1$ are the only possibilities.  In particular, $(x,y)=(1,1)$ is the only solution with $x,y\in\mathbb{R}^+$.
Remark:  I showed the factorization of $u^5-5u+4$ in two steps for ease of checking.


Boost Variant essentially a Union in c/c++?

Question: I'm wondering what the differences are between a Boost Variant and a union data-type in c/c++. I know that a union data-type takes up the same memory location and the largest data type in the region of memory occupies the total amount of memory used e.g.
union space {
   char CHAR;
   float FLOAT;
   int INTEGER;
}S;

should occupy 4 bytes of memory since int and float are the largest and equal size. Are there similarities and differences in other ways between Boost Variant and union data types?
I also know that a Boost Variant can take any data type and it allows data type "polymorphism" (correct me if I'm misusing a OOP topic word). Is a union data type therefore a type of polymorphism also?
Answer: The primary difference is that Boost's Variant knows which type is stored in it, so you can't make mistakes or get UB from misusing a Variant in the same way you can a union. This also permits Variant to take non-POD (i.e. actually useful) types. Variant also has a few extra tricks like permitting visitors and recursive variants.
The best guide to using unions is "Don't, because it's almost impossible to put them to good use without invoking UB". This does not apply to Variant, so it's a lot safer to recommend.
Comment: What is "UB" and "POD"?
Comment: @user2555139 Undefined Behaviour and Plain Old Data (types)
Answer: Boost variant emulates a union but it does not use a union in its implementation. Instead it uses aligned storage and placement new.
It is polymorphic in the sense that if you apply a visitor object on a variant then it will pick the right overload for you. This selection must happen at runtime, but the object code for this is unrolled at compile time. So it's quite fast.


Limit with geometric sequence

Question: I computed
 $$\lim_{n \rightarrow \infty } \sqrt[n]{n^n+n^{n+1}+\cdots+n^{2n}} \cdot\left(1-\cos{\frac{3}{n}}\right)$$
$$=\lim_{n \rightarrow \infty } n^2 \sqrt[n]{n^{-n}+n^{-n+1}+\cdots+1} \cdot \left(1-\cos \frac{3}{n} \right) $$
$$=\lim_{n \rightarrow \infty } \sqrt[n]{n^{-n}+n^{-n+1}+ \cdots +1} \cdot \frac{1-\cos \frac{3}{n} }{\frac{9}{n^2}}\cdot 9=\frac{9}{2} $$
1) Is it correct to extract $n^{2n}$ from $\sqrt[n]{n^n+n^{n+1}+\cdots+n^{2n}}$ the way I did?
2)How do I show that $\lim_{n \rightarrow \infty } \sqrt[n]{n^{-n}+n^{-n+1}+\cdots+1}=1$?
I came up with this:
for geometric sequence the sum can be computed as $s_n=a_1\frac{q^n-1}{q-1}$, but I learned this in high school and if I recall correctly we used it for finite number of terms. So I don't know if I can use it here as $n\rightarrow \infty$.
$$\lim_{n \rightarrow \infty } \sqrt[n]{n^{-n}+n^{-n+1}+\cdots+1} = \lim_{n \rightarrow \infty } \sqrt[n]{n^{-n}\cdot \frac{n^n-1}{n-1}+1}$$
So I can estimate upper/lower bound:
$$\sqrt[n]{1} \le \sqrt[n]{n^{-n}\cdot \frac{n^n-1}{n-1}+1} \le \sqrt[n]n $$
Then:
$$\lim_{n \rightarrow \infty } \sqrt[n]{n^{-n}+n^{-n+1}+\cdots+1}=1$$
Thank you.
Comment: It's all perfect as it is. Observe that, for any given $n\in\Bbb N$, the geometric series in question has only *finite* members.
Comment: thank you, I was eagerly waiting for someone to tell me his/her thoughts on this. So it is alright this way, I see. I assume same could be applied for the sum of arithmetic sequence?(with different formula of course)
Answer: We have these inequalities
$$n^2\le(n^n+\cdots+n^{2n})^{1/n}\le((n+1)n^{2n})^{1/n}=n^2(n+1)^{1/n}\sim_\infty n^2$$
and  by Taylor series
$$1-\cos\left(\frac 3 n\right)\sim_\infty\frac 1 2\left(\frac{3}{ n}\right)^2=\frac{9}{2n^2}$$
hence
$$\lim_{n \rightarrow \infty } {\sqrt[n]{n^n+n^{n+1}+...+n^{2n}}\cdot(1-\cos{\frac{3}{n}})}=\lim_{n \rightarrow \infty }n^2\frac{9}{2n^2}=\frac{9}{2}$$
Comment: I was hoping for more elementary way, as we have not defined Taylor series in our class, but thank you anyway.
Comment: @cryogenic Do you know that $$\lim_{x\to0}\frac{1-\cos x}{x^2}=\frac 1 2?$$
Comment: Yes sure, I managed to solve the problem(see the question above), I was just not sure with some parts of it. For exams we are required to not only compute the limits but also provide "explanations" for the steps we make.
Comment: @cryogenic So you have the full answer with elementary way and I'm sure that you know what we should write!
Comment: I was asking for verification and feedback, I specified with what parts I wasn't sure, as it is often possible to get correct answer with wrong "reasoning" behind it...I apologize if I didn't make it clear enough.
Comment: @cryogenic Do you understand the inequalities? If yes I'll edit my answer for elementary way.
Comment: no, I don't think I understand it. Do you think you can show it different way than I did?
Comment: @cryogenic In the sum $n^n+\cdots+n^{2n}$ there's $n+1$ terms and the biggest term is $n^{2n}$. It's clear that this sum is greater than $n^{2n}$ and smaller than $(n+1)n^{2n}$ since each term is small than $n^{2n}$ and we have as I said $n+1$ terms so write these inequalities then pass to the power $1/n$ and simplfy.
Answer: Your geometric series has $n$ terms, of which all but the last two are smaller than $1/n^2,$ so their sum is smaller than $1/n,$ so the expression under the radical is smaller than $1+2/n,$ so it goes to $1,$ hence so does its $n$th root.

Limit with geometric sequence


How to read an element attribute with BeautifulSoup?

Question: I am trying to find all tags in an html page that have the text "About".
To get that result i used this:
text = page.body.find(string=re.compile('About'))
parent=about.parent
link=parent.href

text is a list of 8 letters forming the phrase "About me", which is surprising to me. Even more surprising is that if i print text the result is the phrase "About me" with no gaps, as it weren't a list but a single variable.
The variable parent results in this:
About Us

As you can see, the parents(a tags) have a href attribute. But the variable "link" results in None instead of the href attribute.
What is going on?
Please ask if anything is not clear
Answer: Welcome to SO.
If I understand your question correctly, you're not sure how to access an attribute of an element.
This should do the trick:
link = parent['href']

Happy coding :)


Using a pyqt widget from a linearly running console application

Question: My scenario here is the following: I am using a pyqt widget to display a solid color fullscreen on a second display and observe this display with a camera that is continuously capturing images. I do some processing with the images and this is the data I am interested in. This works great when used interactively with ipython and matplotlib using the qt4agg backend like so
% ipython -pylab
# ... import PatternDisplay, starting camera
pd = PatternDisplay(); pd.show(); pd.showColor(r=255,g=255,b=255)
imshow(cam.current_image)

I need a similar behavior now in a console script though: it should display the PatternDisplay widget, capture an image, than change the color on the PatternDisplay and take a new image and so on.
The problem is now that the PatternDisplay is never updated/redrawn in my script, likely because PyQt never gets a chance to run it's event queue. I had no luck trying to move the linear worker part of my script into a QThread because I cannot communicate with the PatternDisplay Widget from another Thread any longer. I tried to replicate the implementation of ipython/matplotlib, but I didn't fully understand it, it is quite complicated - it avoids running the QApplication main loop via monkey patching and somehow moves QT into it's own thread. It then checks periodically using a QTimer if a new command was entered by the user.
Isn't there an easy way to achieve what I want to do? I am gladly providing more information if needed. Thanks for any help!
Answer: What you need is easier than IPython's job - IPython makes the Qt application and the command line interactive at the same time.
I think the way to do it in Qt is to use a timer which fires at regular intervals, and connect the signal to the 'slot' representing your function that gets the new image and puts it in the widget. So you're pulling it in from the event loop, rather than trying to push it.
I've not used Qt much, so I can't give specifics, but the more I think about it, the more I think that's the right way to do it.
Comment: I can't see how this can be done though: the main applications task is never idle and will never give control to qts main loop. I also wouldn't know how to "suspend" the flow of the main task, as it needs to be in the same thread as the qt widgets; afaik there is no equivalent to wx.Yield.
Comment: @SirVer: I'm suggesting that you make Qt's main loop the main application task, and get it to call your code regularly. GUI programming is a different approach to standard scripts. The clever stuff in IPython/matplotlib is to handle the GUI without requiring the mental gear shift from the user.
Comment: Thanks Thomas. I understand that this is the appropriate behavior and what I need is something out of the norm. However, since the paradigm I have here is basically a 'standard script' that just happens to display timed images in a GUI I searched for a way to avoid the GUI paradigm. I wasn't sure if this was possible and it seems it isn't. I will stick with running my script from inside ipython -pylab for now. Thanks for your help!
Answer: I solved the same problem (i.e. interactive ipython console in terminal, and GUI thread running independently) in the following way with ipython 0.10 (code here)
 1. Construct QApplication object, but don't enter its event loop explicitly
 2. Run the embedded IPython instance
 3. Run the UI code you need by instantiating your window and calling show() on it (like here with the yade.qt.Controller(), which I aliased to F12. (I did not find a way how to ask the embedded shell to run a command at the start of the session, as if the user had typed it)
(You can also show() your window first, then run the embedded ipython. It will provide event loop for Qt.)
(BTW I also tried running Qt4 from a background thread (using both python threads module, and Qt4.QThreads), but it refuses to run in such way stubbornly. Don't bother going that way.)
The disadvantage is that UI will be blocked while ipython is busy. I hope to finding something better for 0.11, which should have much better threading facilities (I asked on ipython-users about how to unblock the UI).
HTH, v.
Comment: Thanks! Do you have an idea how this can be done without the dependency of ipython? I would like to display my images on the GUI, but keep the linear flow of the program because it is easier to read and understand.
Comment: I think if you don't need the interactive command-line, you can just create regular QApplication and spawn a background QThread  for data acquisition and analysis, while the main UI thread will periodically update image from those data. You just have to ensure consistency, so that you don't display half-old half-new data, if you update them in some loop sequentially.


Is there a more idiomatic way in Rust to handle similar methods?

Question: My program loads two file types, sql or csv, makes manipulations, and then saves them out. I have two structs, one for the preliminary serialization and another for the output.
Both files follow the same process and thus, have the same methods (but the logic obviously differs).
I tried using a trait to group these methods, but I couldn't get it to work because I needed to tell the compiler what the type was ahead of time.
What I have:
struct DerivedTable { /* ... */ }

struct NewTable { /* ... */ }

struct CsvFile { /* ... */ }

struct NewCsv { /* ... */ }

// ... load some files from a dir
for node in dir_of_files {
            match get_extension(path) {
                "csv" => {
                    let model = CsvFile::new_from_file(node.path.to_path_buf())?;
                    let new_csv = NewCsv::from(model);
                    new_csv.export(&out_path)?;
                    Ok(node.name.clone())
                }
                "sql" => {
                    let model = DerivedTable::new_from_file(node.path.to_path_buf())?;
                    let new_table = NewTable::from(model);
                    new_table.export(&out_path)?;
                    Ok(node.name.clone())
                }
                _ => panic!("Illegal file type passed"),
            }
        })
}

I'm wondering if it's possible to consolidate this logic into a single copy:
for node in dir_of_files {
  let model = <What goes here?>::new_from_file(...)?;
  let new_file = <What goes here?>::from(model);
  new_file.export(...)?;
  Ok((node.name.clone())
}

Comment: Don't be too afraid of repeating yourself. If it's a small amount of relatively stable code, the repetition is often the best solution. It's simple and easy to read. Repetition can become a problem if there's a lot of it, or if the code frequently changes, and you have to manually keep multiple copies in sync.
Comment: It is possible, if you create a trait for the operations then store a `Box`. But I'm not sure this is worth it for those few lines of code.
Answer: The only thing you must do is map the runtime file extensions to compile-time types. But once you do that, you can call generic code with the correct types. In this case, you can probably add a default trait method to contain this logic.
fn manipulate_with_path(path: &Path, node: Node) -> Result<Name, Error> {
    match get_extension(path) {
        "csv" => CsvFile::manipulate(node),
        "sql" => DerivedTable::manipulate(node),
        _ => panic!("Illegal file type passed"),
    }
}

trait Export: From<Model> {
    fn export(self, path: &Path) -> Result<(), Error>;
}

trait Filetype {
    type New: Export;
    fn new_from_file(p: PathBuf) -> Result<Model, Error>;
    fn manipulate(node: Node) -> Result<Name, Error> {
        let model = Self::new_from_file(node.path.to_path_buf())?;
        let new_type = Self::New::from(model);
        new_type.export(&out_path)?;
        Ok(node.name.clone())
    }
}

impl Export for NewCsv {
    fn export(self, path: &Path) -> Result<(), Error> {
        todo!()
    }
}

impl Filetype for CsvFile {
    type New = NewCsv;
    fn new_from_file(p: PathBuf) -> Result<Model, Error> {
        todo!()
    }
}

impl Export for NewTable {
    fn export(self, path: &Path) -> Result<(), Error> {
        todo!()
    }
}

impl Filetype for DerivedTable {
    type New = NewTable;
    fn new_from_file(p: PathBuf) -> Result<Model, Error> {
        todo!()
    }
}

There's many things left undefined in your question so I've filled in the gaps with probable types. If you aren't able to adapt this to your situation, add the missing details to your question. In particular, if Model is different between each file type, you'll need another associated type in Filetype.


Square of the Error Function

Question: The author defines the probability integral as follows
$$\Phi(z)=\frac{2}{\sqrt{\pi}}\int_0^z e^{-t^2}\mathrm{d}t$$.
(S)he instructs the reader to derive the following integral representation of the square of the probability integral by transforming it to polar coordinates
$$\Phi(z)^2=1-\frac{4}{\pi}\int_0^1\frac{\exp(-z^2(1+t^2))}{1+t^2}\mathrm{d}t$$.
I am uncertain how transforming the integral from cartesian coordinates to polar coordinates would yield the integral representation. Can someone explain this to me?
$$I^2=\frac{4}{\pi}\int_{0}^{z}\int_{0}^{z}e^{-(x^2+y^2)}dydx=-\frac{2}{\pi}\int_{0}^\frac{\pi}{2}\int_{0}^{z}-2re^{-r^2}drd\theta$$?
Comment: @DavidG.Stork "Extricate" might have made sense if the previous sentence were something like, "I've gotten stuck in an infinite loop of second-guessing my guesses while trying to figure this out."
Comment: Solved:  https://en.wikipedia.org/wiki/Gaussian_integral  (By the way, I suggest you look up "extricate," as it does not mean what you think it does.)
Comment: Yep!  It is one of those words my students use to have that "literate look," but are completely inappropriate.
Comment: @DavidG.Stork I know that $$\int_{-\infty}^\infty e^{-x^2}\,dx = \sqrt{\pi}.$$. However I do not understand how the author derived that $$erf^2(z)=1-\frac{4}{\pi}\int_{0}^{1}\frac{e^{-z^2(1+t^2)}}{1+t^2}dt$$
Answer: $\operatorname{erf}(z)^2$ can be expressed as an integral over the region $[0,z]\times[0,z]$. By symmetry, you can calculate half of its value by looking at the lower half triangle (i.e. with the additional bound $y\leq x$). I believe the correct coordinate transformation is $R=x^2+y^2, t=\frac yx$ (you could think of the former as $r^2$ and the latter as $\tan\theta$ in polar coordinates).  Express the region in the new coordinates, calculate the Jacobian, and the result should follow.
Full solution: $\def\pdv#1#2{\frac{\partial #1}{\partial #2}}$

 First, $erf^2(z)=\frac4\pi\int_{[0,z]^2}e^{-(x^2+y^2)}dxdy=\frac8\pi\int_{D}e^{-(x^2+y^2)}dxdy$, where $D=\{(x,y)\in[0,z]^2 \mid y\leq x\}$. Write $I=\int_{D}e^{-(x^2+y^2)}dxdy$.

 The inverse of the Jacobian (since this is easier to calculate) is $\begin{pmatrix}\pdv Rx&\pdv Ry\\ \pdv tx&\pdv ty\end{pmatrix}$ with determinant $2(1+t^2)$, so its inverse has determinant $\frac1{2(1+t^2)}$. The triangular region $D$ becomes the region $\{(R,t)|0\leq t\leq1, 0\leq R\leq z^2(t^2+1)\}$. (You need to notice $\frac1{\cos^2\theta}=\tan^2\theta+1$.)

 At last the calculation. $$I=\int_0^1\int_0^{z^2(t^2+1)}e^{-R}\cdot\frac1{2(1+t^2)}dRdt=\frac12\int_0^1(1-e^{-z^2(1+t^2)})\frac1{1+t^2}dt=\frac12(\frac\pi4-\int_0^1\frac{e^{-z^2(1+t^2)}}{1+t^2}dt),$$ so $$erf^2(z)=\frac8\pi I=1-\frac4\pi\int_0^1\frac{e^{-z^2(1+t^2)}}{1+t^2}dt$$ as desired.

Square of the Error Function


Do p-values assume an unlikely event has already happened?

Question: According to this thread
What is the meaning of p values and t values in statistical tests?
a p-value essentially lets me compare the probability of tail-end (unlikely) events occurring and judging that against the significance level $\alpha$ to decide whether the null hypothesis should be rejected. In the example on this thread, Muriel Bristol visits Fisher and it essentially asks what's the probability of getting 5/6 correct guesses given the probability of her guessing correctly is $0.5$.
In the context of this, p-values make sense if I assume an unlikely event already happened. Because if such an event happens, then interpreting the significance of that event for a null hypothesis is a natural way to decide whether that hypothesis has been rejected.
My Question
Do p-values assume an unlikely event has already happened? If so, why is this part of the definition? If not, how does knowing the p-value tell me anything about why I should reject the null hypothesis?
Without knowing an unlikely event occurred, it would seem all a p-value can say is "if an unlikely event occurs, then the null hypothesis would be rejected."
Comment: I don't get your assertion "p-values make sense if I assume an unlikely event already happened"; can you explain your reasoning?
Comment: Suppose I am considering whether a die is biased. If I roll this die several times and get the same number each time, that would give me a lot of information about the bias of the die, right? So the occurrence of an unlikely event (or cluster of them) tells me something about the system. So if my null hypothesis is the die is fair, and I roll all 6s, then I would reject that null hypothesis because the pvalue of getting all 6s would be lower than the significance level $\alpha = 0.05$. Did that make any sense?
Comment: That doesn't explain why the p-value would not make sense if the observed event was less unusual.
Comment: I think I do not understand what frequentist statistics means and therefore I do not understand this way of thinking.
Comment: @StanShunpike the classic hypothesis testing you are describing (which is the one working with p-values) is also called "frequentist statistics". It is opposed to Bayesian statistics, which looks at the probability that event B will happen given that another event A has already happened. If you have never done Bayesian (which is rarely taught in introductory courses) you can skip that caveat and just look at the rest of the answer.
Answer: In frequentist statistics, it does not matter whether an event has occurred or not. P-values give an idea of how often the data would be observed given the null hypothesis is true.  If you get a p-value of .15 then we would say that, if the null hypothesis is true, the data or more extreme data would occur in 15% of an infinite amount of cases.
P-values are of limited utility in general, see the statement be the American Statistical Association for more information.
Answer: Do P-values assume that an unlikely event has already happened? No. The P-value is calculated by setting a null hypothesis within the chosen statistical model, but by the P-value itself makes no assumptions. However, if an analyst chooses to accept the null hypothesis despite finding a low P-value then, assuming the P-value is appropriately conditioned for the inferential task at hand, the analyst would be assuming that an unlikely event had occurred.
This answer is not intended to be just nit-picking about the agency of P-values versus analysts. It is necessary to keep the various components of statistical inference clearly labelled to avoid the standard confusions.
P-values have been "defined" in several different ways, and they take subtly different meanings within different statistical frameworks. The unlikely event thing comes from an interpretation of P-values, or a strategy for interpreting them as originally mentioned by Fisher.
Knowing the P-value tells you how unusual the data look according to the statistical model with the particular null hypothesis used. If the data look unusual then you have a reason to suspect that either the model is wrong, the null is wrong, both, or that an unusual event has occurred.
I agree with Chris P that you should have a look at the ASA statement on P-values, but you probably also should look at some of the references cited within. Among them, my own paper on the necessary distinction between hypothesis tests yielding dichotomous decisions and significance tests yielding a P-value to be interpreted as evidence is (of course!) well worth reading: http://www.ncbi.nlm.nih.gov/pubmed/22394284
Answer: As stated in other answers, $p$-values don't assume that an unlikely event occurred. The $p$-value is a probability that is conditioned only on the null hypothesis being true,
$$
P(\text{Obtaining data as or more extreme than that observed} \, | \, H_0)
$$
and not on anything about the observed data.
Some people's logic concerning $p$-values, though, can be reduced to a triviality about the fact that data that were extreme under $H_0$  were observed (see rejoinder 6 in Berger & Delampady, 1987). The logic goes

Either an extreme event occurred and $H_0$ is true OR $H_0$ is false

And this is used as evidence against $H_0$. Though if we are careful we should in fact say

Either an event that would be extreme under $H_0$ occurred and $H_0$ is true OR an event that would be extreme under $H_0$ occurred and $H_0$ is false

which just reduces to

an event that would be extreme under $H_0$ occurred

In fact, this very fallacy is repeated in an answer to your linked question
Comment: +1 and thanks for the link, but it seems like you got the quotes a bit wrong. Don't see any mention of $H_1$, I think you mean to write $H_0$ everywhere?
Comment: thanks, typos now fixed.
Answer:
Do p-values assume an unlikely event has already happened?

p-values assume nothing about the event. Instead, they assume that the null hypothesis is correct.

If so, why is this part of the definition?

It is not part of the definition that we assume that an unlikely event has happened.
Some thought that makes this very clear: p-values can also be computed for events that are very likely.

If not, how does knowing the p-value tell me anything about why I should reject the null hypothesis?

This p-value doesn't tell you directly whether you should reject the null hypothesis. But it does tell you whether a certain observed effect is statistically significant or not.
p-values give a statistical interpretation to deviations of some measurement.
When experiments have variations in the sampling process then the fact that a deviation of a certain magnitude has happened is not very meaningful when we do not know the statistical variation that may occur given some hypothesis.
This helps you because in order to reject a null hypothesis we would like a certain standard about the probability of type I errors (the rejection of a hypothesis that is actually true).


Matplotlib labeling sub subplots

Question: I want to add labels to my plot which consists of sub subplots. Here is what I want (I added the outer labels with GIMP)

And this is what I actually get:

Here is the code that produces the last plot:
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import numpy as np

plots = 16
subplots = 9

fig = plt.figure(figsize=(8, 8))

wh_plots = int(np.sqrt(plots))
wh_subplots = int(np.sqrt(subplots))

outer_grid = gridspec.GridSpec(wh_plots, wh_plots, wspace=0.1, hspace=0.1)
for p in range(plots):
    inner_grid = gridspec.GridSpecFromSubplotSpec(wh_subplots, wh_subplots, subplot_spec=outer_grid[p], wspace=0.05, hspace=0.05)
    for s in range(subplots):
        ax = plt.Subplot(fig, inner_grid[s])
        ax.imshow(np.random.rand(10,10), cmap="magma", interpolation="none")
        ax.set_xticks([])
        ax.set_yticks([])
        fig.add_subplot(ax)

        if (p+1) > 12 and s == 7:
            ax.set_xlabel("sub_xlabel")
        if (p) % 4 == 0 and s == 3:
            ax.set_ylabel("sub_ylabel")

all_axes = fig.get_axes()
plt.show()

My questions:

How can I get the "xlabel" and "ylabel" as seen in the first plot?
Is there a better way to label the subplots (sub_xlabel / sub_ylabel)
compared to what I did?
if (p+1) > 12 and s == 7:
    ax.set_xlabel("sub_xlabel")
if (p) % 4 == 0 and s == 3:
    ax.set_ylabel("sub_ylabel")

It works, but it doesn't look right.
Answer: You can add these lines before plt.show():
fig.text(0.5, 0.04, 'xlabel', ha='center', fontsize=18)
fig.text(0.04, 0.5, 'ylabel', va='center', rotation='vertical', fontsize=18)

Matplotlib labeling sub subplots


Reset one function after ajax is completed

Question: Im having a small problem, I'm trying to create an inline editing system with jquery. So when an user clicks on a table field the innerhtml will change into an input field with ofcourse the content of the table field. Onblur this input field is saved in a mysql db and the innerhtml change back to the new content. I want an user to edit the same text multiple times. If I use  .live('click',function(){}); Every time the user clicks on the table field the input is added so i get an input replaced by an input with the value of the last input. Very annoying, I solved this using the .one function but now an user can only edit every table field once! Is there a way to disable an live event till the ajax call is completed?
The Jquery
$(document).ready(function(){
var id = 0;
$('table.editable td').one('click', function(event) {

    var content = $(this).html();
    id = $(this).parent().find('.id').val();
    var class = $(this).attr('class');

    $(this).html('<input type="text" id="editablefield" name="'+class+'" value="'+content+'"/>');

    $(this).unbind(event);
});

$('#editablefield').live('blur', function() {
    var value = $(this).val();
    var name = $(this).attr('name');
    $.ajax({
        type: "POST",
        url: "modules/Events/ajax/saveField.php",
        data: "id="+id+"&val="+value+"&type="+name,
        success: function(data) {
            var data = data;
            alert(data);
        },
        error: function(request, status, error) {
            alert(request.responseText);
        }
    });

    $(this).parent().html(value);
});

});

THE FRONTEND
<?php
$query = "SELECT * FROM mod_events";
$result = mysql_query($query) or die(mysql_error());

echo "
";

echo "
";
echo "	";
echo "Event	";
echo "	";
echo "	";
echo "	";
echo "Capacity	";
echo "
";

while($row = mysql_fetch_assoc($result)) {

    echo ("
");
    echo ("");
    echo ("<input type='hidden' value='".$row['event_id']."' class='id'>");
    echo ("	");
    echo ("");
    echo ($row['event_name']);
    echo ("	");
    echo ("");
    echo ($row['event_capacity']);
    echo ("	");

    echo ("
");

}

echo "
";
?>

AND THE AJAX SCRIPT
<?php
require_once('../../../../config.php');
require_once("../../../../inc/dbconnect.php");

$id     = mysql_real_escape_string($_POST['id']);
$value  = mysql_real_escape_string($_POST['val']);
$field  = mysql_real_escape_string($_POST['type']);

$query =  "UPDATE mod_events SET ".$field." = '".$value."' WHERE event_id = ".$id;

echo mysql_query($query);

?>

Hope you guys can help me out!
Comment: Shouldn't a better solution be to send the form only after the user clicked a submit button or something similar? Doing this could potentially generate *a lot* of network traffic
Comment: true, only the next step is too disable all field till ajax is complete so only one ajax call is executed.
Answer: You could check if there is already an input in this table cell like this:
$('table.editable td').click(function(event) {
    if ($('input',this).length == 0) { //check if there is already an input?
        var content = $(this).html();
        id = $(this).parent().find('.id').val();
        var class = $(this).attr('class');

        $(this).html('<input type="text" id="editablefield" name="'+class+'" value="'+content+'"/>');

        // $(this).unbind(event); // this shouldn't be needed anymore.
    }
});

to avoid the problem described by aularons comment:

but that may cause this scenario: user clicks to edit, changes data to 555, a request is made but not completed yet, then the user changes the data to 333, now this request goes faster (first got routed somewhere slow or got it's packet resent for some reason), now the user will see 333 in the field while on the server it's 555, cuz the 555 request arrived after the 333. What I did was unbinding while the request is running, then binding again: jsfiddle.net/eDJqL – aularon

You need to change the code like following.
$('#editablefield').live('blur', function() {
    var value = $(this).val();
    var name = $(this).attr('name');
    var cell = $(this).closest('td');
    cell.data('request-running', true); // set data to remember request is running
    $.ajax({
        type: "POST",
        url: "modules/Events/ajax/saveField.php",
        data: "id="+id+"&val="+value+"&type="+name,
        success: function(data) {
            cell.data('request-running', false); // mark finished ajax call
            var data = data;
            alert(data);
        },
        error: function(request, status, error) {
            cell.data('request-running', false); // mark finished ajax call
            alert(request.responseText);
        }
    });

    $(this).parent().html(value);
});

and
$('table.editable td').click(function(event) {
    if ($('input',this).length == 0 || !$(this).data('request-running')) { //check if there is already an input? Or the old request is still runnig.
        var content = $(this).html();
        id = $(this).parent().find('.id').val();
        var class = $(this).attr('class');

        $(this).html('<input type="text" id="editablefield" name="'+class+'" value="'+content+'"/>');

        // $(this).unbind(event); // this shouldn't be needed anymore.
    }
});

Comment: this worked, only i needed to change $('input',this).length > 0) to $('input',this).length == 0)

Thanks a lot!
Comment: but that may cause this scenario: user clicks to edit, changes data to 555, a request is made but not completed yet, then the user changes the data to 333, now this request goes faster (first got routed somewhere slow or got it's packet resent for some reason), now the user will see 333 in the field while on the server it's 555, cuz the 555 request arrived after the 333. What I did was unbinding while the request is running, then binding again: http://jsfiddle.net/eDJqL/
Answer: The most common way to do this would be to either disable the input, or set a flag that prevents the user from focusing on it / turning it into a edit field. For the latter, you can use jQuery data
The Ajax request's complete/success callback would lift the disabling, or the flag, again.
Answer: I did unbinding the event on click, then binding it again after AJAX request is done, to get rid of the following possible scenario (also posted as a comment above):

user clicks to edit, changes data to
  555, a request is made but not
  completed yet, then the user changes
  the data to 333, now this request goes
  faster (first got routed somewhere
  slow or got it's packet resent for
  some reason), now the user will see
  333 in the field while on the server
  it's 555, cuz the 555 request arrived
  after the 333.

Here's the result (You will see ugly alert, cuz the test is on jsfiddle.com, so it will go on the ajax error route).


Interpretation of continuous variable in an odds ratio for logistic regression

Question: I have an odds ratio of 1.02 for x variable (Age, a continuous variable measured in units "1 year"). My response variable is Y. I would interpret this as for every increase in Age by 1 year the odds of Y happening increase by 2%.
My question is can I say for every 10 year increase in Age, the odds of Y happening increase by 20% or would I have to group my continuous variable into 10 year categories to interpret this correctly?
Kind regards,
Comment: If it seems reasonable to extrapolate 10 years ahead *and* age has only a main linear effect without interactions with other predictors, then yes: since the logistic regresssion predicts the odds increase by 1.02 in 1 year, the increase is exp(log(1.02)*10) = 1.22 in 10 years. Obviously this doesn't say anything about the base odds. And odds are hard to interpret anyway, so you should consider converting the odds to probabilities and reporting those.
Comment: A note about terminology: logistic regression is expressed in terms of the log odds (not a log odds ratio).
Answer: Let's say your model, expressed in terms of odds,
$$ \dfrac{p}{1-p} = \exp(\beta_0 + \beta_1x) = B\exp(\beta_1x) $$
Here $B = \exp(\beta_0)$, and $\exp(\beta_1)=1.02$ as per your question.  A ten year increase in age would increase the odds by a factor of
$$ \exp(\beta_110) = \Big(\exp(\beta_1)\Big)^{10} \approx 1.22 $$
Comment: If you found this answer helpful, then please consider
[upvoting](https://stats.stackexchange.com/help/why-vote)
and/or
[accepting](https://stats.stackexchange.com/help/accepted-answer)
it.
Answer: If it is reasonable to extrapolate age by 10 years and if the effect of age is linear and without interactions, we can compute the odds at 10 years given the odds at 1 year.
If the logistic regression is linear in age, we can write:
$$
\text{odds} = \exp\{b_{\text{age}}age + \mathbf{b}_{-age}\mathbf{x}_{-age}\} = \exp\{b_{\text{age}}age\}\exp\{\mathbf{b}_{-age}\mathbf{x}_{-age}\}
$$
where $b_{\text{age}}$ is the age coefficient, $\mathbf{x}_{-age}$ are any other predictors incl. the intercept and $\mathbf{b}_{-age}$ are the rest of the regression coefficients.
You specify that age is measured in units of 1 year and that $\exp\{b_{\text{age}}\cdot1\} = 1.02$. From this we can estimate that at age = 10 years:
$$
\text{odds} = \exp\{\log(1.02)10\}\exp\{\mathbf{b}_{-age}\mathbf{-x}_{age}\} = 1.22\exp\{\mathbf{b}_{-age}\mathbf{x}_{-age}\}
$$
The odds are a function of both age and the other predictors (there is at least an intercept). And since odds are hard to interpret anyway, you should consider converting the odds to probabilities and reporting both.
More importantly — and this is where I went wrong in my comment as well — your statement seems to imply causality: that a subject will have 22% higher odds event Y in 10 years time. However, the regression results cannot be interpreted causally unless a lot of assumptions are made and/or a lot of requirements met.
The correct, if wordier way, to explain the odds is: Say subject A is 10 years older than subject B but otherwise matches B in all other predictors (eg. has the same education if education is also a covariate). Then subject A has 22% higher odds of event Y.
Comment: If you found this answer helpful, then please consider
[upvoting](https://stats.stackexchange.com/help/why-vote)
and/or
[accepting](https://stats.stackexchange.com/help/accepted-answer)
it.


Calculus of Variations-question on rotating curve of max volume

Question:
My calc of variations is still rusty.  I'm assuming implementation of arclength revolution formula is necessary, but how to find y(1/2a)?
Answer: We can decrease the problem to find the largest area in 2D because it will give the largest volume in rotating the curve.
The are to be maximized can be defined as
$$A[y]=\int_{x_1}^{x_2}y\ dx$$
subject to
$$2a=\int_{x_1}^{x_2}\sqrt{1+y'\ ^2} dx$$
We can use Lagrange multiplier such as
$$H=y+\lambda \sqrt{1+y'\ ^2}$$
and
$$\frac{\partial H}{\partial y}-\frac{d}{dx}\bigg(\frac{\partial H}{\partial y'}\bigg)=0$$
$$1-\frac{d}{dx}\bigg(\frac{\lambda y'}{\sqrt{1+y'\ ^2}}\bigg)=0$$
$$\Rightarrow \frac{x-\alpha}{\lambda}=\frac{y'}{\sqrt{1+y'\ ^2}}$$
If $\bar x=\frac{x-\alpha}{\lambda}$
$$\bar x=\frac{y'}{\sqrt{1+y'\ ^2}}\Rightarrow y'=\frac{dy}{dx}=\frac{\bar x}{\sqrt{1-\bar x^2}}$$
which can be solved for $y(x)$ such that
$$y(x)=-\sqrt{1-\bar x^2}+\beta=\beta-\sqrt{1-\bigg(\frac{x-\alpha}{\lambda}\bigg)^2}$$
The equation must satisf boundary conditions
$$(0,0)\Rightarrow 0=\beta-\sqrt{1-\bigg(\frac{-\alpha}{\lambda}\bigg)^2}$$
$$(a,0)\Rightarrow 0=\beta-\sqrt{1-\bigg(\frac{a-\alpha}{\lambda}\bigg)^2}$$
$$2a=\int_{0}^{a}\sqrt{1+y'\ ^2} dx\qquad y'=\frac{x-\alpha}{\lambda^2 \sqrt{1-\frac{\big(\alpha-x\big)^2}{\lambda^2}}}$$


How to remove unwanted form state values before validation

Question: What is the good way of validating a form in Drupal 8 ?
I have a bunch of fields which are supposed to be filled by a positive numeric value (and that's all, no other input types, just positive int).
public function validateForm(array &$form, FormStateInterface $form_state) {
$values = $form_state->getValues();

foreach ($values as $method => $fee) {
  if ($method != 'Free order') {
    if (!is_numeric($fee) || floatval($fee) < 0) {
      $form_state->setErrorByName($method, t('Value must be a positive integer.'));
    }
  }
}

}
The issue is when using $form_state->getValues() it also returns "submit", "form_token", "form_build", "form_id", "op" which is quite boring as those infos are not needed for performing validation.
So what I did is removing those four unwanted values with :
$values = array_splice($values, count($values) - 5, 5);

But it's really annoying, am I doing something wrong, or is just as it ? Because I think those values are really not necessary in the validation process.
Comment: The answer is correct, but there are two other alternatives that you might want to consider. a) If this is really everything you need, then just use #type number and #min => 0. That will cover that validation automatically, it will also do it already in the browser and e.g. mobile clients will automatically show a number-only keyboard. Everyone wins. b) Or, consider putting your elements inside a common key, just do something like $form['numbers']['#tree'] = TRUE, put them below that in the array and then $form_state->getValue('numbers') and you just get your elements, no cleaning necessary.
Comment: I was struggling a bit about how to get floated values with the 'number' field type. You actually have to put a '#step' of 0.01 for example if you want 2 decimal after the integer.
Answer: The FormState class has a method for that: FormState::cleanValues(). From its description, it's the method you should use.

This function can be used when a module wants to store all submitted form values, for example, by serializing them into a single database column. In such cases, all internal Form API values and all form button elements should not be contained, and this function allows their removal before the module proceeds to storage. Next to button elements, the following internal values are removed by default.

form_id
form_token
form_build_id
op

You simply call it before getting the submitted values.
public function validateForm(array &$form, FormStateInterface $form_state) {
  $values = $form_state->cleanValues()->getValues();

  foreach ($values as $method => $fee) {
    if ($method != 'Free order') {
      if (!is_numeric($fee) || floatval($fee) < 0) {
        $form_state->setErrorByName($method, t('Value must be a positive integer.'));
      }
    }
  }

Since FormState::cleanValues() returns the FormState object, you can simply call it in the same line you call  FormState::getValues() concatenating the two calls.
If you need to add more keys to remove from the submitted values, you could use FormState::setCleanValueKeys(), but keep in mind that:

The array passed to the method needs to contain also the default array keys Drupal would remove
The method alters the array keys that are removed from FormState::cleanValues() for every Drupal form


TCP listen on any IPv6 in a block on Debian

Question: I have a /64 block of IPv6 addresses, and I'd like to be able to start a TCP server listening on any one of them. Currently I can bind to any static IP address, but not any others. If I try to bind to an address not statically routed (by the way, I'm not sure if I'm using the right terms), I get an error message, "bind: cannot assign requested address".
Here's from ifconfig:
eth0      Link encap:Ethernet  HWaddr 56:00:00:60:af:c6
          inet addr:188.8.131.52  Bcast:126.96.36.199  Mask:255.255.254.0
          inet6 addr: fe80::5400:ff:fe60:afc6/64 Scope:Link
          inet6 addr: 2001:19f0:6801:187:5400:ff:fe60:afc6/64 Scope:Global
          inet6 addr: 2001:19f0:6801:187:ea1e:eb99:13ae:d49a/128 Scope:Global
          UP BROADCAST RUNNING ALLMULTI MULTICAST  MTU:1500  Metric:1
          RX packets:1526389 errors:0 dropped:0 overruns:0 frame:0
          TX packets:1622562 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:280302410 (267.3 MiB)  TX bytes:266740313 (254.3 MiB)

If I try to bind to e.g. 2001:19f0:6801:187:a:b:c:d, it fails with "bind: cannot assign requested address". But if I do ip -6 addr add dev eth0 2001:19f0:6801:187:a:b:c:d, then I'm able to start the server listening on that IP address.
How can I configure Linux so that I can listen on any 2001:19f0:6801:187::/64 address? That is, I want to bind to some specific IP address without having to ip addr add it first.
Or should I just have my server ip addr add an address before binding, then maybe ip addr del it when I'm done?
Addendum: In case my problem isn't clear, I've already gotten far enough that the whole prefix is getting routed to my server so that it can, for example, respond to pings for any address with that prefix. If I start a TCP listening on "[::]:80", it will respond to requests to any IP address. What I want is to be able to listen on a specific IP address so that only requests addressed to that IP address will hit the server. Other ServerFault questions linked to are asking how to get a server to respond to requests to any IP address. I've already gotten that far. I want to be able to bind to any arbitrary address, but only one specific one. The problem is that Linux won't even let me start the server on a specific address if that particular address isn't statically assigned to an interface, and I'd like to work around that.
To be even more concrete, I can presently run a TCP echo server on my VPS on all interfaces:
ncat -l 2000 --keep-open --exec "/bin/cat"

Then from my laptop, I can connect to it using any random IPv6 address:
telnet 2001:19f0:6801:187:: 2000
telnet 2001:19f0:6801:187:abc:def:: 2000
telnet 2001:19f0:6801:187:abc:def:123:0 2000

This all works. If I start the server on a statically assigned address, it also works:
ncat -l 2001:19f0:6801:187:5400:ff:fe60:afc6 2000 --keep-open --exec "/bin/cat"

Now I can only connect to that particular IP address. So far so good.
Now I'd like to be able to start a server on some random address:
ncat -l 2001:19f0:6801:187:abc:123:: 2000 --keep-open --exec "/bin/cat"

But I get an error: "Ncat: bind to 2001:19f0:6801:187:abc:123:::2000: Cannot assign requested address. QUITTING." But if I ip -6 addr add dev eth0 2001:19f0:6801:187:abc:123::/64, then the previous ncat command works, and the server starts and only responds to connections to 2001:19f0:6801:187:abc:123::.
So can I configure Linux to let me start a server on any arbitrary address in my block without first adding it as a static address?
(Actually, my question is very similar to https://stackoverflow.com/questions/40198619/can-docker-automatically-add-ip-addresses-to-the-host-upon-running-container, although there they're talking about IPv4. There the answer is to statically add all addresses.)
Comment: https://serverfault.com/questions/465889/linux-ipv6-how-to-bind-to-an-arbitrary-ipv6-address is similar.
Comment: Do you already understand the difference between a link prefix and a routed prefix? If not you could take a look at: http://serverfault.com/q/684455/214507
Comment: I probably don't understand the difference. Maybe it was already understood what I'm asking, but I tried to clarify.
Answer: The feature you are asking for appears to not be present in ncat, so you may have to download the source and add it yourself.
The way I verified whether the feature existed was as follows (done on Ubuntu 16.04 because that's the closest to a Debian system which I have immediate access to). First I tried to type the command to see if it is installed on my system:
$ ncat
The program 'ncat' is currently not installed. You can install it by typing:
sudo apt install nmap

So it is not installed, but is available in the nmap package. So I go ahead and download the source:
$ apt-get source nmap

And I look if IP_FREEBIND or IP_TRANSPARENT is used anywhere in that source code:
$ find nmap-7.01 -type f -print0 | xargs -0 grep -l 'IP_FREEBIND\|IP_TRANSPARENT'

That does not appear to be the case. So the next question is where in the source would we add it.
$ grep bind nmap-7.01/ncat/*c
nmap-7.01/ncat/ncat_connect.c:    /* TODO just two bytes for now, need to read more for bind */
nmap-7.01/ncat/ncat_main.c:            bye("-l and -s are incompatible.  Specify the address and port to bind to like you would a host to connect to.");
nmap-7.01/ncat/ncat_main.c:        /* Try to bind to IPv6 first; on AIX a bound IPv4 socket blocks an IPv6
nmap-7.01/ncat/util.c:        /* Tell it to not try and bind to IPV4 */
nmap-7.01/ncat/util.c:            die("Unable to set IPV6 socket to bind only to IPV6");
nmap-7.01/ncat/util.c:    if (bind(sock, &srcaddr_u->sockaddr, sa_len) < 0) {
nmap-7.01/ncat/util.c:            bye("bind to %s: %s.", srcaddr_u->un.sun_path,
nmap-7.01/ncat/util.c:            bye("bind to %s:%hu: %s.", inet_socktop(srcaddr_u),
nmap-7.01/ncat/util.c:        if (bind(sock, &srcaddr.sockaddr, sa_len) < 0) {
nmap-7.01/ncat/util.c:            bye("bind to %s:%hu: %s.", inet_socktop(&srcaddr),

The bind function is called from two places inside util.c, setting the IP_FREEBIND in one of those locations (or both) should do what you need.
Comment: Ah ha, didn't know about IP_FREEBIND and IP_TRANSPARENT. That's what I needed to know!
Comment: @TrevorDixon It is mentioned in the [other question](https://serverfault.com/a/591435/214507) which I linked to in my previous comment.


Is there a test statistic for poisson regression?

Question: I compared the number of pregnant women receiving specific health service indicators (deliveries, antenatal attendances and malaria prophylaxis uptake) at 14 facilities during three specific time periods; pre, during and after a project intervention; using the pre-intervention data set as the reference in a Poisson regression model, I calculated the Incident rate ratios and their confidence intervals and p-values. I have now been asked to run a test statistic to show whether the data sets pre, during and after the intervention are different or not. Is showing the IRR not enough and is there another test statistic beyond what I have just done?
here is an example of the STATA read out that I obtained on running an analysis.
My challenge is in interpreting the print out especially the LR chi2(2) and prob > chi2 results. what do they mean?
Answer: GLMs, including Poisson regression, have (asymptotic) tests that are akin to the corresponding familiar tests in regression.

Tests of individual coefficients: there's an asymptotic z-test (some packages refer to the statistic as a t-statistic, but in my opinion there's not really a good justification for calling it that; we're not estimating a dispersion parameter). Here's an example of such statistics (which is obtained by running the first example in the help on glm in R - which fortunately doesn't call it a "t" statistic):
 Coefficients:
               Estimate Std. Error z value Pr(>|z|)
 (Intercept)  3.045e+00  1.709e-01  17.815   <2e-16 ***
 outcome2    -4.543e-01  2.022e-01  -2.247   0.0246 *
 outcome3    -2.930e-01  1.927e-01  -1.520   0.1285
 treatment2   1.338e-15  2.000e-01   0.000   1.0000
 treatment3   1.421e-15  2.000e-01   0.000   1.0000

In this particular case, where each of the terms are levels of some factor, you wouldn't normally test them individually, but at least this gives an idea of where you look for the information.

Overall tests of the model

There's an overall asymptotic chi-square test of the model, based on the deviance, which is akin to the normal-theory F-test.
For an example, if we take another part of the summary output from the same model from the glm help in R as above:
    (Dispersion parameter for poisson family taken to be 1)

        Null deviance: 10.5814  on 8  degrees of freedom
    Residual deviance:  5.1291  on 4  degrees of freedom

then we obtain a chi-squared test for the model based on the difference, (10.5814-5.1291=5.4523) on (8-4=4) df

Tests of subsets of variables. Again, this is asymptotically chi-square.
In the case of factors, of course, you want to test a whole factor at once:
           Df Deviance Resid. Df Resid. Dev
 NULL                          8    10.5814
 outcome    2   5.4523         6     5.1291
 treatment  2   0.0000         4     5.1291

So, for example, to test the 'treatment' variable, you'd test it with a chi-square of 0.0 on 2 df (which of course is not significant; it contributes essentially nothing).
Any difference of two nested models could be compared similarly.
Comment: Here is the STATA read out for deliveries that I obtained. I should point out that statistics is not  something I excel at and clear lay-man interpretation of this print out would help me understand the read-out better.
Comment: user41816: The LR chi-square and prob>chi-square would presumably be the chi-square (and corresponding p-value) for the test of the model I describe in **2.** above. (You should check the documentation of your software to be absolutely certain.)


Custom block with a field value that can be used in other twig template

Question: I am creating a custom block with fields:

field_items_to_show (items to show)
field_logos (images, multiple)

The site editor must have the option to set the amount of items to show in a field.
in the twig field template field_logos I need the value from field_items_to_show

            {% for item in items %}
            {% if loop.index == 9 %} // this value must be set from field_items_to_show

            {% endif %}

{{ item.content }}

            {% endfor %}

Answer: In a field template you find the parent entity in the variable element['#object'], from where you can get field values of other fields:
{% set field_foo_value = element['#object'].field_foo.value %}


Liszt Campanella tricks or exercises

Question: I played the piano for years now, but stopped taking courses when I started college. I don't have time and budget, as a student, to take classes again, so that's why I'm asking here.
I am trying to learn Liszt's Campanella (just started). Thing is, I have fairly small hands, and I'm having a hard time hitting the right notes at the beggining (starting mesure 5) when playing at the right tempo. Do you have any exercise I could try to do, or any advice on how I could play it ? Or should I stick to the old, well known "play it slower hundreds of time and eventually you'll speed up" ?
Thanks !
Comment: You can try to separate the melody from the organpoint, by practising with the correct fingers, first the upper part, then the lower part. It's like practicing each hand by itself, but instead you solve one of the problems at a time. I think the answer you already received covers the jumps. Break down the problems: What makes this difficult? Identify as many aspects as possible and practice them separately.
Comment: one of the best exercises for movement - particularly with not-very-big hands - Chopin Etude 1 in C Major. The trick being not to stretch and to move the wrist to get the notes in (RH)
Answer: Well, yeah, the first four bars are the easy bit.... < grin >.
Just "playing it slower hundreds of times" won't work. Everybody can play this 100% accurately if they go slow enough to take aim at each individual note, one note at a time.
Start by playing scales (diatonic and chromatic) in jumps, for example

in 10ths C E' D F' E G' etc
or 12ths C G' D A' E B' etc
or double-octave jumps.

Start at a tempo where you have to use a continuous back-and-forth movement of your hand and arm, not pick off the notes one at a time - for example playing 8th notes at a tempo of about 80 BPM. Then speed up when that gets too easy ;)
Then try different sized jumps where you keep either the top note or the bottom note constant, for example

C C' C D' C E' C F' ..... C B' C C''.
C C'' D C'' E C'' F C'' ....

Concentrate on how the different sized jumps feel. When you start to get confident at playing these exercises accurately at a steady tempo, try them with your eyes closed!
Practice these with both hands (separately, and together.) The Liszt doesn't need your left hand to do this, but if you alternate between your hands you can practice for longer without getting tired, and really you are training your brain as much as your hands. (And being able to skip around the keyboard confidently with your left hand is useful in its own right, of course.)
Then you can get back to what Liszt actually wrote, and you should quickly make some real progress.
Comment: Yep, the "slower hundreds of time" didn't sounded that useful :p
I'll try this, thank you !

Liszt Campanella tricks or exercises


How can one prepare oneself to receive a slap in a slapping contest?

Question: I wonder what the techniques are to prepare oneself to receive a slap in a slapping contest (e.g., "Power Slap League"). I read techniques to improve the slap but didn't find any yet on the best way to receive it.
Comment: I strongly advise against participating in slapping contests. You will put yourself at rick of Chronic Traumatic  Encephalopathy (a form of brain damage), and other injuries to the beck and eardrums.
Comment: @Futilitarian I agree. Regarding CTEs, true for many sports:  https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5094259/ "It is estimated that between 1.6 and 3.8 million sports-related mTBIs occur annually, and sport-related head injuries make up 20% of TBI cases in the United States each year \[[10](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5094259/#b10-jvin-9-2-7),[11](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5094259/#b11-jvin-9-2-7)\]. This may be an underestimate, as mTBI frequently goes unreported." But esp. fighting + US football. Hence my interest in defense.
Answer: Power Slap president Frank Lamicella mentioned the following defense:

There is definitely defense. There is training the head, neck, shoulder muscles, and our sports science and sports data that we put out will start to support that.

Reddit Head catcher onejonejohnson mentioned the following defense:

Tensing the neck, clenching the jaw.


Which of these parameterize the parabola $y^2=x$? $(\sin^2t,\sin t)$, $(\cos^2t,\cos t)$, $(\sec^2t,\sec t)$, $(\tan^2t,\tan t)$

Question: In this question

I tried various different methods to solve it but was ending up with the same answer again and again and unfortunately that answer was not given in the options.
I did my working as shown below

I somehow believe that my answer is correct because if this is a parametric coordinate it should represent any point on this particular parabola.  Now for eg if we want to represent a point (0,0) we can do that as here $\theta$ would be 90 and hence $cot \theta$ = 0 . This doesn't hold true for the answer given in the answer key which is (D) $tan^2(\theta)$ , $tan \theta$ which becomes not defined at $\theta =90$ .
But I still could be wrong .
It would be greatly appreciated if somebody guides me through this problem.
Comment: Parametric representations are not unique. Try now to choose the parameter as the angle between $(h,k)$ and the $\color{red}y$-axis, i.e. $\theta_{new}=\frac{\pi}{2}-\text{your }\theta$.
Comment: I am still confused as to how did you get .\theta_{new}=\frac{\pi}{2}-\text{my }\theta$.
Comment: Just pick $\theta$ as $\color{red}{\text{the angle with }y\text{-axis}}$ instead and redo your calculations.
Answer: The problem (I believe) is supposed to be approached like this: we know that a parametric representation for this parabola is obviously $(y^2,y)$ where $y\in{\Bbb R}$. Hence a possible parametrisation (with the change of the parameter $y=f(\theta)$) could be $(f^2(\theta),f(\theta))$ provided that the range of $f$ is $\Bbb R$.
Now look at 4 options and chose that one where the second coordinate ranges over the whole axis. For example, (A) certainly does not work as $y=\sin\theta\in[-1,1]$, which is not $\Bbb R$, so with (A) we get only a part of the parabola, not the whole one, etc
Comment: Yeah but I gave the explanation as to why D can't work.  It does not represent (0,0) then why is it considered as the answer . isn't the whole point of a parametric coordinate to represent all points on the parabola
Comment: @gucci You give the explanation why it does not work **for your choice of the parameter $\theta$**, however the exercise does not tell your that you have to pick it as you did. For example, if you pick $\theta$ as the angle with $y$-axis then everything works fine with $\tan$ (and does not work with $\cot$). The problem with your solution is that you are stuck with this particular choice of the parameter which restricts you too much.
Comment: @gucci Your parametrisation is correct as many others (for example, $(y^2,y)$ as also correct). The problem is that you have to pick a correct one *among just 4 given* and not come up with yet another correct one.
Comment: Oh Ok thanks a lot but I had just one thing to clarify, my answer was also correct ,right? if it was given in the choices
Comment: @gucci Note that the complete parametrisation is supposed to be supplemeted by the range of the parameter. Thus, the answer $(\cot^2\theta,\cot\theta)$, $\theta\in]0,\pi[$ is correct, as well as $(\tan^2\theta,\tan\theta)$, $\theta\in]-\pi/2,\pi/2[$. The main lesson: in your solution you are doing a lot of unnecessary things trying to solve the problem bottom up.
Answer: As A.Γ said, the solution is obviously in the form $(f(t)^2, f(t))$.
Let us see if option $A$ works. For the function to be parameterised, then a $t$ must exist for any $k$ in $\sin t = k$. This is to say that if a horizontal line $k$ is drawn, then there must be an intersection between $\sin x$ and $k$ – we are looking for the range of the function.
Then the ranges of the following functions are:
$$\sin x \Rightarrow y \in [-1, 1]$$
$$\cos x \Rightarrow y \in [-1, 1]$$
$$\sec x \Rightarrow y \in [-\infty, -1] \cup [1, \infty]$$
$$\tan x \Rightarrow y \in [-\infty, \infty]$$
Therefore, only $(\tan^2 t, \tan t)$ can parametrise all of $y =x^2$.


Solve startActivity in fragment

Question: I have a problem in my code. My problem is related to the startActivity(). When the app is running on the emulator, it does not work. The line causing the problem is described in the end.
I tried to open a new activity (this, newactivity.class), however the problem persists.
UpdateAnsList
public class UpdateAnsList extends Fragment{

    /**
     * @param args
     */
    final static String ARG_POSITION_ANSWER = "position";
    private String jsonResult;
        private ListView listView;
    public int selsub;
    public Activity activity;
    public String tagsub;
    private Context mContext;
    private Activity mact;

    public UpdateAnsList(Activity _activity){
         mact = _activity;
        this.activity = _activity;
        super.onAttach(_activity);
        mContext = this.activity.getApplicationContext();
    }

    public enum SubSectionAnswer {
        TagArt,
        TagBio

    }

    public void StartUpdateAnsList(int v, String o){
        tagsub = o;
        selsub = v;
        SubSectionAnswer currentSub = SubSectionAnswer.valueOf(tagsub);
        listView = (ListView) this.activity.findViewById(R.id.listView11);

        selectItemAns(selsub,currentSub);
        accessWebService();
    }

    private void selectItemAns(int position, SubSectionAnswer currentSub) {

        switch(currentSub){

        case TagArt:

            switch(position){
            case R.id.buttonArt001:
                url = "myip/newfolder/question_2.php";
                tagdb = "info_general";
                break;

            case R.id.buttonArt002:
                url = "http://myip/newfolder/question_1.php";
                tagdb = "info_animation";
                break;

            case 2:

                break;

            }

            break;

        case TagBio:

            switch(position){
            case R.id.ButtonBio001:
                url = "http://myip/newfolder/question_4.php";
                tagdb = "info_general";
                break;

            case R.id.buttonBio002:
                url = "http://myip/newfolder/question_5.php";
                tagdb = "info_evolution";
                break;

            case 2:

                break;

            }

            break;

        }

    }

    // Async Task to access the web
    private class JsonReadTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(params[0]);
            try {
                HttpResponse response = httpclient.execute(httppost);
                jsonResult = inputStreamToString(
                        response.getEntity().getContent()).toString();
            }

            catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        private StringBuilder inputStreamToString(InputStream is) {
            String rLine = "";
            StringBuilder answer = new StringBuilder();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));

            try {
                while ((rLine = rd.readLine()) != null) {
                    answer.append(rLine);
                }
            }

            catch (IOException e) {
                // e.printStackTrace();
                //Toast.makeText(getApplicationContext(),
                //      "Error..." + e.toString(), Toast.LENGTH_LONG).show();
            }
            return answer;
        }

        @Override
        protected void onPostExecute(String result) {
            ListDrwaer();
        }
    }// end async task

    public void accessWebService() {
        JsonReadTask task = new JsonReadTask();
        // passes values for the urls string array
        task.execute(new String[] { url });
    }

    // build hash set for list view
    public void ListDrwaer() {
        List<Map<String, String>> employeeList = new ArrayList<Map<String, String>>();

        try {
            JSONObject jsonResponse = new JSONObject(jsonResult);
            JSONArray jsonMainNode = jsonResponse.optJSONArray(tagdb);

            for (int i = 0; i < jsonMainNode.length(); i++) {
                JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
                String name = jsonChildNode.optString("employee name");
                String number = jsonChildNode.optString("content_text");
                //String outPut = name + "-" + number;
                String outPut = name;
                String outPut1 = number;
                employeeList.add(createEmployee("Question", outPut,"textlong",number));
            }
        } catch (JSONException e) {
            Toast.makeText(this.activity, "Error" + e.toString(),
                    Toast.LENGTH_SHORT).show();
        }

        //new String[] { "employees" }
        //new int[] { android.R.id.text1 }
        String[] de = {"Question", "textlong"};
        int[] para ={R.id.textView1list11, R.id.textView11  };
        SimpleAdapter simpleAdapter = new SimpleAdapter(this.activity, employeeList,
                R.layout.activity_item_list_answer,
                de, para);
        listView.setAdapter(simpleAdapter);
        listView.setOnItemClickListener(new ListClickHandler());

        //Toast.makeText(getApplication(), "c", Toast.LENGTH_SHORT).show();

    }

    public class ListClickHandler implements OnItemClickListener{

        public void onItemClick(AdapterView<?> adapter, View view, int position, long arg3) {
            // TODO Auto-generated method stub
            int a =1 ;
            //Toast.makeText(mContext, "c", Toast.LENGTH_SHORT).show();
            //Intent i = new Intent(mact, QuestionActivity.class);
            //mContext.startActivity(i);

            // create intent to perform web search for this planet
                        Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
                        intent.putExtra(SearchManager.QUERY, "test");
                        // catch event that there's no activity to handle intent
                        mContext.startActivity(intent);

        }

    }

    private HashMap<String, String> createEmployee(String s1, String s2, String s3,String s4) {
        HashMap<String, String> employeeNameNo = new HashMap<String, String>();
        employeeNameNo.put(s1, s2);
        employeeNameNo.put(s3, s4);
        return employeeNameNo;
    }

}

This is the line causing the problem:
mContext.startActivity(intent);

Screen of debug:

Screen when I use getActivity():
Comment: Post your logcat please when the error happens
Comment: You Cannot Start Activity Using Context. You either need a reference to current activity or in case of fragment you can do it simply by
  getActivity().startActivity(new Intent(....));
Comment: Can you post your activity class also?
Comment: Your ListClickHandler class must be declaired as static first. I'll post a better practice to solve your problem later. Note: Fragment has its own startActivity method, you can use that, but wisely
Answer: You should start new Activity using Activity context:
getActivity.startActivity(intent);

Answer: Basically you are working with Fragment:
How to Start Activity from Fragment:
mContext.startActivity(intent);

Edit 1:
private Context mContext;

 public void StartUpdateAnsList(Context ctx, int v, String o){
        mContext = ctx;
        tagsub = o;
        selsub = v;
        SubSectionAnswer currentSub = SubSectionAnswer.valueOf(tagsub);
        listView = (ListView) this.activity.findViewById(R.id.listView11);

        selectItemAns(selsub,currentSub);
        accessWebService();
    }

Now you can use: mContext.startActivity(intent);
Hope this will help you.
Comment: How you can see. My getActivity is null. I do not know why
Comment: Be careful to call getActivity() only when the fragment is attached to an activity. When the fragment is not yet attached, or was detached during the end of its lifecycle, getActivity() will return null.
Answer: This is a Fragment class, so you are not able to pass an Intentby simply writing this.startActivity();
What you need to do is to get the Activity of this Fragment class.
So instead of mContext.startActivity(intent); you should write :
getActivity().startActivity(intent);

Solve startActivity in fragment


Where is the animation demo for Material Design Lite?

Question: Following the instructions of Material Design Lite's README, I have successfully build and served the local version of MDL website. I found that folder material-design-lite\dist\ was served.
What I curious about is, there is a folder called animation, and its path is material-design-lite\dist\components\animation. However, I can't seem to navigate to there by clicking here and there on MDL website. I can access through https://getmdl.io/components/animation/demo.html though.
Anyone have insight on this? Is there any place or thing that I overlooked?
Answer: Animation is not a component on its own per-say but just a quick set of classes to get our transitions in place if you need them.
There aren't any documents on this since explaining how and why it should be used gets into murky territory for documentation authors trying to explain it concisely.
Comment: Thanks for explaining. So the classes are actually reflecting this documentation [Duration and easing](https://www.google.com/design/spec/motion/duration-easing.html#duration-easing-natural-easing-curves), minus the `Sharp curve`, is that correct?
Comment: The classes are our best setup for Material Animations on the web. As far as where exactly they came from, I do not know myself since I didn't build them. I'd assume they were as specific to the specification as they could get.


Finding variance of AR process

Question: $\newcommand{\E}{\mathbb{E}}$How do I find the variance of an autoregressive AR(1) process $$y_t=\phi y_{t-1}+\varepsilon_{t}$$
where $\lvert {\phi}\rvert<1$ and knowing that
$$y_t=\sum_{j=0}^\infty \varphi_j\varepsilon_{t-j}$$
$\E(\varepsilon_t)=0,\ \E(\varepsilon^2_t) = \sigma^2,\ \E(\varepsilon_t\varepsilon_s)=0$ for $s\ne t,\ $ $\sum_{j=0}^\infty \varphi^2_j<\infty$ and
$\operatorname{Var}(y_t)=\sigma^2\sum_{j=0}^\infty \varphi^2_j$
Answer: $$\text{Var}(y_t)=\text{Var}(\phi y_{t-1}) + \text{Var}(\varepsilon_{t}).$$
As we know, $E(\varepsilon_{t}^2)=\sigma^2$. Then we have:
$$\text{Var}(y_t)=\text{Var}(\phi y_{t-1}) + \sigma^2.$$
Now using variance properties we take out $\phi$ from the variance:
$$\text{Var}(y_t)=\phi^2\text{Var}(y_{t-1}) + \sigma^2.$$
Given that $\text{Var}(y_t)=\text{Var}(y_{t-1})$ we solve to get:
$$\text{Var}(y)=\frac{\sigma^2}{1-\phi^2}.$$
Comment: and if I get the calculations right, it should be $var(y)=\frac{(σ^2)}{1-ϕ^2}$, no?
Comment: Thank you! Could you please elaborate, why $var(y_t)=var(y_{t−1})$?
Comment: you assume variance to be constant over time, so there is no heteroskedasticity, it is to say, different variances across time. This implies: $var(y_t)=var(y_{t-1})$
Answer: $$y_t = \varepsilon_{t} +\phi y_{t-1}= \varepsilon_{t} +\phi (\varepsilon_{t-1} +\phi y_{t-2}) = \sum_{j=0}^{\infty}\phi^j \varepsilon_{t-j},$$ and If $|\phi|<1$, then  $$\text{Var}(y_t) = \sum_{j=0}^{\infty}(\phi^j)^2 \text{Var}(\varepsilon_{t-j})=\sigma^2 (1+\phi^2+\phi^4+\dots) = \sigma^2\frac{1-\lim_{n \rightarrow \infty} \phi^{2n}}{1-\phi^2} = \frac{\sigma^2}{1-\phi^2}.$$
P.S. From here, we can conclude that $\text{Var}(y_t)$ isn't a function of time.

Finding variance of AR process


inApp Purchase in iOS products returned no product in the response

Question: I am following tutorial of raywenderlich on the following blog:
http://www.raywenderlich.com/2797/introduction-to-in-app-purchases
Everything is working fine in the code, all delegate methods are being called properly, but still there is no product returned against product identifiers
<code>- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {

    self.products = response.products;
    NSLog(@"products array count= %i", [self.products count]);  //products array count=0  :(
}
</code>
Has anyone tried the same code, can suggest me what is the problem in it ?
<code><SKProductsRequestDelegate, SKPaymentTransactionObserver>
</code>
are used in this tutorial,
i've successfully created product identifier and app id. so only problem is to load that product against identifier. is there any other classes or InApp reusable code  which you think is suitable than this?
already spent whole day to fix the problem, finally posted here to get help.
Thanks
Comment: if anyone already followed the above tutorial and faced same problem then kindly guide me. or any sample code will be appreciated :)
Answer: There can be a lot of places where in-app purchase set up can go wrong. And the problem is often not within the code. I found this checklist very helpful:
Invalid product IDs