What is obtained from the product of a probability and a log probability ratio?

Question: I'm looking at the commonly used artificial neural network model that has nodes and connections.
Quick refresher

A connection has a source and target node, and a weight. The output of the source node is multiplied by the weight to give the connection's output value.
A node sums the value of each connection feeding into it, and applies a sigmoid activation function. This is the node's output value.
A commonly used activation function is the logistic function.

I'm just exploring some ideas around this commonly used model. So for instance, the logistic function is the inverse of the logit function. That's interesting because the logit function is commonly used to calculate a log-odds from a probability. Therefore if we work backwards we can think of the summed input into the activation function as being a log-odds value.
So let's say we have one input node (x), one output (y), and one connection (w) then we have:
y = logitInverse(xw)

(logitInverse being the sigmoid logistic function, same thing).
We've inputed xw into logitInverse() function, so in one sense we are treating xw as a log-odds value. But x was the output from a previous node so is from the output of a previous node's logitInverse() and it can therefore be considered to be a probability with range [0,1]. Hence we have multiplied a probability (x) with a log-odds (w) and treated the result as a log-odds (the input to logitInverse).
Regarding w. This definitely hints at being amenable to being treated as a log-odds value since the range 'fits', e.g. typically a weight would be observed to be in the range [-5,5] (but could go far beyond that), but crucially a weight of zero corresponds with a probability of 50% [ consider log(50/50) = 0 ], i.e. the target node is not correlated with the source node.
So everything sort of fits, except we multiply a probability (x) with a log-odds (w) and treat it as a log-odds.
Final thought. Again, taking w to be a log-odds value, then we can write it as:
w = log(a/b)

And we multiply xw, therefore we have:
xw = x * log(a/b) = log((a/b)^x)

I have no idea if that has any significance on the question or not.
Comment: You have a lot of background here, can you clarify your actual question?
Comment: Sorry, I must have missed the "ratio". That isn't standard, though. It is definitely conventional to refer to "odds". I'm not sure I've ever heard "probability ratio". To me that connotes *risk ratio*, which is definitely not the same thing as odds.
Comment: (Also note that the logit is not used to calculate a log probability, the logit transformation converts a probability into the log odds.)
Comment: I very specifically used the term 'log probability ratio'; is it more common place to refer to it as log probability odds? (I think of 'odds' as being old fashioned terminology, but that might be just me). The title question pretty much covers it - what actually is the value that we get by multiplying a probability with a log probability odds? Is it another log probability odds? or something else?
Comment: @gung Thanks. I've updated the Q to use the term 'log-odds'.
Comment: i think you should just read up on logistic regression to understand the modelling approach.
Answer: I don't believe it is any specific kind of animal, in the sense that probabilities and odds are specific kinds of things.  I think its just a number.
(I'll admit that this doesn't seem like much of an answer, but I don't think there's anything more to it than that.)

Edit: I may still be misreading this, but let me note that w is not a log-odds, it is just some number that is adjusted throughout the training of the neural network to optimize the network's predictive accuracy.  It could be anything.  In your setup, xw is treated as though it were a log odds, in the sense that xw is passed through the logistic / inverse logit function.  Then, y becomes a number that is like a probability in the sense that it now varies within the interval $(0,\ 1)$.  For completeness, if we are moving from the input layer to the hidden layer, x could be any number as well (in many machine learning contexts, x is a binary feature indicator—0/1—but it could be a continuous value).  If we are moving from the hidden layer to the output layer, your new x is your old y, so it can be thought of as analogous to a probability.


Como criar uma Animação no JavaScript usando For

Question: Estou tentando fazer uma
 ter o background alterado para as três cores primarias, no caso Yellow, Blue e Red, porem só começaria a alterar a cor 4 segundos depois da pagina ser atualizada, escrevi uma função que é chamada 4 segundos depois da pagina atualizar, porem as cores não mudam, na verdade ele ignora as primeiras cores e pula direto para a ultima, e não ocorre o efeito de animação, simplesmente fica vermelho, segue a baixo o código...

Eu quero que altere entre as 3 cores, que mostre as cores mudando na tela, mas necessito que seja com a estrutura de repetição for ou while, porquê talvez eu precise deixar isso rodando infinitamente.
Answer: Para fazer animação em Javascript, com navegadores modernos, deve-se usar o método window.requestAnimationFrame() que informa ao navegador que deseja-se realizar uma animação e pede ao navegador que chame uma função específica para atualizar um quadro de animação antes da próxima repintura.
O método tem como argumento uma callback que será invocado antes da repintura. Por sua vez o callback possui um único argumento um DOMHighResTimeStamp, que indica o momento no qual o callback foi enfileirado por requestAnimationFrame().
O número de callbacks invocados está normalmente na ordem de 60 chamadas por segundo, mas normalmente acompanha-se a taxa de atualização do display na maioria dos navegadores, como recomenda a W3C.
Nesse exemplo é criada uma animação que inicia após 4s e vai trocando as cores de um
.

var inicio = null; //inicio da animação
var cores = ['yellow', 'blue', 'red']; //Array de cores
let elem = document.getElementById("colorido");

requestAnimationFrame(mudarCor);

function mudarCor(tempo) {

  if (!inicio) inicio = tempo;

  // Aguarda 4s antes de iniciar a animação
  if ((tempo - inicio) > 4000) {
    //Escolhe uma cor "aleatoriamente" e muda a atual
    elem.style.background = cores[Math.floor(Math.random() * cores.length)];
  }

  //Faz a requisição do próximo quadro
  requestAnimationFrame(mudarCor);
}
#colorido {
  width: 100px;
  height: 100px;
  background: red;
}

Aviso!!!
Se você sofre com epilepsia ou fotossensibilidade não veja esse exemplo

Se quiser um efeito menos intenso basta fazer as mudanças em uma frequência menor

var inicio = null; //inicio da animação
var ultima = null; // momento da última atualização
var cores = ['yellow', 'blue', 'red']; //Array de cores
let elem = document.getElementById("colorido");

requestAnimationFrame(mudarCor);

function mudarCor(tempo) {

  if (!inicio) {
    inicio = tempo;
    ultima = tempo;
  }

  // Aguarda 4s antes de iniciar a animação
  if ((tempo - inicio) > 4000) {
    // Só troca a cor a cada 0,5s
    if (tempo - ultima > 500) {
      //Escolhe uma cor "aleatoriamente" e muda a atual
      elem.style.background = cores[Math.floor(Math.random() * cores.length)];
      ultima = tempo;
    }

  }

  //Faz a requisição do próximo quadro
  requestAnimationFrame(mudarCor);
}
#colorido {
  width: 100px;
  height: 100px;
  background: red;
}

Aviso!!!
Se você sofre com epilepsia ou fotossensibilidade não veja esse exemplo

Answer: Nessa caso, para a cor ser alterada dentro de um intervalo de tempo, o ideal é utilizar o setInterval() em vez do setTimeout(), pois ele será executado repetidamente.
Exemplo usando o setInterval():


Quantidade de decrementos em um dataframe

Question: Possuo um data frame onde em cada coluna é o valor de eventos no período, preciso calcular o incremente e o decremento desses períodos para uma base maior e não consegui fazer:
p1<- rep(2:11)
p2<- rep(3:12)
p3<- rep(1:10)
p4<- rep(4:13)

base<- cbind(p1,p2,p3,p4)

base
      p1 p2 p3 p4
 [1,]  2  3  1  4
 [2,]  3  4  2  5
 [3,]  4  5  3  6
 [4,]  5  6  4  7
 [5,]  6  7  5  8
 [6,]  7  8  6  9
 [7,]  8  9  7 10
 [8,]  9 10  8 11
 [9,] 10 11  9 12
[10,] 11 12 10 13

esperado:
       p1 p2 p3 p4 in dc
  [1,]  2  3  1  4  2  1
  [2,]  3  4  2  5  2  1
  [3,]  4  5  3  6  2  1
  [4,]  5  6  4  7  2  1
  [5,]  6  7  5  8  2  1
  [6,]  7  8  6  9  2  1
  [7,]  8  9  7 10  2  1
  [8,]  9 10  8 11  2  1
  [9,] 10 11  9 12  2  1
 [10,] 11 12 10 13  2  1

Ou seja, tomando como exemplo a linha 9:
[9,] 10 11  9 12  2  1

comparando o p2 com o p1 houve um incremento (10 > 11)
para o período 3 houve um decremento (11 > 9)
para o período 4 houve outro incremento (9 > 12) totalizando 2 incrementos e um decremento.
A ideia é executar isso para um conjunto de 500 variáveis visualizadas em 10 períodos.
Comment: Teria como você explicar de forma mais clara o que seria o incremento e o decremento em questão?
Comment: concordo que não estava claro, obrigado pelo feedback, fiz uma alteração veja se me fiz entender!
Comment: O que deve acontecer se não incremento? Por exemplo, se originalmente a linha 9 fosse `10 11 11 12`, qual deveria ser o resultado? `10 11 11 12 2 0`? Ou algo diferente?
Comment: correto, dado que não houve incremento é 0, so preciso contar os incrementos entre as linhas do data frame
Answer: Primeiro usarei a função diff para calcular a diferença entre duas colunas consecutivas. É necessário transpor o resultado para que ele fique no mesmo padrão de base:
diferencas <- t(apply(base, 1, diff))
diferencas
      p2 p3 p4
 [1,]  1 -2  3
 [2,]  1 -2  3
 [3,]  1 -2  3
 [4,]  1 -2  3
 [5,]  1 -2  3
 [6,]  1 -2  3
 [7,]  1 -2  3
 [8,]  1 -2  3
 [9,]  1 -2  3
[10,]  1 -2  3

Isto posto, vou contar quantos incrementos há por linha. Isto é, vou contar quantos valores de diferencas são maiores do que 0:
in <- apply(t(apply(diferencas, 1, function(x) x > 0)), 1, sum)

De mono análogo, vou contar quantos decrementos há por linha. Isto é, vou contar quantos valores de diferencas são menores do que 0:
dc <- apply(t(apply(diferencas, 1, function(x) x < 0)), 1, sum)

Note que isto funciona porque, para o R, TRUE tem valor 1. Agora só preciso juntar os resultados:
cbind(base, in, dc)
      p1 p2 p3 p4 in dc
 [1,]  2  3  1  4  2  1
 [2,]  3  4  2  5  2  1
 [3,]  4  5  3  6  2  1
 [4,]  5  6  4  7  2  1
 [5,]  6  7  5  8  2  1
 [6,]  7  8  6  9  2  1
 [7,]  8  9  7 10  2  1
 [8,]  9 10  8 11  2  1
 [9,] 10 11  9 12  2  1
[10,] 11 12 10 13  2  1


Vue3: Add value to array or proxy

Question: Let's start of with what I'm trying to do: I want to create an app in which I can list IP addresses and the user can add as many as they want. The app starts with 1 input field and with the press of a + button it should show the user an extra input field. I'm trying to add these IP addresses to an array which I can loop through later on.
Vue 3 however turns my basic array into a proxy, I've tried to understand how to use proxies (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) but I can't find out how to add a basic item to the end of the array (proxy?). Using v-for I'm generating the amount of input fields based on how many items the array holds, but let's not get into that seeing that that is not the problem I'm facing.
Here's my first code snippet:
export default {
  data() {
    return {
      addresses: ["192", "193"],
    };
  },
  methods: {
    addIp() {
      this.addressses.push(194);
      // using 194 as an example but I'd like the new item to be empty
    },
}

For some reason however this is not adding 194 to the end of the array, it's not really doing anything. When I log the this.addresses it returns a proxy so Vue changed my basic array to a proxy, which is fine, I think.
I've looked up how to add items to an array/proxy in Vue 3 (How can I push to an array (in Vue 3)?) but for some reason it doesn't work for my code.
I've also tried this.addresses.push({2: 194}) to see if I had to force the item to the second position, which broke my code.
Main questions that I have regarding this issue:

Does the array really need to be changed to a proxy and why?
What am I missing/doing wrong if I'm trying to add to a proxy?
For later, how do I loop through a proxy?

EDIT:
<template>
<form class="serviceForm" @submit.prevent>

    IP Adress
    <button @click="removeIp">-</button>
    <button @click="addIp">+</button>

  <input
    type="text"
    v-for="(address, index) in addresses"
    :key="index"
    v-model="addresses[index]"
    name="ipAddress"
    class="ipAddress"
  />

</form>
<button @click="generateServiceList">Test services</button>
</template>

Above is the code I'm using to generate the input fields.
I'm using the console to check wether or not I have values in my array and if something is added to the array when I press the + button, should I do that somewhere else and if so: where?
Comment: You seem to pay too much attention to the proxy part. It's just implementation detail that needs to be taken into account. Reactivity worked without proxies in very similar way in Vue 2. Consider focusing instead on the problem you try to solve. "doesn't work for my code." - which code? Currently the question doesn't contain https://stackoverflow.com/help/mcve , the problem cannot be reproduced. It's unknown how you observe values. console should not be used for debugging.
Comment: There's a typo in addressses, and 194 is a number and not a string. Otherwise .push(194) will result in ["192", "193", "194"] array without any pitfalls or concerns related to a proxy
Comment: @EstusFlask Thank you for your replies. I've added code to show how I'm generating the input fields. I've also tried to add "194" instead of 194, but it gives me the error `Cannot read properties of undefined (reading 'push')`. Can you guide me as in where to look first?
Comment: The comment above. There is a typo. It's addresses in one place and addressses in another. This is the perfect reason and seemingly the only one why it's undefined
Answer: If I understood you correctly, take a look at following snippet:

const app = Vue.createApp({
  data() {
    return {
      addresses: ["192", "193"],
      ip: ''
    };
  },
  methods: {
    addIp() {
      this.addresses.push(this.ip);
      this.ip = ""
    },
  }
})
app.mount('#demo')

    {{ i + 1 }}<input v-model="addresses[i]" />

  <input v-model="ip" />
  <button @click="addIp">Add</button>

{{ addresses }}

Vue3: Add value to array or proxy


Interior estimates for $H^1$-norm of solutions of divergence-type elliptic PDE

Question: Let $u\in H^1(\Omega)$ be a weak solution of $Lu=f$, where the coefficients of $L$ satisfy $a^{ij}{\xi}_i {\xi}_j \ge \lambda {|\xi|}^2$ for any $x\in \Omega$, $\xi \in {\mathbb{R}}^n$ and ${\|a^ij\|}_{\infty},{\|b^ij\|}_{\infty},{\|c^ij\|}_{\infty} \le \Lambda$, where both $\lambda$ and $\Lambda$ are positive constants. Assume that $f\in L^2(\Omega)$. Derive an estimate for ${\|u\|}_{H^1(\Omega')}$ for any open subset $\Omega'\Subset\Omega$.

I attempted to prove ${\|u\|}_{H^1(\Omega')}\le C({\|u\|}_{\infty}+{\|f\|}_{\infty})$ but that is wrong. The answer says ${\|u\|}_{H^1(\Omega')}\le C({\|u\|}_2+{\|f\|}_2)$, where $C=C(n,\lambda,\Lambda,\textrm {dist}(\Omega', \partial\Omega))$ and I cannot work that out.
Comment: Typographical suggestion: `$\|u\|$`  instead of `$||u||$` makes nicer norm notation.
Answer: This is a typical energy estimate for an elliptic PDE. Recall that the divergence-type operator
$$
Lu = \sum_{i} \left(D_i \left(\sum_j a^{ij}D_ju + b^i u\right) + c^i D_i u \right)
\tag1$$
is associated with a bilinear form
$$
\mathcal L(u,v) = \int_\Omega \left\{\sum_{i} \left(\sum_j a^{ij}D_ju + b^i u\right)D_i v -( c^i D_i u )v \right\}
\tag2$$
The weak form of the equation $Lu=f$ is $$\mathcal L(u,v) + \int_{\Omega} fv = 0 \tag3$$ for every test function $v$, which can be taken from $H^1_0(\Omega)$ (the test function must vanish on the boundary).
Pick a smooth cut-off function $\varphi$ that has compact support in $\Omega$ and is identically $1$ on $\Omega'$. This can be done so that $|D\varphi|\le C/\operatorname{dist}(\Omega', \partial \Omega)$. Put $v=u\varphi$ in (3) and write out all of the terms. The main one is
$$
\int_\Omega \varphi \sum_{ij}a^{ij}D_juD_iu  \ge \lambda \int_{\Omega'} |Du|^2
$$
The rest involve at most one derivative of $u$, and are handled with weighted Cauchy-Schwarz inequality,
$$2|ab|\le \epsilon a^2 + \epsilon^{-1}b^2$$
so that any $|Du|^2$ you get has tiny coefficient, which will be dominated by $\lambda$. E.g.,
$$
\left| \int_\Omega u D_j u \right| \le  \frac{\epsilon^{-1}}{2} \int_\Omega u^2   + \frac{\epsilon}{2} \int_\Omega  |Du|^2
$$
When the dust settles, (3) leads to
$$
 \int_{\Omega'} |Du|^2 \le C \int_{\Omega} (u^2 + f^2)
$$
as claimed.


Show that if $|f(z)| \leq M |z|^n$ then $f$ is a polynomial max degree n

Question: I can't prove this statement, can anybody show me how to prove it?
$$f:\mathbb{C}\rightarrow \mathbb{C} \in \mathcal{O}(\mathbb{C}), \exists n\in \mathbb{N}, R >0 , M>0 : |f(z)| \le M|z|^{n} \ \ \forall |z|>R \Rightarrow \deg(f)\le n $$
To show is that if there exists such an $M$, that then $f$ is a polynomial of max degree $n$. I started like this:
$$f(z) = \sum_{n=0}^{\infty} a_n (z-z_0)^n$$ So if I put this into the inequality: $$|f(z)| = \left| \sum_{n=0}^{\infty} a_n (z-z_0)^n \right| \le M |z|^n .$$
Comment: Remark: there is a list of similar questions [here](https://math.meta.stackexchange.com/a/34548/80734)
Answer: We have for $k\geq 1$, $z_0\in\mathbb C$ fixed and $r$ such that $\{z,|z-z_0|=r\}\subset\{z\in\mathbb C,|z|\geq R\}$, we have thanks to the Cauchy integral formula
$$f^{(n+k)}(z_0) =\frac{(n+k+1)!}{2i\pi}\int_{C(z_0,r)}\frac{f(z)}{(z-z_0)^{n+k+1}}dz,$$
hence
$$|f^{(n+k)}(z_0)|\leq \frac{(n+k+1)!}{2\pi}\int_{C(z_0,r)}M\frac{|z|^n}{r^{n+k+1}}\leq \frac{(n+k+1)!}{r^{n+k+1}}M(r+|z_0|)^n.$$
Since it's true for $r$ large enough, we get that $f^{(n+k)}(z_0)=0$ for each $z_0$ and $k\geq 1$, which show that $f$ is a polynomial of max degree $n$.
Comment: @GeneralMathematics By the triangle inequality, $|z|\leq |z-z_0|+|z_0|=r+|z_0|$.
Comment: @DavideGiraudo I got a bit confused, why exactly do we deduce that n is the maximum degree?
Comment: The degree cannot be larger than $n$ because $|f(z)|\leqslant |z|^n$ (consider this inequality for $z$ with large modulus).
Comment: @DavideGiraudo Hi, I faced the same problem but I am restricted to use the coefficients of the Taylor series for $f$ to prove it. So any hint or guidlines? Thanks
Comment: @DavideGiraudo can we solve it using rouché's theorem?
Comment: Sir, can you explain the last step? I mean how you get $M(r+|z_0|)^n$?
Comment: Thanks sir, for replying to such an old post.


Is there a math term for a modificated minimum spanning tree?

Question: I have found a minimum spanning tree (left figure).
Then I have applied some modification:

The edge A-B (red) was added,
The edge C-D (green) was rewritten to C'-D.

Edit. I don't delete the vertices.

Steps 1-2 can be repeated more that one time for different edges.

Question. Is there a math term for an obtained graph (right figure)?

Answer: Well...it's no longer a tree, so I guess the best I can say is that it's a spanning subgraph. I'm not sure whether your "modifications" always preserve the property that the new graph contains all the vertices. If not, then you can just say "it's a subgraph."
Comment: I don't delete the vertices.
Comment: It is more than a subgraph : it is a $1$-tree.
Comment: In view of Nick's comment on your answer: I don't think it *is* a 1-tree. :) It's tough to know without a description of all possible "modifications."
Answer: There is a term for this subgraph with a unique cycle: it is a $1$-tree.
Some authors also call it a pseudotree.
Comment: In my case I can add more than one cycle.


Show that $\lim_{n \rightarrow \infty} \frac{\Sigma_{i=0}^k \binom{n}{3i}}{2^n} = \frac{1}{3}$

Question: Let $n =  3k$  . Show that $\displaystyle{\lim\limits_{n \rightarrow \infty} \frac{\Sigma_{i=0}^k \binom{n}{3i}}{2^n} = \frac{1}{3}}$ . In other words, the sum of every third element of the nth row of the Pascal triangle is roughly one third of the sum of all elements of that row; after this,  generalize the result.
attempt:
$\displaystyle{\begin{array}{ll}
\lim\limits_{n \rightarrow \infty} \displaystyle{\frac{\Sigma_{i=0}^k \binom{3k}{3i}}{2^n}} & = \\\\
\lim\limits_{n \rightarrow \infty} \displaystyle{\frac{\binom{3k}{0} + \binom{3k}{3} + \binom{3k}{6} + \cdot \cdot \cdot + \binom{3k}{k} }{2^n}} & = \\\\
\lim_\limits{n \rightarrow \infty} \displaystyle{\frac{\frac{3k!}{0! 3k!} + \frac{3k!}{3!(3k-3)!} + \frac{3k!}{6!(3k-6)!} + \cdot \cdot \cdot + \frac{3k!}{3k!(3k - 3k)!} }{2^n}} & = \\\\
\lim_\limits{n \rightarrow \infty} \displaystyle{\frac{\frac{1}{1} + \frac{3k (3k-1)(3k-2)(3k-3)....2 \cdot 1}{3!(3k-3)!} + \frac{3k(3k-1)(3k-2)...(3k-6)...2.1}{6!(3k-6)!} + \cdot \cdot \cdot + \frac{1}{1} }{2^n}} & = \\\\
\lim_\limits{n \rightarrow \infty} \displaystyle{\frac{\frac{1}{1} + \frac{3k (3k-1)(3k-2)(3k-3)}{3!} + \frac{3k(3k-1)(3k-2)...(3k-5)}{6!} + \cdot \cdot \cdot + \frac{1}{1} }{2^n}}
\end{array}}$
I am stuck. If $n = 3k$ approaches infinity then it seems that we would have $0$ on the numerator and so the expression would go to $0$ and not $1/3$ .
Could someone please help me ? and give me some feedback. Thank you
Comment: Editing: I used displaystyle and array, your version was very small for reading.
Comment: You should probably have $2^n$ (the sum of all the entries in the $n$-th row) and not $2$ in the denominator.
Comment: Your question in combinatoric language is in the following form. If we have a set of size $n$, why the ratio of all subsets of size $0$ to $3k$ to all subsets of the set, tend to $\frac{1}{3}$ when $n$ is an enough large number.
Answer: Let $\omega=\exp\left(\frac{2\pi i}{3}\right)$. The characteristic function of the integers $n$ of the form $3k$ can be written as $\frac{1+\omega^n+\omega^{2n}}{3}$ (this is the principle behind the discrete Fourier transform) hence
$$ \sum_{i\geq 0}\binom{n}{3i} = \frac{1}{3}\sum_{k=0}^{n}\binom{n}{k}(1+\omega^k+\omega^{2k})=\frac{2^n+(1+\omega)^n+(1+\omega^2)^n}{3}$$
and accidentally both $1+\omega$ and $1+\omega^2$ have unit modulus, hence the term $(1+\omega)^n+(1+\omega^2)^n$ is bounded by $2$ in modulus, regardless of $n$. It follows that
$$ \lim_{n\to +\infty}\frac{1}{2^n}\sum_{i\geq 0}\binom{n}{3i}=\color{red}{\frac{1}{3}} $$
as wanted. In other terms,

If we consider a random subset of $\{1,\ldots,n\}$, its cardinality equals $3k$ for some $k\in\mathbb{N}$ with a probability closer and closer to $\frac{1}{3}$ as $n$ increases.

That holds also if $3$ is replaced by $4,5,6,7,\ldots$, but the speed of convergence is quite different: to prove it (through the DFT) is an interesting exercise I leave to the reader / to the OP.
Comment: First time I see this characterization of $\chi_{kn}$ with roots of unity, although it seems so obvious now that I see it. I mean I have already used similar tricks like in calculating $\sum\frac 1{5n!}$ for instance, but it never tilted as a general principle for selecting some given multiples of $n$.
Comment: thanks for your answer. But I could not find this principle in my book, I have not learned this. Do you think I can still apply this for a combinatorics class?
Comment: @Mahidevran: the DFT is a key technique in (analytic) combinatorics, and I am not aware of simpler methods for proving the same, hence definitely yes.
Answer: $\newcommand{\bbx}[1]{\,\bbox[8px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$

As $\ds{k \to \infty}$:

\begin{align}
{1 \over 8^{k}}\sum_{i = 0}^{k}{3k \choose 3i} & \sim
{1 \over 8^{k}}\sum_{i = 0}^{k}
{3k \choose 3k/2}\exp\pars{-\,{6\bracks{i - k/2}^{2} \over k}}
\\[5mm] & \sim
\root{\pi \over 6}{k^{1/2} \over 8^{k}}{3k \choose 3k/2} \to
\bbx{\ds{{1 \over 3}\quad\mbox{as}\ k \to \infty}}
\end{align}

That is an application of 'Laplace Method for Sums' as explained in, for example, page $761$ of $\ds{\bbox[8px,#efe,border:1px dotted navy]{Analytic\ Combinatorics}}$ by Philipe Flajolet and Robert Sedgewick, Cambridge University Press 2009.


Stop text input with 100% width and 10px padding extending beyond 100% width

Question: I am styling a text input with 100% width and 10px padding like this:

    Outer element
    <form method="get" id="searchform" action="#">
        <input type="text" class="field" name="s" id="s" placeholder="Search here...">
        <input type="submit" class="submit" name="submit" id="searchsubmit" value="GO">
    </form>

CSS:
.wrapper {
    background: #ccc;
    padding: 20px;
    width: 200px;
}

#s {
    width: 100%;
    display:block;
    padding: 10px;
}

#searchsubmit {
    display: block;
    width: 100%;
    padding: 10px;
}

The problem is the text input extends beyond the width of the wrapper. See example here.
I've tried adding "box-sizing: border-box" and -moz-box-sizing: border-box" but I'm still seeing the input extending beyond 100% on certain browsers e.g. Android.
Is there a solution to this?
Answer: Use box-sizing:
#s {
    width: 100%;
    display:block;
    padding: 10px;
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}

Here is a demo.
Note: It's supported by all major browsers since IE8. For Android just don't forget the -webkit prefix. More Details
Answer: Remove left and right padding. If you need padding, play with width.
#s
{
    width: 99%;
    display:block;
    padding: 10px 0;
}


No backtrace from SIGABRT signal on ARM platform?

Question: I'm using 'backtrce()' and 'backtrace_symbols_fd()' functions in a signal handler to generate a backtrace for debugging (GDB not available).
They work fine on x86 desktop (Ubuntu), but on the target device (ARM based) the backtrace on Abort signal (due to double-free error) shows only three frames: the signal handler and two from within libc, which is not useful for debugging our code! Backtrace on SEGV (e.g. using a bad pointer) DOES produce a good backtrace.
Why can't I get a useful backtrace on ABRT signal on ARM?
[Question edited for clarity]
Here's a simple test program which demonstrates the problem:
#include <execinfo.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

// Signal hangler to catch seg fault:
void handler_segv(int sig) {
    // get void*'s for all entries on the stack
    void *array[10];
    size_t size;
    size = backtrace(array, 10);
    fprintf(stderr, "Error: Signal %d; %d frames found:\n", sig, size);
    // print out all the frames to stderr
    backtrace_symbols_fd(array, size, STDERR_FILENO);
    exit(1);
}

void crashme()
{
  // Deliberate Error: Abort (double free):
  char *test_ptr = malloc(1);
  free(test_ptr);
  free(test_ptr);
  // Deliberate Error #2: Seg fault:
  //char * p = NULL;
  //*p = 0;
}

void foo()
{
    fprintf(stdout, "---->About to crash...\n");
    crashme();
    fprintf(stdout, "---->Crashed (shouldn't get to here)...\n");
}

// Main entry point:
int main(int argc, char *argv[])
{
    fprintf(stdout, "Application start...\n");

    // Install signal handlers:
    fprintf(stdout, "-->Adding handler for SIGSEGV and SIGABRT\n");
    signal(SIGSEGV, handler_segv);
    signal(SIGABRT, handler_segv);

    fprintf(stdout, "-->OK. Causing Error...\n");
    foo();
    fprintf(stdout, "-->Test finished (shouldn't get to here!)\n");
    return 0;
}

This was compiled for x86 as follows:
gcc -o test test-backtrace-simple.c -g -rdynamic

And for ARM:
arm-none-linux-gnueabi-gcc -o test-arm test-backtrace-simple.c -g -rdynamic -O0 -mapcs-frame -funwind-tables -fasynchronous-unwind-tables

I've used various compiler options for ARM as described in other posts related to generating backtraces on ARM.
When run on the x86 desktop, it generates the expected output with plenty of debug, ending in:
Error: Signal 6; 10 frames found:
./test(handler_segv+0x19)[0x80487dd]
[0xb7745404]
[0xb7745428]
/lib/i386-linux-gnu/libc.so.6(gsignal+0x4f)[0xb75b0e0f]
/lib/i386-linux-gnu/libc.so.6(abort+0x175)[0xb75b4455]
/lib/i386-linux-gnu/libc.so.6(+0x6a43a)[0xb75ed43a]
/lib/i386-linux-gnu/libc.so.6(+0x74f82)[0xb75f7f82]
./test(crashme+0x2b)[0x8048855]
./test(foo+0x33)[0x804888a]
./test(main+0xae)[0x8048962]

(i.e. the back trace generated by my handler, with my function calls at the bottom).
However, when run on the ARM platform, I get:
Application start...
-->Adding handler for SIGSEGV and SIGABRT
-->OK. Causing Error...
---->About to crash...
*** Error in `/opt/bin/test-arm': double free or corruption (fasttop): 0x015b6008 ***
Error: Signal 6; 3 frames found:
/opt/bin/test-arm(handler_segv+0x24)[0x8868]
/lib/libc.so.6(__default_sa_restorer_v2+0x0)[0xb6e6c150]
/lib/libc.so.6(gsignal+0x34)[0xb6e6af48]

The backtrace() finds only 3 frames, and they are only the signal handler and something in libc (not useful)!
I found a mailing list post which said:

If you link with the debugging C library, -lc_g, you'll get debugging
  info back past abort().

This might be relevant, but -lc_g doesn't work on my compiler (ld: cannot find -lg_c).
The backtrace works fine on ARM if I generate a seg fault instead (e.g. change crashme() function to use "char *p = NULL; *p = 0;" instead of the double free.
Any ideas or suggestions for other ways to get a back trace?
[--EDIT--]
I tried some MALLOC_CHECK_ options as suggested in the comments, but the only effect was to change whether the abort was generated. Here is the output from three runs on the ARM:
 # MALLOC_CHECK_=0 /opt/bin/test-arm
Application start...
-->Adding handler for SIGSEGV and SIGABRT
-->OK. Causing Error...
---->About to crash...
---->Crashed (shouldn't get to here)...
-->Test finished (shouldn't get to here!)

# MALLOC_CHECK_=1 /opt/bin/test-arm
Application start...
-->Adding handler for SIGSEGV and SIGABRT
-->OK. Causing Error...
---->About to crash...
*** Error in `/opt/bin/test-arm': free(): invalid pointer: 0x015b2008 ***
---->Crashed (shouldn't get to here)...
-->Test finished (shouldn't get to here!)

# MALLOC_CHECK_=2 /opt/bin/test-arm
Application start...
-->Adding handler for SIGSEGV and SIGABRT
-->OK. Causing Error...
---->About to crash...
Error: Signal 6; 3 frames found:
/opt/bin/test-arm(handler_segv+0x24)[0x8868]
/lib/libc.so.6(__default_sa_restorer_v2+0x0)[0xb6e24150]
/lib/libc.so.6(gsignal+0x34)[0xb6e22f48]
#

MALLOC_CHECK_=0: No error message (double free is ignored!)
MALLOC_CHECK_=1: Error message, but program continues
MALLOC_CHECK_=2: Error message and ABRT signal; useless backtrace generated (this is the default behaviour!)
My cross compiler reports:
gcc version 4.6.1 (Sourcery CodeBench Lite 2011.09-70)
Target device has linux kernel version 3.8.8
Comment: Could you state what your asking for as briefly as possible? I'm a bit confused on your question about what it is you are really asking for help on.
Comment: Have you taken a look at: http://www.gnu.org/software/libc/manual/html_node/Backtraces.html
It gives an example of how backtracing can be used without the need for gdb. Let me know if this helps, thanks.
Comment: @Kozmik yes, already using pretty much that (see question and attached example code). However it doesn't work correctly for an ABRT caused by double free.
Comment: "How (on ARM platform) do I get a useful back trace for an abort signal caused by a double free?".     Using the 'backtrace()' function I only get three frames, one from the signal handler and two from libc, which are not useful since I am trying to find out where (in my code) the double free is occurring. Note the back trace DOES work properly when the code is run on my Ubuntu desktop so it seems to be an issue with the ARM compiler.
Comment: You can try using MALLOC_CHECK_ to '1' or '2' and see if this helps. You should see early aborts or error messages which will help you debug. This along with backtrace should help you out.

http://www.gnu.org/software/libc/manual/html_node/Heap-Consistency-Checking.html
Comment: @Arun: I tried MALLOC_CHECK_ as suggested, but this only changed whether any error message and/or abort signal was generated by the double-free; if the abort occurs, I still get a useless backtrace that shows only libc (not my code) - See edited question above for the output.
Comment: `fprintf(stderr, "Error: Signal ...` : you know that `prinf()` and friends are not signal-safe ?
Comment: I can relate that the same thing occurs on my Raspberry Pi. Compiling with the additional flags doesn't change anything.
Comment: Running on the exact same problem. Did you ever got it working? Did you have a chance to try @itaych 's suggestion?
Comment: I haven't tried @itaych 's solution, but I think it is probably correct, i.e. you also have to build libstdc++ and similar libraries with the appropriate flags set, and they probably weren't set in the toolchain we were using.
Answer: It appears you have done sufficient research to know that you need the switches -funwind-tables and -fasynchronous-unwind-tables in your compiler command line. In practice either one of them seems sufficient but clearly without them backtracing doesn't work at all. Now, the trouble with things like SIGABRT is that the backtrace must traverse stack frames that were generated by libc functions such as abort and gsignal, and fails because that lib is not built with either of those switches (in any distribution that I know of).
While it would be nice to petition the maintainers of Sourcery CodeBench to build their distribution with that option, the only immediate solution is to build libc yourself, with either or both of those flags set (in my experience just -funwind-tables is enough). If you also need a stack trace in case of catching an unhandled exception (via std::set_terminate) then you will also need to rebuild libstdc++.
At my workplace we needed backtraces for both cases (SIGABRT and unhandled exceptions), and since libstdc++ is part of the toolchain we rebuilt the toolchain ourselves. The tool crosstool-NG makes this relatively easy to do. In the configuration utility ./ct-ng menuconfig we entered section Target Options and edited Target CFLAGS (which sets the build variable TARGET_CFLAGS) to -funwind-tables. The resulting toolchain (more specifically, using the libc and libstdc++ from the resulting toolchain build) provides us with a full backtrace in nearly all cases.
I've found one case where we still don't get a full backtrace: if the crash occurred within a function that originally is written in assembly, such as memcpy (unfortunately this is not an uncommon occurrence). Perhaps some option needs to be passed to the assembler, but I didn't have the time to investigate this further.
Comment: @itaych I confirm your answer and I have to retract my certainty that I was linking correctly.  I am now able to get 13 frames.  Turns out linking correctly against a custom glibc is rather tricky and will only work correctly on programs with no other dependencies (not our case).  I have actually reverted to rebuilding the debian package (ie. apt-get source libc6-dev)  with the modified cflags in the debian/rules file.   Thanks very much for taking the time to report your findings!
Comment: Thanks, that's an interesting angle that I had not considered. Unfortunately I'm not in a position to test your solution at the moment.
Comment: So I managed to compile glibc 2.28 with -funwind-tables and -fasynchronous-unwind-tables and test the code above (on ubuntu linaro 16.04 armhf).  I had to use the following article to be sure I was linking against my custom-built glibc.

https://stackoverflow.com/questions/10763394/how-to-build-a-c-program-using-a-custom-version-of-glibc-and-static-linking

All of this to no avail: no stack trace with any MALLOC_DEBUG_ level [0 .. 2];.  Any thoughts on what I might have missed, or does stack tracing just not work on ARM?
Comment: @DaveMcMordie - running the code from the question, on an ARM, the stack trace has 7 entries and ends with "/lib/libc.so.6(__libc_start_main+0x114)[0xf70fecfc]" and looks complete, and the same as what I get on x86. Make sure you're linking with your custom glibc at runtime - if they're not placed in the standard location on your target system (/lib/ I guess) use LD_LIBRARY_PATH. Also make sure that your own project is also compiled with the flags -funwind-tables -fasynchronous-unwind-tables -g -rdynamic .
Comment: @itaych what version of glibc have you linked against and how was it built?  I am certain I am linking against the correct glibc.  The default one actually does better-- I get five frames ending at abort.  My configure for glibc: ../configure --prefix=/opt/lib  CFLAGS='-mapcs-frame -rdynamic -funwind-tables -fasynchronous-unwind-tables -fno-omit-frame-pointer -g -O3' libc_cv_ctors_header=yes
Comment: @DaveMcMordie The Glibc version is 2.26. We built it along with the GCC 5.1 toolchain using ct-ng as detailed in my answer above.
Comment: Very useful comment. Note that it must be possible in theory without rebuilding the toolchain though. I have the same issue as Jeremy explains (perfectly working backtrace decoding on x86, not on arm) But if I debug my arm application with gdbserver, it does succeed in fully decoding all the task frames. I guess gdb is more clever than the "backtrace_symbols" function that we compile with.
Answer: This is because unwinding through signal handlers is broken in glibc on ARM. I've dug into this a few years back and managed to create a working standalone fix. The hard part was digging through the undocumented bowels of exception handling in glibc, after that the fix was simple bordering on trivial.
I posted this to the glibc mailing list, as reply to an old thread about this problem, in the hope that a glibc dev would take my standalone fix as guide to fix it in glibc proper, but this never happened.
Recently I tested it again: it turns out that the problem still hasn't been fixed in glibc, and due to changes in glibc my fix no longer works. Update: I've fixed it!
Comment: I'm glad it wasn't just me going crazy! Thanks for posting your solution; next time I'm working on the ARM platform, I'll need to try it. Hopefully someone finds it useful!
Comment: @Matthijs I tried your library but unfortunately it didn't work. In the SIGABRT case it just prints 3 frames consisting of handler_segv, then `sa_restorer_v2.S` from your library, then some nonsense address from libc (`addr2line` maps it to `strfmon_l.c` which makes no sense). If I trigger the abort via gdb, that **does** print all frames, so there _is_ some way to get that info...
Comment: Backtrace from SIGSEGV does match that shown by gdb.
Comment: addr2line wants an address relative to the start of the executable, but the location of the executable in ram is randomized for security (ASLR) so feeding actual runtime addresses directly into addr2line is not going to work.
Comment: It's not really clear what you're doing, and this comment thread is probably not the best place for a detailed discussion. Feel free to open an issue on github with a sufficiently detailed explanation of the problem you're having.
Comment: @Matthijs, you wrote "Update: I've fixed it!" Does this mean it is now fixed in mainstream? Can you provide a link to the thread?
Comment: @eDeviser no I meant I fixed my code to support current glibc.


Hook_views_query_alter: adding condition with entity reference value

Question: I need to filter a table result based the current user.
I added this condition in my hook_views_query_alter
function my_module_views_query_alter(&$view, &$query) {
  global $user;
  if ($view->name == 'preventivi' && $view->current_display == 'page_3')
  {
    // $view->query->add_where(1, $user->uid, 33, '=');
    $view->query->add_where(1, "field_data_field_installatori_reference.field_installatori_reference_target_id", $user->uid, '!=');

    // dpm($view);
    //dpm($query);
  }
}

but I can't find the correct value of target_id to insert in the condition.
Any suggestion?
Comment: What version of drupal
Answer: This comment save my life!
https://api.drupal.org/comment/49458#comment-49458

Be careful to add the table, even if You added the field in the view
  UI :

I added
$view->query->add_table("field_data_field_installatori_reference");

and then I could access to my field:
$view->query->add_where(1, "field_data_field_installatori_reference.field_installatori_reference_target_id", $user->uid, '!=');


getOutputStream() has already been called for this response error

Question: Exception :
org.apache.jasper.JasperException: java.lang.IllegalStateException: getOutputStream() has already been called for this response
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:584)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:466)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:389)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:333)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)

root cause :
java.lang.IllegalStateException: getOutputStream() has already been called for this response
org.apache.catalina.connector.Response.getWriter(Response.java:627)
org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:215)
javax.servlet.ServletResponseWrapper.getWriter(ServletResponseWrapper.java:105)
org.apache.jasper.runtime.JspWriterImpl.initOut(JspWriterImpl.java:125)
org.apache.jasper.runtime.JspWriterImpl.flushBuffer(JspWriterImpl.java:118)
org.apache.jasper.runtime.PageContextImpl.release(PageContextImpl.java:190)
org.apache.jasper.runtime.JspFactoryImpl.internalReleasePageContext(JspFactoryImpl.java:123)
org.apache.jasper.runtime.JspFactoryImpl.releasePageContext(JspFactoryImpl.java:80)
org.apache.jsp.DownloadResume_jsp._jspService(DownloadResume_jsp.java:91)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:433)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:389)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:333)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)

Comment: And your code is ...?
Comment: please take a look at http://stackoverflow.com/questions/1776142/getoutputstream-has-already-been-called-for-this-response
Answer: I think I also got this error when I was working with jasper reports with Struts.
What happen was after creating the report I still returned a value(null) from the Action class(Servlet/Controller). The issue is, the report was set to the HTTPResponse and it is generated and I returned the response from the Action class again.
I just commented the return part from the Action class and then it worked.
Hope this will solve your issue.
Thanks.


Microsoft.Office.Interop.Excel is too slow

Question: I'm using the Excel Interop and I have an object list. It takes too long when I set the properties of the objects in the list in Excel cells in a loop:
        workSheet = (Excel.Worksheet)wbook.ActiveSheet;
        var row = 1;
        foreach (var shiftStop in shiftStops)
        {
            row++;
            workSheet.Cells[row, "A"] = shiftStop.MachineName;
            workSheet.Cells[row, "B"] = shiftStop.MachineType;
            workSheet.Cells[row, "C"] = shiftStop.UnitName;

        }

The shiftStops list has about 4000 objects. It takes 4-5 minutes to complete the return. Is there a way to make this process faster?
Comment: yes, dont use excel interop. use openxml nuget from nuget package manager ( i assume you are writing in c# in visual studio)
Comment: I used Spreadsheetlight but decided to try interop when I experienced problems with date-time formatting. Yes I am writing in C#.
Answer: The following functionality can usually be turned off while your code is executed:

Application.ScreenUpdating
Turn off screen updating. If Application.ScreenUpdating is set to False, Excel does not redraw the screen. While your code runs, the screen updates quickly, and it is usually not necessary for the user to see each update. Updating the screen once, after the code executes, improves performance.
Application.DisplayStatusBar
Turn off the status bar. If Application.DisplayStatusBar is set to False, Excel does not display the status bar. The status bar setting is separate from the screen updating setting so that you can still display the status of the current operation even while the screen is not updating. However, if you do not need to display the status of every operation, turning off the status bar while your code runs also improves performance.
Application.Calculation
Switch to manual calculation. If Application.Calculation is set to xlCalculationManual, Excel only calculates the workbook when the user explicitly initiates the calculation. In automatic calculation mode, Excel determines when to calculate. For example, every time a cell value that is related to a formula changes, Excel recalculates the formula. If you switch the calculation mode to manual, you can wait until all the cells associated with the formula are updated before recalculating the workbook. By only recalculating the workbook when necessary while your code runs, you can improve performance.
Application.EnableEvents
Turn off events. If Application.EnableEvents is set to False, Excel does not raise events. If there are add-ins listening for Excel events, those add-ins consume resources on the computer as they record the events. If it is not necessary for the add-in to record the events that occur while your code runs, turning off events improves performance.
ActiveSheet.DisplayPageBreaks
Turn off page breaks. If ActiveSheet.DisplayPageBreaks is set to False, Excel does not display page breaks. It is not necessary to recalculate page breaks while your code runs, and calculating the page breaks after the code executes improves performance.

Read more about that in the Excel performance: Tips for optimizing performance obstructions article.
Also I'd recommend releasing underlying COM objects. All Excel add-ins should systematically release their references to Excel objects when they are no longer needed. Failing to systematically release reference to Excel objects can prevent Microsoft Office Excel from shutting down properly.
Use System.Runtime.InteropServices.Marshal.ReleaseComObject to release an Excel object when you have finished using it. Then set a variable to Nothing in Visual Basic (null in C#) to release the reference to the object.
Comment: I've set all the properties you mentioned, but nothing has changed.
Answer: Each time you make a call to an object in an Office application it takes time - especially via the interop. This is particularly noticeable in the kind of looping operation you show.
Instead, consider creating an ARRAY of the values then writing the array to an Excel Range. Excel should write each element of the array to a cell. This is standard practise when writing large amounts of data to Excel in order to speed the process.
Assuming shiftStops is an array, the code could look like:
    workSheet = (Excel.Worksheet)wbook.ActiveSheet;
    var row = 1;
    Excel.Range rng = worksheet.Cells[row, "A"];
    rng = rng.Resize(1, shiftStops.Length);
    rng.Value = shiftStops;


Configuring mod_mem_cache to only cache certain content types and finding out what is cached

Question: I've installed Apache's mod_mem_cache on a server that serves multiple websites. I needed to install it in a hurry as I had a massive traffic spike and was firefighting. It has improved performance massively and all of my sites seem to be serving the correct content, all is well, but I have two questions:

How do I restrict the content types that are cached? Ideally I'd like to cache just css|js|jpg. I tried a <FilesMatch> within the mod_mem_cache.conf but that didn't work.
Is there any way to see which files are in the cache at any point?
Comment: It's been removed from Apache 2.4 so I wouldn't get too attached to it, or spend too much time learning how to configure it. Look into disk caching.
Comment: Or look in to Varnish.
Answer: The answer above is pretty good but...
Personally I would skip mod_mem_cache and install Varnish IMO a much better tool for the job and comes with some very useful debugging and metrics. Put varnish on port 80 and apache on 8080 or another used high level port.
https://www.varnish-cache.org
Answer:
http://www.askapache.com/htaccess/apache-speed-cache-control.html
Default path is /var/cache/apache/
(http://httpd.apache.org/docs/2.2/caching.html)
Comment: Hi japao, thanks for the comment but that wasn't exactly what I was looking for. /var/cache is the mod_disk_cache location and the askapache article seems to be talking about cache headers that are sent to the browser.


Multiple angular 2 apps and /api on same host with nginx

Question: I'm trying to achieve this goal with nginx configuration:
mydomain.com/api        should serve the php API
mydomain.com/login      should serve an angular 2 app
mydomain.com/dashboard  should serve another angular 2 app

The nginx.conf I post below works fine except for this (which is the problem i need help fixing):
When the user visits a route in angular like mydomain.com/dashboard/forms then the url is rewritten like this mydomain.com/dashboard/dist/forms
Here is the code tree:
├── mydomain.com
│   ├── app           // slim project
│   │   └── ...
│   ├── public
│   │   ├── dashboard // anuglar project
|   |   |   └── dist
│   │   └── login     // angular project
|   |       └── dist

And here is the server block I use:
server {

  listen 80;
  server_name mydomain.com;

  error_log /home/test/code/mydomain.com/error.log;
  access_log /home/test/code/mydomain.com/access.log;
  root /home/test/code/mydomain.com/public/;

  sendfile on;
  rewrite_log on;
  include  /etc/nginx/mime.types;

  gzip on;

  location ~ ^/(assets|bower_components|scripts|styles|views) {
    expires     31d;
    add_header  Cache-Control public;
  }

  ############################################################################
  #                             D A S H B O A R D
  ############################################################################

  location /dashboard/ {
    alias /home/test/code/mydomain.com/public/dashboard/dist/;
    try_files $uri $uri/ /index.html =404;
  }

  ############################################################################
  #                                L O G I N
  ############################################################################

  location /login/ {
    alias /home/test/code/mydomain.com/public/login/dist/;
    try_files $uri $uri/ /index.html =404;
  }

  ############################################################################
  #                                 A P I
  ############################################################################

  location ~ ^/api/(.*)$ {
    alias /home/test/code/mydomain.com/public;
    try_files $1 $1/ @php;
    index index.php;
  }

  location @php {
    fastcgi_split_path_info ^(/api)(/.*)$;
    fastcgi_pass localhost:9000;
    fastcgi_index index.php;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME /home/test/code/mydomain.com/public/index.php;
    fastcgi_param REQUEST_URI $fastcgi_path_info;
    fastcgi_read_timeout 900;
  }
}

What should I change so that the "/dist" doesn't get written in the url?
Answer: The configuration file is actually fine. The problem was building the angular app with --base-ref /dashboard/dist/ instead of plain /dashboard/


Parsing json into java objects in spring-mvc

Question: I'm familiar with how to return json from my @Controller methods using the @ResponseBody annotation.
Now I'm trying to read some json arguments into my controller, but haven't had luck so far.
Here's my controller's signature:
@RequestMapping(value = "/ajax/search/sync")
public ModelAndView sync(@RequestParam("json") @RequestBody SearchRequest json) {

But when I try to invoke this method, spring complains that:
Failed to convert value of type 'java.lang.String' to required type 'com.foo.SearchRequest'
Removing the @RequestBody annotation doesn't seem to make a difference.
Manually parsing the json works, so Jackson must be in the classpath:
// This works
@RequestMapping(value = "/ajax/search/sync")
public ModelAndView sync(@RequestParam("json") String json) {
    SearchRequest request;
    try {
        request = objectMapper.readValue(json, SearchRequest.class);
    } catch (IOException e) {
        throw new IllegalArgumentException("Couldn't parse json into a search request", e);
    }

Any ideas? Am I trying to do something that's not supported?
Answer: Your parameter should either be a @RequestParam, or a @RequestBody, not both.
@RequestBody is for use with POST and PUT requests, where the body of the request is what you want to parse. @RequestParam is for named parameters, either on the URL or as a multipart form submission.
So you need to decide which one you need. Do you really want to have your JSON as a request parameter? This isn't normally how AJAX works, it's normally sent as the request body.
Try removing the @RequestParam and see if that works. If not, and you really are posting the JSON as a request parameter, then Spring won't help you process that without additional plumbing (see Customizing WebDataBinder  initialization).
Comment: +1, You beat me to this. However, one more thing is to make sure that the client set the request `Content-Type` to `application/json`? Try that with `@RequestBody`, and remove `@RequestParam`, as skaffman suggested originally.
Comment: Just now I removed the `@RequestBody` annotation and sent the parameter as a GET parameter: `http://localhost:8080/my-app/ajax/search/sync?json={"foo"%3A"bar"}` but I'm getting the same error.
Comment: @oksayt: As I said, if you want to use `@RequestParam` for parsing JSON, you're going to have to customize your data binding, as described in the link.
Comment: Ah I see. Now I removed `@RequestParam`, added back `@RequestBody`, and now I'm sending the parameter as a form POST (so the POST body is the json string prefixed with `json=`). But I'm still getting the same error.
Comment: @oksayt: You don't need the `json=`, it's redundant. You just need the JSON text in the body. oh, and you'll also need `` for Jackson support (see http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-annotation-driven)
Comment: Thanks for the follow up answers. I verified that I have the `` directive. To generate a POST like you described, I used TamperData to set the POST data of my request to just the url-encoded json string. This time I didn't get the error and my controller method got invoked, but the parameter object was null.
Comment: Even though I didn't get it working yet, marking this as correct as it definitely points out the original problem correctly. Thanks!
Answer: if you are using jquery on the client side, this worked for me:
Java:
@RequestMapping(value = "/ajax/search/sync")
public ModelAndView sync(@RequestBody SearchRequest json) {

Jquery (you need to include Douglas Crockford's json2.js to have the JSON.stringify function):
$.ajax({
    type: "post",
    url: "sync", //your valid url
    contentType: "application/json", //this is required for spring 3 - ajax to work (at least for me)
    data: JSON.stringify(jsonobject), //json object or array of json objects
    success: function(result) {
        //do nothing
    },
    error: function(){
        alert('failure');
    }
});


jQuery ajax issue on IE9

Question: I am using this plugin to let users upload images trough ajax.
To create the uploader and trigger a post this jQuery function is used:
function createUploader() {
        var uploader = new qq.FileUploader({
             element: document.getElementById('file-uploader'),
             allowedExtensions: ['pdf'],
             multiple: false,
             action: '@Url.Action("AjaxUpload", "Upload")',
             onComplete: function(id, fileName, responseJSON){
               window.location.href = responseJSON.message;
            }
        });
    }

Well, in responseJSON.message I am returning the path where the file was uploaded (actually converted) and I am doing a trick with window.location.href to force the browser to show the user DOWNLOAD box for that file.
This works great on FF and Chrome but on IE it says:
Do you want to open or save AjaxUpload from localhost?
And if you press open, instead of getting the file from the specified location, you actually get a file containing responseJSON message.
Any jQuery guru who can give me a clue for this issue?
UPDATE: What I can confirm is that the issue is not with window.location.href = responseJSON.message; because even if I remove this line and put alert('something') the same problems occurs...so instead of parsing onComplete, IE try to open the JSON response...
Comment: What's the point of uploading and then downloading the same file? Or are you doing some transformation on it on the server?
Comment: yeah, it's a conversion I'm doing: from pdf to word
Comment: Does your route translate the ActionMethod pointer correctly ? If look through IE source, what does it show ?
Also, what's the return type on AjaxUpload method ?
Comment: Also.. I'm not familiar with that uploader but if there is a OnFailure event try using that and display the error.
Comment: I'm returning a `JsonResult`: `return new JsonResult { Data = new { message = outputFilePathResponse } };` so the response is for instance: `{"message":"/Tmp/0c40d994-6d3e-4fab-a43f-028468cb77e8.doc"}`
Answer: Try
return Json(new { Data = new { message = outputFilePathResponse } }, "text/html");

Reference:
IE tries to download JSON in ASP. NET MVC 3

jQuery ajax issue on IE9


What does the replace mean in sample function?

Question: I try to figure out how dose the sample function work when I try to random select 10 samples in each group from the data frame.
I have a data frame with 5 columns and 7000 rows. I split the dataset into around 200 groups. Then I want to random select 10 samples from each group. Some groups have less 10 samples. So when I try to sample them, I set replace=T. However, when I check the output, I found out some groups which were more then 10 sample in the group have repeat samples.
I am not sure how to fix this?
  mydata2<- split(mydf,mydf$Group)
  names(mydata2)<-paste0("mydata2",1:length(levels(mydf$Group)))
  mysample<-Map(function(x) x[sample((1:nrow(x)),size=10,replace=T),],
  mydata2)

Comment: Googling "sample with replacement" produces countless applicable explanations, since it is a common and critical concept in statistics. Premise: when you "sample" something, does what you pull out go back into the "population" allowing it to be picked again? (`replace=TRUE`) Or does pulling it out randomly mean it is no longer available for future samples? (`replace=FALSE`)
Answer: Let's first understand the concept of replace.
By default replace is FALSE in sample. So when you do
sample(1:5, 2)
#[1] 4 1

As replace is default set to FALSE you are not allowed to repeat elements.  It will randomly select 2 unique elements from 1:5.
But now when you do
sample(1:5, 6)

it results in an error stating

Error in sample.int(length(x), size, replace, prob) :
    cannot take a sample larger than the population when 'replace = FALSE'

which means you are trying to take 6 unique element from 1:5 which is not possible because you have only 5 unique elements in them. So when you set replace = TRUE you say that elements are allowed to be repeated.
sample(1:5, 6, replace = TRUE)
#[1] 3 3 5 3 1 1

Here, we see with replace = TRUE element 3 is repeated whereas in first example how many times you run it, it will never repeat elements.

So now, I hope the concept of replace is clear to you. Now you want to repeat rows only when there are less than 10 rows in the list. So you can add a condition accordingly,
lapply(mydata2, function(x) x[sample(1:nrow(x) ,size=10, replace=nrow(x) < 10), ])

This will be TRUE only when the number of rows in the dataframe is less than 10.
Using reproducible example from mtcars
table(mtcars$cyl)

# 4  6  8
#11  7 14

We see cyl = 6 has 7 rows which is less than 10.
mydata2 <- split(mtcars, mtcars$cyl)

lapply(mydata2, function(x) x[sample(1:nrow(x) ,size=10, replace=nrow(x) < 10), ])

#$`4`
#                mpg cyl  disp  hp drat    wt  qsec vs am gear carb
#Fiat X1-9      27.3   4  79.0  66 4.08 1.935 18.90  1  1    4    1
#Merc 230       22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2
#Toyota Corolla 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
#Honda Civic    30.4   4  75.7  52 4.93 1.615 18.52  1  1    4    2
#Toyota Corona  21.5   4 120.1  97 3.70 2.465 20.01  1  0    3    1
#Lotus Europa   30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2
#Volvo 142E     21.4   4 121.0 109 4.11 2.780 18.60  1  1    4    2
#Fiat 128       32.4   4  78.7  66 4.08 2.200 19.47  1  1    4    1
#Datsun 710     22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
#Merc 240D      24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2

#$`6`
#                mpg cyl  disp  hp drat    wt  qsec vs am gear carb
#Valiant        18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
#Valiant.1      18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
#Mazda RX4      21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
#Ferrari Dino   19.7   6 145.0 175 3.62 2.770 15.50  0  1    5    6
#Valiant.2      18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
#Mazda RX4.1    21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
#Mazda RX4 Wag  21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
#Merc 280C      17.8   6 167.6 123 3.92 3.440 18.90  1  0    4    4
#Hornet 4 Drive 21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
#Merc 280       19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4

#$`8`
#                     mpg cyl  disp  hp drat    wt  qsec vs am gear carb
#Dodge Challenger    15.5   8 318.0 150 2.76 3.520 16.87  0  0    3    2
#Camaro Z28          13.3   8 350.0 245 3.73 3.840 15.41  0  0    3    4
#Ford Pantera L      15.8   8 351.0 264 4.22 3.170 14.50  0  1    5    4
#Merc 450SLC         15.2   8 275.8 180 3.07 3.780 18.00  0  0    3    3
#AMC Javelin         15.2   8 304.0 150 3.15 3.435 17.30  0  0    3    2
#Pontiac Firebird    19.2   8 400.0 175 3.08 3.845 17.05  0  0    3    2
#Duster 360          14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
#Cadillac Fleetwood  10.4   8 472.0 205 2.93 5.250 17.98  0  0    3    4
#Hornet Sportabout   18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
#Lincoln Continental 10.4   8 460.0 215 3.00 5.424 17.82  0  0    3    4

In the output we can see the rows are repeated only for cyl = 6 and not for anybody else.
Answer: Perhaps only use replace=T when the group is smaller than the minimum size? This flag allows duplicates in the sample resulting in the behavior you're observing.
replace - If this is true a sample may contain an element several times while another element might not occur at all.
http://www.rexamples.com/14/Sample()


Why does the distribution of the probability change this way?

Question: Bob wants to test a possibly biased coin's probability $p$ of getting heads. His prior prediction is that $p \sim \mathrm{Uniform}(0, 1)$.
After getting all heads on 2 flips of the coin, why should the probability distribution change to $\mathrm{Beta}(3, 1)$? How is the Beta distribution relevant?
Comment: I don't think your question is clear. What are you asking? Does Bob wants to conduct Testing of Hypothesis for $H_0 : p \sim U(0,1) \text {vs } H_1 : p \sim Beta (3,1)$? (If he does, it might explain the question a little bit.) Please consider editing your question.
Comment: To me the question seem well formed. From what I understood, the question is equivalent to: you generate a random number $p$ between 0 and 1 uniformly. Now you flip the coin that generate heads with probability $p$ two times. What is the distribution of $p$ over the coins that result in $2$ heads? (if your initial $p$ was close to 0, only few times end with $HH$, so on the final distribution should be less represented)
Answer: check http://www.kris-nimark.net/pdf/BayesianIntroSlides.pdf
pages 28 and up
you're trying to evaluate $p$ in $[0,1]$. The Beta is a convenient prior distribution.
Answer: Fixing $p$, what is the probability of obtaining $HH$? $P(HH | p) = p^2$
What's the probability of getting p with the initial distribuition? $f(p) = 1$ (this is the probability density function)
What's the total probability of getting HH? $P(HH) = \int_0^1{P(HH|p)f(p)dp} = \int_0^1{p^2dp}=[1/3p^3]_0^1=1/3$
And then, using Bayes' theorem: $f(p|HH) = \frac{P(HH|p) * f(p)}{P(HH)}=\frac{p^2}{1/3}=3p^2$
You can check that this is exactly the probabily density function of $B(3,1)$.
More generally, if you obtain $h$ heads and $t$ tails starting with uniform distribuition, the probability distribuition become $B(h,t)$.


How to use solfège for chords?

Question: I'm just wondering how one would use solfège for chords/harmony. For example, to sing C major, does one say "do mi so"? If so, wouldn't that in practice mean that one would have to say a lot of words when harmonizing with another person? It's like arpeggiating the chord.
Instead of arpeggiating, is there a block chord version where the entire chord is contained in one syllable? Or when we harmonize with solfège, do all notes of the chord need to be individually pronounced?
Comment: Solfege was designed for individual notes. Therefore it doesn't encompass multiple notes with other names. Simply say each name. When you get good at it, it's just like ordinary speech - and just as quick. Bear in mind movable do, but also fixed do - where someting like Bflat; is called 'si bemole - 3 syllables, making the make-up of chords quite a mouthful!
Comment: It was designed to be sung. Chances are you can only sing one note at a time. Arpeggiating the chord you are singing is really the only choice.
Comment: @Tim ok I didn't know it was only for individual notes, if you put your comment below it may be the answer.
Answer: Keep in mind that, in several languages, solfège syllables are just the names of the notes themselves. In other words, "do mi sol" literally translates to "C E G." As such, solfège syllables only map to individual pitches.
The only system that I can think of where "the entire chord is contained" is with a system that we already know well: by saying something like a major triad built on "mi." But even then, it's not always clear if "mi" means E or E♭. (I certainly hope it isn't E♯...)
But as for monosyllabic solutions, there aren't any that I'm familiar with.
Comment: There is the (I think) German or Dutch method of suffixes "es" or "s" for flat and "is" for sharp, so you get C, Cis=Des, D, Dis=Es, E=Fes, Eis=F, Fis=Ges, G, Gis=As, A, Ais=Bes, B=Ces, Bis=C. So you can sing all the notes in one syllable, but they're still notes, not chords.
Comment: @YourUncleBob - English B flat is German B, and English B is German H, so it's Ais=B and H=Ces.
Comment: @Dekkadeci The way I wrote it is apparently Dutch only: https://nl.m.wikipedia.org/wiki/Bes_(muziek)
Answer: That's the right way and probably the best way to learn chords. But you need to use movable-do solfege. There's this big reason behind it. Most of the songs aren't written with absolute scales in mind due to which we always use terms like 1,4,5 chords. These are nothing but do fa sol chords. These don't change with pitch as you're using movable-do. If you learn chords as solfege based chords, you'll know how the chord relates to the actual song again converted into solfege. You could have converted them into absolute notes but then again you would go about doing calculations of 1,4,5,6 etc. I use it and it's very powerful. I just sit and listen to the whole song. I don't even touch my instrument. I would have decoded all the chords in terms of do Major or re minor etc. And the song will be decoded in terms of do re mi.. The moment I take the instrument I know the chords to play given the pitch as i know what the solfege corresponds to in each pitch.
Answer: The purpose of solfege is that you practice to sing and mind the chords as long until you can imagine - or hear with your "inner ear" the entire chord by singing only the root tone or the bass note in case of inversions. This needs a lot of practice, but it is a big help in combination with the RNA.

How to use solfège for chords?


Oxyplot: AreaSeries ItemSource with custom DataPoints

Question: I am using the AreaSeries in Oxyplot to graph a range between two points and would like the Tracker to display both of them when hovered. I achieved making the Tracker display custom properties with other series by creating a custom class for the DataPoints and changing the TrackerFormat accordingly. Here is an example:
    public class CommentPoint : IScatterPointProvider
    {
        public CommentPoint(double x, double y, string text)
        {
            X = x; Y = y; Text = text;
        }
        public double X, Y;
        public string Text { get; set; }
        public ScatterPoint GetScatterPoint()
        {
            return new ScatterPoint(X, Y);
        }
    }

And the TrackerFormat:
Series.TrackerFormatString = "{2}\n{Text}";

However, this only works when adding an array of the new points as the ItemSource of the series. With Line/ScatterSeries it's easy, since they require just a list of points. But an AreaSeries requres 2 points to be graphed.
I tried adding a 2d array of these custom points as the ItemSource:
    public class AreaPoint : IDataPointProvider
    {
        public AreaPoint(double x, double y, double y2)
        {
            X = x; Y1 = y; Y2 = y2;
        }

        public double X { get; set; }
        public double Y1 { get; set; }
        public double Y2 { get; set; }
        public DataPoint GetDataPoint()
        {
            return new DataPoint(X, Y1);
        }
    }

So basically:
AreaPoint[,] points = new AreaPoint[2,amount.Count]
AreaPoint[0,i] = new AreaPoint(x,y,y2);
....
Series.ItemSource = points;

That doesn't work and I recieved an error "Is not a one-dimentional array".
Next I tried adding the points directly via the GetDataPoint method:
Series.Points.Add(new AreaPoint(x,y,y2).GetDataPoint());
Series.Points2.Add(new AreaPoint(x2,y2,y3).GetDataPoint());
Series.TrackerFormatString = "{2}\n{4}\n{Y2}";

This works in that the AreaSeries is being plotted correctly, but the Tracker won't display my custom properties.
So I suppose my question is, how can I add a custom ItemSource to an AreaSeries?
Answer: You can just add X2, Y2 fields to your custom point class and set DataField properties in your AreaSeries.
public class AreaPoint : IDataPointProvider
{
    public AreaPoint(double x, double y, double x2, double y2, string customValue)
    {
        X = x;
        Y = y;
        X2 = x2;
        Y2 = y2;
        CustomValue = customValue;
    }

    public double X { get; set; }
    public double Y { get; set; }
    public double X2 { get; set; }
    public double Y2 { get; set; }
    public string CustomValue { get; set; }
}

...
series = new AreaSeries();
series.DataFieldX = "X";
series.DataFieldY = "Y";
series.DataFieldX2 = "X2";
series.DataFieldY2 = "Y2";
series.TrackerFormatString = "{0}\n{1}: {2}\n{3}: {4}" +
    "\nMy custom value: {CustomValue}"


jQuery - select all elements except those which are in element2

Question: I would like to select all elements, for example a tags
$('a').blabla();

But I don't want to have selected those that are deeply inside of div with id theChosenOne so #theChosenOne>a wont work because a tags can be deeply inside of this div surrounded by tons of other tags...
Is there some possibility how to solve this? The way I would appreciate the most is using :not
Comment: Could you post some sample markup?
Answer: My first thoughts are:
$('a').not('#theChosenOne a');

Or
$('a').filter(
    function(){
        if (!$(this).closest('#theChosenOne')){
            return $(this);
        }
    });


How would I add markup inside of page title input?

Question: If I wanted to achieve the below, can I insert HTML markup inside of the page title on the node?
For example,

Dummy page title content

Answer: Install HTML Title. It will solve your issue.

Drupal node titles are restrictive and do not support italicized text
  or superscript text (e.g., Book titles, trademark symbols). The HTML
  Title module allows a limited set of HTML markup (em, sub, sup, b, i,
  strong, cite, code, bdi, wbr) to be used in node titles.

Also take a look at Stack Overflow question HTML\rich text in Drupal's node title?.


I get "unhandled exception of type 'System.NullReferenceException' occurred" how to solve it?

Question: I tried the following code and I get this error.

An unhandled exception of type 'System.NullReferenceException' occurred in Linkedlist.exe Additional information: Object reference not set to an instance of an object.

I think the problem is in insertlast() and when I checked the solutions to similar problems, they talk about instantiating the new node. I my method i.e. Node *q = new Node; wrong?
struct Node {
    int data;
    Node* next;
};
int is_list_empty(struct Node*head){
    int count=0;
    Node* p = head;
    while (p!= NULL)
{
  ++count;
  p = p->next;
  cout<<"go";
}
    return count;
}

void insertlast(struct Node *head,int value)
{
    Node *q = new Node;
    q->data=value;
    q->next=NULL;
    Node *p=head;
    while(p!=NULL)
    {
        p=p->next;
    }
    q=p->next;
}

void display(struct Node *head){
    Node*p = head;
    while(p!=NULL){
        cout <
data<< "  ";
        p=p->next;
    }
}

int main(){
    //Node *head = NULL;
    Node *head;
    Node *x ;
    x = (Node*)malloc(sizeof(Node));
    x->data=112;
    x->next = head;
    head = x;
    display(head);
    //works fine upto here and 112 is displayed
    insertlast(head,34);
    insertlast(head,32);
    insertlast(head,44);
    display(head);
    cout<< is_list_empty(head);
    system("Pause");
    return 0;
}

Answer: You should make head null . Next there is mistake in assigning q back to p (It should be p->next=q ) and your while loop should check only up to p->next!=NULL. See the changes i have made.
struct Node {
    int data;
    Node* next;
};
int is_list_empty(struct Node*head){
    int count=0;
    Node* p = head;
    while (p!= NULL)
{
  ++count;
  p = p->next;
  cout<<"go";
}
    return count;
}

void insertlast(struct Node *head,int value)
{
    Node *q = new Node;
    q->data=value;
    q->next=NULL;
    Node *p=head;
    while(p->next!=NULL)
    {
        p=p->next;
    }
   p->next=q;
}

void display(struct Node *head){
    Node*p = head;
    while(p!=NULL){
        cout <
data<< "  ";
        p=p->next;
    }
}

int main(){
    //Node *head = NULL;
    Node *head=NULL;
    Node *x ;
    x = (Node*)malloc(sizeof(Node));
    x->data=112;
    x->next = head;
    head = x;
    display(head);
    //works fine upto here and 112 is displayed
    insertlast(head,34);
    insertlast(head,32);
    insertlast(head,44);
    display(head);
    cout<< is_list_empty(head);
    system("Pause");
    return 0;
}

Comment: In the above problem after the end of while loop **node p** points to the last element and **p->next** points to null. Hence you should assign **node q** (which contains current value to be added) to  **p->next** . If u do **q=p->next** u will end up assigning null to **node q** and your original list **head** remains unchanged.
Comment: It works now thanks. I would like to know the difference between p->next=q and q=p->next.


how to accept only specific "subnets" using iptables?

Question: I have to limit access to 8080 port and allow only some IPs and specific subnets.  Is it possible, can you please help?
I enabled filtering for IPs but I couldn't find how to accept subnets?
sudo /sbin/iptables -N CHN_PNTS
sudo /sbin/iptables -A CHN_PNTS --src 184.108.40.206  -j ACCEPT
sudo /sbin/iptables -A CHN_PNTS --src 22.214.171.124  -j ACCEPT
sudo /sbin/iptables -A CHN_PNTS --src 184.108.40.206   -j ACCEPT
sudo /sbin/iptables -A CHN_PNTS -j DROP
sudo /sbin/iptables -I INPUT -m tcp -p tcp --dport 8080 -j CHN_PNTS

subnets that i want to accept;
188.8.131.52/24
184.108.40.206/23

Thanks
Erdal
Comment: `--src 188.8.131.52/24`
Answer: You just use CIDR notation like in your question
sudo /sbin/iptables -A CHN_PNTS --src 220.127.116.11/24   -j ACCEPT
sudo /sbin/iptables -A CHN_PNTS --src 18.104.22.168/23   -j ACCEPT

Remember to place them before your
sudo /sbin/iptables -A CHN_PNTS -j DROP

so that they are actioned correctly.
Answer: Subnet specifications are acceptable in the source.
sudo /sbin/iptables -A CHN_PNTS --src 220.127.116.11/24 -j ACCEPT
sudo /sbin/iptables -A CHN_PNTS --src 220.127.116.11/23 -j ACCEPT

how to accept only specific “subnets” using iptables?


Add ctools processing for content loaded via ajax

Question: I have a search result page where all the searched results are loaded using ajax call. For each result, there is a button which should open a form in the modal.
The code snippet which is loading a button on the search result is as follows:
$build[$entity->id]['footer']['footer-bottom-section']['view-modal-form'] = array(
        '#type' => 'markup',
        '#markup' => l(' Get Best Price', 'request/add/'.$space_id.'/'.$entity->id, array('html'=>TRUE,'attributes'=> array('class'=>array('btn','btn-orange', 'pull-right', 'ctools-use-modal')))),
    );

The button is loaded properly on each search result, and it has all the classes provided. But it does not have ctools-use-modal-processed class.
I know the reason since the page is already loaded and results are added to the page through ajax after load finishes, ctools is not finding ctools-use-modal class to process.
I would like to know, how can I trigger ctools to process my ajax loaded search results so that it can add modal form for each searched result?
EDIT: Following is the js function which is calls a custom menu callback function, to load results:
function fetchNext(url, $parent) {
    $parent.append('
Loading
');
    $.get( url, function( data ) {
        $parent.append( data );
        $('.load-next').bind('inview', function (event, visible) {
            if (visible && !($(this).hasClass('disabled'))) {
                var url = $(this).attr('href');
                fetchNext(url, $(this).parent());
                $(this).remove();
              }
            });
        $('.load-next').click(function (event) {
            event.preventDefault();
            var url = $(this).attr('href');
            fetchNext(url, $(this).parent());
            $(this).remove();
        });
        processAfterLoad();
    }).fail(function() {
        $('#space-loading').text('Error in loading spaces. Please refresh page');
    });
}

This is line which calls above function:
$('.load-next').bind('inview', function (event, visible) {
            if (visible && !($(this).hasClass('disabled'))) {
                var url = $(this).attr('href');
                fetchNext(url, $(this).parent());
                $(this).remove();
              }
            });

Following is the kind of URL which will be called:
/lazyspaces/<Google places api locality>?<lat, lng, geolocation, sort, page>

for e.g.:
/lazyspaces/Thane-West--Thane--Maharashtra--India?lat=19.2444738&lng=72.9814877&geolocation=Thane%20West%2C%20Thane%2C%20Maharashtra%2C%20India&sort=distance&page=2&plain=1&lastdistance=8.80

Menu callback:
$items['lazyspaces'] = array(
        'title' => 'Find a Space',
        'page callback' => 'discover_lazy_spaces',
        'access callback' => 'entity_access',
        'access arguments' => array('view', 'space', 1),
        'file' => 'includes/search.utils.inc',
);

Here discover_lazy_spaces function, extracts get parameters and send it to a query to fetch results from database and then builds result list.
Comment: How are you loading the search results with ajax? Through a custom script, a module, or some API in core? And what version of Drupal?
Comment: I am using drupal 7. I have created a drupal module which has ajax calls specified in module's js file.
Comment: Please edit the original post and show the JS you are using to embed the new content into the page. I can give you an answer after I see that.
Comment: I have updated my question with codebase. Please review and let me know the solution.
Answer: You need to call Drupal.attachBehaviors() after inserting the new content into the page.
Change this:
$parent.append( data );

To this:
$parent.append( data );
Drupal.attachBehaviors($parent);


AJAX Successful redirects but gives [object : object]

Question: I have used my node.js method getDetails and provide one static id. But data  results as object. When I check my node.js method from postman it provide JSON string but AJAX successful data is provide object dont no why??

$.post("/salons/getDetails",
{
    objectId: "561cd801a4b2b6ec1dafba23"
},
function(data)
{
    alert(1);
    alert(data);
});

});

My backend method is

router.post('/getDetails',function(req,res){
    data=req.body;
    var objectId=data.objectId;
    salon.find({ "_id": objectId }).exec(function(err, data) {
    if (err) throw err;
    res.json(data);
  });
Answer: Alert only outputs strings, therefore you either use console.log allowing you to see its contents in the console, or use JSON.stringify(data) to convert your JSON object into a string.
Comment: Thanx its working for me
Comment: Sorry to ask but is something wrong with your `E` on the keyboard? First "objact" and now this.
Comment: no its not but objact is typed in hurry by mistakes as its my first question on stack overflow and my work is not getting done so in hurry.
Answer: You're returning a JSON object. Try putting a console.log(data); instead of alert(data);. Or if you want to keep the alert, try alert(JSON.stringify(data)); and see what it returns.


Locally compact $T_2$ but not $T_4$ spaces

Question: Does there exist an example of locally compact Hausdorff (each two points can be separated by disjoint neighborhoods) but not normal Hausdorff (each two closed subsets can be separated by disjoint neighborhoods) topological space?
Even if there is, does it carry the Tietz extension property (any continuous function to $\mathbb{R}$ on closed subset can be extended to the whole space i.e. the sheaf of continuous $\mathbb{R}$-functions is soft)?
Answer: There are quite a few of them: an easy way to find them: use $\pi$-base which incorporates the spaces from "Counterexamples in Topology" by Steen and Seebach.
The deleted Tychonoff plank $(\omega_1 + 1) \times (\omega + 1) \setminus \{\omega_1, \omega)\}$ is the classical example.
$\omega_1 \times [0,1]^{[0,1]}$ is another relatively easy example, if you know the relevant theory: It's locally compact and $T_2$ as a product of two such spaces. It's not normal, because it contains $P= \omega_1 \times (\omega_1+1)$ as a closed subspace (by Tikhonoff's embedding theorem, as the weight of $\omega_1 + 1$ is at most $\mathfrak{c}$, it can be embedded into $[0,1]^{[0,1]}$ and compact subsets of $[0,1]^{[0,1]}$ are closed) and $P$ is not normal (classical; $X \times \beta(X)$ is normal iff $X$ is paracompact and $\beta\omega_1 = \omega_1 +1$, or use a pushing down lemma argument).
But a Mrówka $\Psi$-space based on a MAD family is also an example. See this blog for proofs and definitions. This is not normal as it's pseudocompact and $T_3$ but not countably compact. Or use Jones' lemma.
I also like the rational sequence topology, it's not normal by a Jones' lemma argument. And it's the simplest to describe (no ordinals or MAD families).
The Tietze extension property for $X$ is equivalent to $X$ being normal. So these spaces don't obey it.
Comment: You could also quote the result that a space is hereditarily normal iff every open subspace is normal. So a locally compact normal space  X that is not hereditarily normal has a non-normal open subspace Y. And  Y is locally compact (because it is open in X, and X is both normal and locally compact).
Comment: @DanielWainfleet I don't follow. You mean that any compact $T_2$ but not $T_5$ space contains an example as asked (which is true)?
Comment: If $X$ is normal and locally compact  but not $T_5$ then an open non-normal subspace $ Y$ is an example of a locally compact non-normal  Tychonoff ( and a fortiori) Hausdorff space.
Comment: @DanielWainfleet and all examples are of this form. It doesn't give us "new" or "concrete" examples.


How to use Gulp and Babelify (Babel + Browserify) to compile singletons and classes

Question: I'm trying to develop an isomorphic game in NodeJS and the web browser. I decided to transfer my codebase to ES6 and ES7 and compile it with BabelJS.
I'm having difficulty compiling the code with Gulp, Babelify, and Gulp-develop-server.
First Issue
First off, the server seems to cache files when I use Gulp watch and call
Application structure
The files in node_modules are there because then I don't need relative import paths. import Event from 'event/event'; instead of import Event from '../event';
src
|
| -- client
|    |
|    | -- main.js (Entrypoint, instantiate game.js class)
|    | -- ...
|
| -- server
|    |
|    | -- main.js (Entrypoint, instantiate game.js class)
|    | -- ...
|
| -- node_modules
|    |
|    | -- event
|    |    |
|    |    | -- event.js (See singleton below)
|    |    | -- package.json ({ "browserify": { "transform": [ [ "babelify", { "stage": "0" } ] ] } })
|    | -- game
|    |    |
|    |    | -- game.js (Class, imports event.js)
|    |    | -- package.json ({ "browserify": { "transform": [ [ "babelify", { "stage": "0" } ] ] } })
|    | -- ...

Second Issue
When I import my singleton, it is missing its functions. Previously, I tried creating a class, and exporting an instance of it, but that didn't work.
Singleton
export default
{
    events: new Map(),
    dispatch: function ( name, value )
    {
        if ( !this.events.has( name ) )
        {
            this.events.set( name, [] );
        }

        for ( var func of this.events.get( name ) )
        {
            func( value );
        }
    },
    listen: function ( name, func )
    {
        if ( !this.evens.has( name ) )
        {
            this.events.set( name, [ func ] );
        }

        this.events.get( name ).push( func );
    }
};

Class (.listen() doesn't work)
import Event from 'event/event';

export default class Game
{
    constructor()
    {
        // listen is undefined
        Event.listen( 'play', function () {} );
    }
}

Gulp Cache
var gulp = require( 'gulp' ),
    babel = require( 'gulp-babel' ),
    babelify = require( 'babelify' ),
    server = require( 'gulp-develop-server' ),
    source = require( 'vinyl-source-stream' ),
    changed = require( 'gulp-changed' ),
    sourcemaps = require( 'gulp-sourcemaps' ),
    browserify = require( 'browserify' ),
    autoprefixer = require( 'gulp-autoprefixer' ),
    watchify = require( 'watchify' );

var paths = {
    client: 'src/client/',
    common: 'src/node_modules/',
    server: 'src/server/',
    html: 'src/client/view/',
    css: 'src/client/view/css/',
    assets: 'src/client/view/assets/',
    node_modules: 'node_modules',
    build_client: 'build/client',
    build_server: 'build'
};

var files = {
    client: paths.build_client + '/client.js',
    server: paths.build_server + '/server_src.js'
}

gulp.task( 'watch', [ 'build', 'server:start' ], function ()
{
    var originalKeys = Object.keys( require.cache );
    gulp.watch( [ paths.common + '**/*.js', paths.client + '**/*.js' ], [ 'client:js' ] );
    gulp.watch( [ paths.common + '**/*.js', paths.server + '**/*.js' ], [ 'server:restart' ] );
} );

gulp.task( 'watch_client:js', function ()
{
    var bundle = browserify(
    {
        debug: true,
        entries: './src/client/main.js',
        cache:
        {},
        packageCache:
        {}
    } );

    bundle = watchify( bundle );
    bundle.transform( babelify.configure(
    {
        sourceMaps: true,
        stage: 0
    } ) );
    bundle.on( 'update', function ()
    {
        executeBundle( bundle );
    } );
    executeBundle( bundle );
} );

function executeBundle( bundle )
{
    var start = Date.now();
    bundle
        .bundle()
        .on( "error", function ( err )
        {
            console.log( "Error : " + err.message );
        } )
        .pipe( source( 'client.js' ) )
        .pipe( gulp.dest( paths.build_client ) )
        .on( 'time', function ( time )
        {
            console.log( 'Bundle finished in ' + time + '.' );
        } );
}

gulp.task( 'build', [ 'client:js', 'client:node_modules', 'server:js' ] );

gulp.task( 'client:js', function ()
{
    browserify(
        {
            debug: true,
            cache:
            {},
            packageCache:
            {}
        } )
        .transform( babelify.configure(
        {
            sourceMaps: true,
            stage: 0
        } ) )
        .require( "./src/client/main.js",
        {
            entry: true
        } )
        .bundle()
        .pipe( source( 'client.js' ) )
        .pipe( gulp.dest( paths.build_client ) );
} );

gulp.task( 'client:node_modules', function ()
{
    return gulp.src( [ paths.node_modules + '/socket.io/node_modules/socket.io-client/socket.io.js' ] )
        .pipe( changed( paths.build_client ) )
        .pipe( gulp.dest( paths.build_client ) );
} );

gulp.task( 'server:js', function ()
{
    browserify(
        {
            debug: true
        } )
        .transform( babelify.configure(
        {
            sourceMaps: true,
            stage: 0
        } ) )
        .require( "./src/server/main.js",
        {
            entry: true
        } )
        .bundle()
        .pipe( source( 'server_src.js' ) )
        .pipe( gulp.dest( './build' ) );

    gulp.src( './src/server/server.js' )
        .pipe( gulp.dest( paths.build_server ) );
} );

gulp.task( 'server:start', [ 'server:js' ], function ()
{
    server.kill();
    server.listen(
    {
        path: paths.build_server + '/server.js'
    } );
} );

gulp.task( 'server:restart', [ 'server:js' ], function ()
{
    server.restart();
} );

Answer: I am using RollupJS (http://rollupjs.org) now because it greatly simplifies the process of module loading and running plugins like Babel.
Stop downvoting and thinking this post is too broad. If you've actually tried to do what I've done, you've realized is quite a specific issue.


Are there CPUs with cache line widths others than powers of 2?

Question: Does anyone know of CPUs where the cache line widths are anything other than powers of 2?
Comment: is there any data in a computer's memory of a size other than a power of 2 ?
Comment: Probably not. Anything other than a power of two would severely complicate the hardware.
Comment: @Mystical: can you post a proper reply so I can mark it the correct answer?
Answer: This goes back to how computers store information and handle instructions in general, through binary(base 2) numbers.  This logically is the most simple that you can break anything down to either something is or it is not; 1 or 0.
Comment: Yes, but I'm asking about cache line widths, not why binary is used in computers =-)
Comment: My bad went off on a tangent kinda, but I believe its basically for the same reason. Cache's are components in the datapath of a computer these components handle different sized instructions the instructions themselves are always powers of two.


Como transformar um set em lista Python 3.x

Question: Estou fazendo um exercício que pede para, dado dois sets, printar em ordem crescente (linha por linha) a diferença simétrica entre eles, meu código:
n = set(input().split())
m = set(input().split())

m_diff = m.difference(n)
n_diff = n.difference(m)
result = [m_diff, n_diff]

if __name__ == '__main__':
    for i in range(0, len(result)):
        print(result[i])

input:
2 4 5 9
2 4 11 12

meu output:
{'11', '12'}
{'9', '5'}

output esperado:
5
9
11
12

Como eu faço pra tirar os elementos de dentro dos sets e fazer todos eles virarem elementos de apenas uma mesma lista?
Comment: Não está iterando o `set`? acho que é só usar `for i in m_diff` ou `for i in n_diff` (dependendo de qual recebeu o update)
Comment: Iterar usando o índice não é o jeito mais idiomático de se iterar em `Python`. O jeito proposto pelo @GuilhermeNascimento, entretanto, com `for var in iterable` é o mais idiomático e permite iterar de diversas maneiras
Comment: Não ocorreu isto porque você colocou assim `result = [m_diff, n_diff]`? Porque ai nem foi a questão de transformar em set, foi simplesmente que pegou os "diffs" e colocou um no index 0 e outro no index 1, isso tudo já sabendo que o `.difference` retorna todos resultados que diferem em um novo `set`, pois bem, se quer juntar tudo o correto me parece que seria o `.union` (acho não tenho certeza) ou o `.update` ou o "pipe" (`set1|set2`)
Comment: o problema que o difference() retorna um set, eu pus numa lista pra poder dar .sort() e printar item por item em order crescente, igual aparece no output esperado
Comment: Eu disse no começo, o problema não parece no resto do código e nem no difference, parece no `result = [m_diff, n_diff]`, vou usou um `[...,...]` quando talvez deveria ter usado union ou update, depende do que deseja
Comment: Você tinha razão, com o update retorna o set  completo {'4', '12', '9', '11'}, agora como faço para dar print em cada elemento do set?
Comment: Pega o set que foi atualizado, afinal essa é diferença do .update() pro .union(), não é? Não me lembro ao certo. Se usou o update um dos seus sets foi atualizado, então um deles tem todos valores
Comment: sim, o update() transformou tudo num set apenas, com todos os elementos que me interessaram, mas nao se pode iterar e print como numa lista, nem usar o sort(). Ainda me falta saber como retornar o output esperado
Comment: Obrigado pela ajuda, o método de vocês não precisou transformar em list, eu não sabia que se podia iterar ali. De qualquer forma, a jus do título vou responder à pergunta convertendo o set em list primeiro.
Answer: Você pode usar o método da classe set de diferença simétrica:
result = m.symmetric_difference(n)

Ou o operador equivalente ^:
result = m ^ n

Por exemplo:
a = '2 4 5 9'
b = '2 4 11 12'

n = set(int(i) for i in a.split())
m = set(int(i) for i in b.split())

result = m ^ n

for i in sorted(result):
    print(i)

Saída:
5
9
11
12

Veja funcionando no Repl.it
Comment: a saída tem que ser em ordem crescente: ```for i in sorted(list(result), key=int):
print(i)```
Comment: @Pirategull: Feito!
Answer: n2 = set(input().split())
m2 = set(input().split())

m_diff = m2.difference(n2)
n_diff = n2.difference(m2)

# poderia resolver o exercício iterando diretamente no set e usando print()
m_diff.update(n_diff)

# esse método converte set em list:
def convert(set):
    return list(set)

#set convertido para lista
m_lis = convert(m_diff)

if __name__ == '__main__':
    for elements in m_lis:
        print(elements)