Flip a coin until getting HTH

Question: I am tossing a coin with probability $p$ of heads (H) and $q=1-p$ of tails (T). What is the expected number of tosses until I get HTH?
The book that I am reading suggests the following solution: consider the event that HTH does not occur in $n$ tosses, and in addition the next three tosses give HTH. If we look at the combinations of the $(n-1)$-th and $n$-th tosses, followed by HTH, we can deduce that:
\begin{equation}
\mathbb{P}(Y>n)p^2q=\mathbb{P}(Y=n+1)pq+\mathbb{P}(Y=n+3),\quad n\geq 2
\end{equation}
As suggested, it is possible to sum this equation over $n$ in order to obtain that $\mathbb{E}(Y)=(pq+1)/(p^2q)$. However, I tried to do the sum and manipulate it in different ways but I could not obtain anything that leads me to this conclusion.
Comment: I suppose that $m$ is supposed to be $n$?
Comment: yes, thanks, I will edit it.
Comment: That equation and $E(Y)=(pq+1)/p^2 q$ are not compatible: summation over $n$ gives $E(Y)p^2 q = pq + 1 - P(Y=3) - P(Y=4)$ which would imply $E(Y)>(pq+1)/p^2 q$. There must be some error in the formulation of the equation. Doing some reverse engineering, the solution would go through if that equation were to hold for $n \geq 0$; then summation over $n$ would give the given result. But I cannot really follow the derivation of the equation anyway, so I don't see how to get this.
Answer: The method I like for this kind of problem is to set up a Markov chain. Here the state space is the last three coin flips that we saw. We set the initial distribution to be the usual distribution on 3 biased coin flips (a sequence containing $k$ heads has probability $p^k q^{3-k}$). Then we use a standard "renewal argument":
$$E[\tau_{HTH} \mid X_0=i] = \sum_{j \in S} (1+E[\tau_{HTH} \mid X_0=j]) p_{ij} = 1 + \sum_{j \in S} E[\tau_{HTH} \mid X_0=j] p_{ij}$$
This is just saying that if  we start at $i$, we go to a new state $j$, that takes one flip, and then we add in the average number of flips it's going to take us to get from $j$, weighted by how likely it was to go to $j$. Finally we adjoin the boundary condition $E[\tau_{HTH} \mid X_0=HTH]=0$. So one of our seven other equations will be
$$E[\tau_{HTH} \mid X_0=HHH]=1+p E[\tau_{HTH} \mid X_0=HHH]+ q E[\tau_{HTH} \mid X_0=HHT].$$
Solving this whole system of linear equations, left-multiplying the resulting column vector by the row vector of the initial distribution, and then adding $3$ (to take into account the initial three flips) gives the desired result.
This approach is quite flexible; for example it can be used to understand the surprising differences between "HHT" and "HTT".
Comment: It puzzles me that the MC states that you propose do not model the initial states of the system. I actually made the calculations as you suggest and it does not agree with the solution suggested in the book.
Comment: @IRO What do you mean that it doesn't model the initial states? I condition on the first three flips, compute the expectation under each of the eight possible conditions, and then I average the results (since the eight initial strings are all equally likely) and add 3. When I do this I get an answer of 10 (with p=q). What answer do you get? It seems likely that you just made an error in setting up the transition probability matrix.
Comment: @IRO I also tried direct simulation and I get a similar result; doing 1000 Monte Carlo iterations gave me an average number of flips of 10.162 (again with p=q).
Comment: Indeed your numeric result agrees with the formula given above. My question regards exactly what you just explained: what if p<>q? I suppose that I would have to determine the probability of each initial state as ppp, ppq, pqp, etc., and compose the row vector that multiplies the solution of the system, correct? This sounds reasonable to me, however when I solved the system it resulted in a too big expression that I could not manipulate further. Perhaps I made some mistake, but if you can give some hint how to simplify the resolution (perhaps using a solver), it would be of great help.
Comment: @IRO Do you really need a closed form solution for the expectation? It seems to me that this closed form could be quite complicated.
Comment: This was my goal, although your explanation opened my eyes to another way of resolution. I have just find out another demonstration, which I will post here soon. Thanks so far!
Answer: Consider a Markov Chain (MC) whose states are:
$S_0$: no flip (initial state), or the only flip was a T, or the last two flips were TT;
$S_1$: the last flip was an H;
$S_2$: the last two flips were HT;
$S_3$: the last three flips were HTH.
These states and the transitions between them are represented in the figure below:

Such MC induce a partition of the possible strings. Let $m_{i,j}$ be the expected number of flips needed to visit state $j$ for the first time after departing from state $i$. We can write the following system of linear equations:
\begin{equation}
m_{0,3}=1+q.m_{0,3}+p.m_{1,3}\\
m_{1,3}=1+p.m_{1,3}+q.m_{2,3}\\
m_{2,3}=1+p.m_{3,3}+q.m_{0,3}\\
m_{3,3}=0
\end{equation}
Where the first equation means that the expected number of flips to reach state $S_3$ from state $S_0$ is one flip plus whatever number is needed after this flip: with probability $q$, this flip resulted in a T, the state is again $S_0$ and the remaining expected number to reach $S_3$ continues to be the same; and, with probability $p$, this flip resulted in an H, the state becomes $S_1$, and the remaining expected number is the analogous number needed for going from $S_1$ to $S_3$. The other equations are built similarly.
Solving this system of equations and doing some mechanic algebra, we obtain $m_{0,3}=(pq+1)/(p^2q)$ as proposed.
I think that this solution is simple enough, however I could not check how this relates to the demonstration suggested by the book that I mentioned in the question.
Comment: That's another nice approach, which involves a bit more delicate setup but less calculation in the end. You can get something similar by "compressing" the state space of my approach by identification of "equivalent" states. For example, from the perspective of getting to HTH, THT and HHT are the same state, so they may be identified. This "compressed" version of my approach is not quite the same as yours, however, because your approach explicitly models the first three flips rather than building them into the initial distribution.
Comment: To be specific, one may compress my approach by identifying THH with HHH; THT with HHT; and HTT with TTT. HTH and TTH of course cannot be identifed. So my approach can have its state space reduced to 5 states instead of 8.

Flip a coin until getting HTH


how to complete order review and send to the users email adress specified while placing the order as a confirmation massage

Question: hello i was following a tutorial on a javascript mastery video on creating an ecommerce web shop everything was ok it uses stripe for payment but i dont want to use online payment i want to use payment on delivery but the customers should receive order summary via email after placing order
this is the link to the github project i want to modify if someone can help me modify or modify it for me and push it to github i  will apreciate to download and review how it was archived am new to react https://github.com/adrianhajdin/project_e_commerce
Comment: Stackoverflow is for asking about specific problems, not essentially asking people to code entire projects for you.
Comment: itsnot coding the entire project its removing the stripe and sending order email the project is already coded just a litle modification
Answer: you need backend to store users and orders, then it will be easy to send mail with order summary after user placing order.
Comment: iam using commerce js to store and upload the product can i use webhook with it


Woocommerce 2 items in the cart = price x

Question: I would like to add conditional pricing to the woocommerce cart.
I have business card products priced at 65.00 for 250 and 85 for 500. I would like it so when a user adds two product items in the cart at the individual price of 65.00 the cart total is not 130 but rather a value I specify.
I know some of the woothemes plugins could do this but I don't want to pay as I know somewhere out there is a simple enough solution.
Any help much appreciated.
Thanks
Comment: Ok, well then you are going to need to spend time instead, because this isn't a site that just gives products away for free or does your work for you. Browse around SO for similar quesitons and please come back with a specific question/problem.
Comment: The "simple solution" is to use [Dynamic Pricing](http://www.woothemes.com/products/dynamic-pricing/).
Comment: thanks for the link Helga, but I am afraid I don't have $129 for this plugin. Would love to but can't
Answer: You can just create a woocommerce coupon in Wordpress that will discount the desired products(s)/cart total by a specific percentage amount.
You can set various "Usage Restriction" settings that will make the coupon only be applicable under certain circumstances (such as minimum spend, products, expiration date). Users can then be provided with a a coupon code to enter at the cart checkout.
This will be the easiest and fastest the solution that doesn't involve creating code for Dynamic Pricing.
The following link will help you to set up a Coupon:
WooCommerce 101 Coupons
For more specific pricing needs you will have to create a function that hooks into the Woocommerce shopping cart in the functions.php file. The logic for the function should be something like this:

Get the cart contents.
Check that the number of items in the cart are equal to 2 (or more if you want).
if $cart_count == 2 then $cart_total - $x_amount.

This Question will help you understand how to write a simple function to achieve this.
Best of luck! :)


Minha função em Javascript não está sendo "enxergada"

Question: Estou implantando funcionalidades em Javascript para fechar um submenu. Para fechar com ESC e clicando no item de menu que abriu o submenu está funcionado. O que não estou conseguindo fazer funcionar é a função que captura o click fora das áreas do submenu aberto e do item de menu, parece que a função nem está sendo lida. Segue código abaixo para conferência, críticas e sugestões. Sou iniciante e ainda não estou familiarizado com as boas práticas de programação, então fiquem à vontade para criticar o que estiver em desalinho às boas práticas.
Detalhes: a parte de HTML e CSS foi copiada de um exemplo, o que fiz foi mudar o nome de algumas classes/Ids mas o código Javascript foi implantado por mim. Havia postado o código no do Codepen, copiei e colei aqui, então está tudo como se fosse um arquivo só. Caso queiram ver no Codepen, o link é esse [Link para o Codepen][1] (nem sei se posso postar o link aqui, então se estiver infringindo as regras, por favor me desculpem).
EDIT: conforme pedido nos comentários, coloquei o código em ordem. A parte de Javascript que está dando problemas fica bem no final, onde tem o Alert("cliquei fora do menu").
HTML
<!DOCTYPE html>

    <link rel="stylesheet" href="css/estilos.css"/>

Home

News

          Clique-me

            Link 1
            Link 2
            Link 3

CSS
ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #333;
}

li {
    float: left;
}

li a, #Menu_Principal_ITENS {
    display: inline-block;
    color: white;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
}

li a:hover, .dropdown:hover #Menu_Principal_ITENS {
    background-color: red;
}

li.dropdown {
    display: inline-block;
}

#SubMenus_MONTAGEM {
    display: none;
}

#SubMenus_MONTAGEM {
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
}

#SubMenus_MONTAGEM a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
    /* text-align: center; */
    text-align: left;
}

#SubMenus_MONTAGEM a:hover {background-color: #f1f1f1}

.CSS_Exibe_Oculta {
display:block;
}

JAVASCRIPT
function SubMenu_EXIBE_OCULTA(menu){
var obj=document.getElementById(menu);
  if(obj.style.display == 'block'){
    obj.style.display = 'none';
  }
  else
  {obj.style.display = 'block';
  }

  document.querySelector('body').addEventListener('keydown', function(event) {
    var tecla = event.keyCode;
    if (tecla == 27){
      obj.style.display = 'none';
    }
  });
}

var modal = document.getElementById('menu');
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
    alert("cliquei fora do menu");
  }
}

Comment: Dá uma olhada no código que vc postou na pergunta. Está tudo desorganizado. Por favor, edite a pergunta com o código bem organizadinho para que se possa analisar melhor.
Comment: Tens razão Sam, ficou desorganizado mesmo, é que copiei do Codepen e fui colando meio que com pressa, agora ficou tudo separado. A parte do código que não está executando é bem no final, onde tem o Alert, que coloquei justamente para ver que essa parte do código não está sendo executada.
Answer: Tente colocar o EventListener referente ao body, fora do escopo da função 'SubMenu_EXIBE_OCULTA' alterando também alguns comandos:
function SubMenu_EXIBE_OCULTA(menu){
  var obj=document.getElementById(menu);
  if(obj.style.display == 'block'){
    obj.style.display = 'none';
  }
  else {
    obj.style.display = 'block';
  }
}

document.querySelector('body').addEventListener('keydown', function(event) {
  var obj = document.getElementById('SubMenus_MONTAGEM');
  var tecla = event.keyCode;
  if(tecla == 27 && obj.style.display == 'block'){
    obj.style.display = 'none';
  }
});

Comment: Olá Caio, desculpa a demora em responder. Fiz isso mas não adiantou, acabei desistindo desse exemplo, estou tentando um novo e já estou com um problema que acho que vou postar aqui. Obrigado mesmo pela ajuda.


What is the probability that in a sample of $5$ people that all of them are blonde? at least two of them are blonde?

Question: I am dealing with this probability problem and I am stuck. I would really appreciate if you could please help me. Thanks in advance.

In a population of $80$ people, $30\%$ are blonde and $70\%$ are black-haired. If we take a sample of $5$ guys,

what is the probability that all of them are blonde?
what is the probability that at least two of them are blonde?

I have thought for the first one that it should be , by Laplace's rule, $\frac{24\choose 5}{80\choose 5}$. But, I also would say that it is true that it is a binomial distribution and thus it should be $(0.3)^5$. Nevertheless, these answers do not coincide.
Comment: Since this is a site that encourages and helps with learning, it is best if you show your own ideas and efforts in solving the question. Can you edit your question to add your thoughts and ideas about it? Don't worry if it's wrong - that's what we're here for.
Comment: A population of $12$ and $30$ percent are blond... So there are 3.6 blond persons. Weird, I would say that the number of persons is always a nonnegative integer.
Comment: Even with your edit to $15$ people, $30\%$ of $15$ is $4.5$ so you didn't really explain anything.
Comment: Okey, thank you for your suggestion. I just added this information.
Comment: The question is (as drhab points out) quite unclear and cannot really be answered before you explain the confusion.
Comment: It was a tipo. Should say 15. Changed. Thanks!
Comment: I put now good numbers. Sorry!
Comment: Agree with all of you. The numbers were not correct. Now they are. Sorry for the confusion
Comment: If it is a selection of $5$ distinct persons out of $80$ then hypergeometric distribution must be applied (as you did). Not binomial. That must be applied if the persons are *replaced* after selection so that a person can be selected more than once. So your answer of 1) is okay. Do you still want an answer on 2)?
Comment: Yes, please! Thank you very much
Answer: If it is a selection of $5$ distinct persons out of $80$ then hypergeometric distribution must be applied (as you did). Not binomial. That must be applied if the persons are replaced after selection so that a person can be selected more than once. So your answer of 1) is okay.
Also for 2) we use hypergeometric distribution and if $W$ denotes the number of blondes we find probability:$$P(W\geq2)=\sum_{w=2}^5P(W=w)=\sum_{w=2}^5\frac{\binom{24}w\binom{56}{5-w}}{\binom{80}5}$$
A summation of $4$ terms. We can make it a bit less complicated like this:$$P(W\geq2)=1-P(W\leq1)=1-P(W=0)-P(W=1)=1-\frac{\binom{24}0\binom{56}{5}}{\binom{80}5}-\frac{\binom{24}1\binom{56}{4}}{\binom{80}5}$$


Why do official Olympics youtube channel in USA hiding Indian videos?

Question: This is the screenshot of official Olympics Youtube channel from India (July 30, 2021):

Here is the official Olympic Youtube channel from USA location (July 30 2021):
Comment: I'm not sure this is on-topic here, as it's about the actions of a social media account, rather than actually being about sport. It's worth noting that content being restricted to certain locations is perfectly normal.
Comment: When you click on an Indian video from a US location, does it say "This video is not available in your country"?
Comment: Location blocking by YouTube and its uploaders is not an issue restricted, or even primarily relevant, to sports. It has been happening across media for decades. There is a valid on-topic question regarding the mechanics of this, as it is of interest to sports fans and those involved in the pro sports and related industries. But I do not believe this is that question..
Comment: @F1Krazy "Things of interest to fans" are in our scope, and the Olympics is probably the biggest thing of interest to fans globally so I think it's generally on-topic.
Answer: On your first screenshot, 10 videos out of 15 are related to the Indian athletes. Do you think this is representative of what is going on in the Olympics in general?
The real question is not "Why does Youtube channel in USA hide Indian videos", but "Why does Youtube channel in India show mostly Indian videos". The answer is obvious: because that's what Indian viewers are likely to be interested in. As the other countries are concerned, India now has 1 silver and 1 bronze medal (hopefully they get more later on), this doesn't make it likely to make the front page in the USA or worldwide.
Answer: If you want a definitive answer on why YouTube make the decision they make about which videos to show, you'd have to ask YouTube. Looking at the general case, there are two primary reasons why a social media account might do this:

The right to show certain content in certain territories. The rights to show the Olympics are enormously complicated (and expensive) - it may be the case that the rights to the Indian-specific videos do not allow them to be shown in the USA.
Interest of fans. There is no law which says a social media account has to show the same content in every country (at least, not in the USA). It is a perfectly valid editorial decision for whoever is managing the content on the Olympics YouTube channel to say that a video about a non-American athlete competing in a sport which is barely played in America with non-English commentary is of very low interest to American fans.


Java.Util.Set não adiciona novos elementos

Question: Na variavel loja ao tentar adicionar um novo elemento do tipo "Loja" ele sempre fica somente com um elemento e não adiciona um novo elemento. E nunca adiciona um novo. Segue os codigos:
Metodo main:
public static void main(String[] args) {
        Usuario usuario = new Usuario();
        Set<Integer> idsLojas = new HashSet<>();
        idsLojas.add(123);
        idsLojas.add(333);
        idsLojas.add(3333);

        Set<Loja> lojas = new HashSet<>();
        for (Integer idLoja : idsLojas) {
            lojas.add(new Loja(idLoja));
        }
        usuario.setLojas(lojas);

        System.out.println(usuario.getLojas().size());
    }

Construtor de loja:
public Loja(Integer id) {
        this.setId(id);

    }

O resultado sempre é 1, mesmo eu adicionando 3 valores.
Comment: E a variável local `lojas`, tem apenas um único elemento?
Answer: Sobrescreva os métodos equals() e hashcode() da classe Loja. De preferência deixe o seu IDE criá-los por você. Quando ele lhe pedir por quais critérios especificar os métodos adicione o id da loja como critério.
Leia mais aqui: Como definir a comparação de igualdade entre dois objectos presentes num ArrayList?
Comment: Talvez o problema esteja no `Usuario`: o `setLojas` ou o `getLojas` podem estar fazendo bobeiras. Não há garantias disso pois o código não foi mostrado
Comment: Não sei se o problema é esse, pois sem sobrescrever `equals` e `hashCode` o código já funciona (cria um `Set` com 3 lojas): https://ideone.com/fkd5Fy - se o `Set` dele está com 1 elemento, o problema pode estar em outro lugar (ou então ele implementou `equals` e `hashcode` da maneira errada, isso explicaria o `Set` estar com apenas 1 elemento: https://ideone.com/hfprQ3)
Comment: Aproveitando, a implementação de `hashCode` do Java _normalmente_ faz com que 2 objetos distintos tenham códigos de _hash_  distintos, e o `equals` meio que valida pela referência do objeto (não o conteúdo, já que a mesma referência implica mesmo conteúdo) [esse comentário é basicamente o do @hkotsubo, mas comecei a escrevê-lo antes de ver que o hkotsubo havia comentado]
Comment: @JeffersonQuesado Tem razão. Não me atentei ao fato que o Object.equals() deveria ser suficiente para comparar as instâncias de Loja no Set. Então esqueçam tudo o que falei (ou não, é bom saber).
Comment: Eu não cheguei a entender o que aconteceu do "set reconhecer como objetos duplicados", mas se ajudou, beleza. :)
Comment: O erro estava acontecendo por causa do hashCode e equals, por que o set, a lista, estava reconhecendo como objetos duplicados.


Is a goal scored if the goalkeeper, but not the ball, enters the goal?

Question: Is a goal scored if a goalkeeper holding the ball enters the goal, but keeps the ball out of the goal?
Answer: No goal. This is a basic rule of football: it's the position of the ball that matters, not the players.
Specifically quoting from the Laws of the Game, Law 10 - The Method of Scoring (page 35):

A goal is scored when the whole of the ball passes over the goal line, between
  the goalposts and under the crossbar

(my emphasis). In your example, the whole of the ball has not crossed the goal line, so no goal is scored.
Answer: Even if the goalkeeper is standing inside the goal post, as long as the ball has not crossed the goal line it is not a goal / if the ball in the keepers hand immediately while saving a shot and his legs or one leg is inside the goal, no goal if ball has not crossed goal line.
Answer: Goal wont be scored if goalkeeper is standing in goal holding the ball but his hands should not be inside goal even in air if the ball crosses the line even in air it will be considered as a goal
Comment: Not quite true - the keeper's hands can be in the goal so long as the whole of the ball hasn't crossed the line.


Calculating the SD for the z-test

Question: The following picture, taken from some lecture notes, shows a very strange formula for calculating the SD, that I have never come accross. Can somebody explain how this formula yields the SD, even though I was originally taught another formula (square root of variance)?
Comment: This formula *is* the square root of a variance.  The variance is based on a Binomial distribution.
Answer: That $\sigma_{p}$ looks like a standard error for the proportion.

The variance for a single Bernoulli case is $\pi (1-\pi)$

so the variance for the sum (i.e. binomial) is $n\pi (1-\pi)$

and variance for the sample proportion $\frac1n\pi (1-\pi)$.

Then take the square root

Calculating the SD for the z-test


Como resolver o erro "ReferenceError" para nodeJS no AWS Lambda acessando o DynamoDB

Question: Ao usar o AWS Lambda para inserir registros no dynamoDB, via console, recebo o seguinte erro:
<code>{
    "errorType": "ReferenceError",
    "errorMessage": "require is not defined in ES module scope, you can use import instead",
    "stack": [
        "ReferenceError: require is not defined in ES module scope, you can use import instead",
        "    at file:///var/task/index.mjs:1:13",
        "    at ModuleJob.run (node:internal/modules/esm/module_job:193:25)",
        "    at async Promise.all (index 0)",
        "    at async ESMLoader.import (node:internal/modules/esm/loader:530:24)",
        "    at async _tryAwaitImport (file:///var/runtime/index.mjs:921:16)",
        "    at async _tryRequire (file:///var/runtime/index.mjs:970:86)",
        "    at async _loadUserApp (file:///var/runtime/index.mjs:994:16)",
        "    at async UserFunction.js.module.exports.load (file:///var/runtime/index.mjs:1035:21)",
        "    at async start (file:///var/runtime/index.mjs:1200:23)",
        "    at async file:///var/runtime/index.mjs:1206:1"
    ]
}
</code>
ABAIXO O CÓDIGO QUE ESTÁ SENDO USADO.
<code>const AWS = require("aws-sdk");

const insertArtist = async (event) => {

    // const {id, name, age, startDate} = JSON.parse(event.body);

    const id = event.id;
    const name = event.name;
    const age = event.age;
    const startDate = event.startDate;

    var responseBody = "";
    var statusCode = 0;

    const dynamodb = new AWS.DynamoDB.DocumentClient();

    const newArtist = {
        id,
        name,
        age,
        startDate
    };

    try {
        await dynamodb.put({
            TableName: "Artist",
            Item: newArtist
        }).promise();

        responseBody = JSON.stringify(newArtist);
        statusCode = 200;

    } catch (e) {

        responseBody = JSON.stringify(e);
        statusCode = 400;

    }

    var response = {

        responseBody: responseBody,
        statusCode: statusCode

    };

    return response;

};

module.exports = {
    handler:insertArtist
};
</code>
Comment: Você pode verificar a parte `type` no arquivo `package.json` e veja se a parte do `"type"` for `"module"`. Se sim, você receberá este erro. Você tem que colocar `"commonjs"` no lugar. Assim: `"type": "commonjs"`
Answer: Você pode tentar usar essa importação
const AWS = require("@aws-sdk/client-dynamodb");
Pelo que parece a versão do SDK para essa versão do node tem outra importação.
Answer: Parece apenas uma configuração errada com o NODEJS, já que aparentemente ele não reconhece a forma de importar com o 'require', provavelmente apenas mudar o type no package.json deve resolver:
"type":"module" para "type":"commonjs"
Exemplo de package.json
Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


Using hook_form_alter() only on loading

Question: I am using hook_form_alter() in  Drupal 6, which successfully works. As for now, when I submit the form, it again runs the same hook. I want to run it only on load and edit.
Do you have any idea on how I do this?
Answer: Use the following code for the load operation of existing forms
<code>hook_form_alter(&$form, &$form_state, $form_id) {

  if(empty($form_state['post'])) {
    //do you load operation
  }

}
</code>
Comment: I am not sure this works, as [drupal_get_form()](http://api.drupal.org/api/drupal/includes%21form.inc/function/drupal_get_form/6) set `$form_state['post']` with `$form_state['post'] = $_POST;` right before invoking `hook_form_alter()`.

Using hook_form_alter() only on loading


Regex correto em C++ retornando 0

Question: Caros,
Criei uma expressão regular para instruções MIPS. Foi uma trabalheira danada, mas consegui. Pelo menos no regexr.com funciona, mas no C++ não. Eis o código com a expressão alguns exemplos de string com instruções que devem ser aceitas:
Código:
bool regexOk(string str){
    regex express{"[a-z]{2,4}[\s](([\$][a|f|g|k|r|v|s|t][a|t|p|\d]\,\s[\d]*\([\$][(a|f|g|k|r|v|s|t)][a|t|p|[\d]\)|(\$szero\,\s[\d]*\([\$][(a|f|g|k|r|v|s|t)][a|t|p|[\d]\)|(-?[\d]*\,\s[\d]*\([\$][(a|f|g|k|r|v|s|t)][a|t|p|[\d]\))))|([\$][a|f|g|k|r|v|s|t][a|t|p|\d]\,\s|(\$szero\,\s|(-?[\d]*\,\s)))([\$][a|f|g|k|r|v|s|t][a|t|p|\d]\,\s|(\$szero\,\s|(-?[\d]*\,\s)))([\$][a|f|g|k|r|v|s|t][a|t|p|\d]|(\$szero|(-?[\d]*))))"};
    return regex_match(str, express);
}

Strings:
lw $t0, 0($t7)
srl $t0, $t0, 1
addi $t1, $t7, 28
sll $t0, $t0, 2
add $t1, $t1, $t0
lw $t1, 0($t1)
addi $t1, $t1, 1
lw $t0, 0($t7)
sll $t0, $t0, 2
addi $t2, $t7, 28
add $t2, $t2, $t0
sw $t1, 0($t2)
lw $t0, 0($t7)
addi $t0, $t0, 1
sll $t0, $t0, 2
addi $t1, $t7, 28
add $t1, $t1, $t0
addi $t2, $szero, -1
sw $t2, 0($t1)

Sim, a expressão ficou imensa e difícil de ler, mas no regexr.com funciona (rs), então imaginei que no C++ funcionaria também. Ela não está perfeita, mas serve para o propósito atual. Basicamente, ela pesquisa pelos seguintes grupos:

instrução registrador, endereço

ou

instrução registrador, registrador, registrador

Estes registradores podem ser também uma constante ($szero) ou um valor inteiro.
Como o regex do C++ funciona? Tem algo errado na expressão? Se não, qual seria o motivo do erro?
Comment: Olá acho o problema está nas barras, o regex de C++ deve estar identificando o \ como escape veja esse exemplo aqui no [SOpt](https://pt.stackoverflow.com/questions/123262/regex-com-stdregex-em-c?rq=1)(leia principalmente os comentários da resposta aceita), e este no [cppreference](https://en.cppreference.com/w/cpp/regex) repare o uso das barras.
Comment: @DiegoFerreira, eu havia visto essa resposta em minha pesquisa, mas não acho que seja o caso, pois as barras que estou usando são todas invertidas intencionalmente para o escape ou para os metacaracteres do regex (\s para espaço branco, etc.). Parece que na resposta que vc sugeriu, o erro era no uso de /, ao invés de \.
Comment: eu reescrevi o seu código fazendo que cada vez que ele encontrasse a sua expressão regular, ele circulasse com [ ], a saída foi [ lw $t0, 0($t7) ] para cada linha da string, é mais ou menos isso que voce quer ?
Answer: Com relação a sua expressão regular você deve usar \\ ao invés de \, com relação ao código o erro está no uso de std::regex_match, segundo a documentação encontrada aqui, ele só procura por correspondências completas veja o caso abaixo extraído do site que mencionei na seção Notas:
Como o std::regex_match considera somente correspondências completas, a mesma expressão regular pode fornecer correspondências diferentes entre std::regex_match e std::regex_search:
std::regex re("Get|GetValue");
std::cmatch m;
std::regex_search("GetValue", m, re);  // retorna true, e m[0] contém "Get"
std::regex_match ("GetValue", m, re);  // retorna true, e m[0] contém "GetValue"
std::regex_search("GetValues", m, re); // retorna true, e m[0] contém "Get"
std::regex_match ("GetValues", m, re); // retorna false

Segue um exemplo onde é feito o uso de regex:
#include <iostream>
#include <regex>
#include <string>
#include <iomanip>

using namespace std;

bool regexOk( const string&, const regex& );
void print_regex( const string&, const regex& );

int main()
{

    string str = "lw $t0, 0($t7)\nsrl $t0, $t0, 1\naddi $t1, $t7, 28\nsll $t0, $t0, 2\nadd $t1, $t1, $t0\nlw $t1, 0($t1)\naddi $t1, $t1, 1\nlw $t0, 0($t7)\nsll $t0, $t0, 2\naddi $t2, $t7, 28\nadd $t2, $t2, $t0\nsw $t1, 0($t2)\nlw $t0, 0($t7)\naddi $t0, $t0, 1\nsll $t0, $t0, 2\naddi $t1, $t7, 28\nadd $t1, $t1, $t0\naddi $t2, $szero, -1\nsw $t2, 0($t1)";

    regex expression( "[a-z]{2,4}[\\s](([\\$][a|f|g|k|r|v|s|t][a|t|p|\\d]\\,\\s[\\d]*\\([\\$][(a|f|g|k|r|v|s|t)][a|t|p|[\\d]\\)|(\\$szero\\,\\s[\\d]*\\([\\$][(a|f|g|k|r|v|s|t)][a|t|p|[\\d]\\)|(-?[\\d]*\\,\\s[\\d]*\\([\\$][(a|f|g|k|r|v|s|t)][a|t|p|[\\d]\\))))|([\\$][a|f|g|k|r|v|s|t][a|t|p|\\d]\\,\\s|(\\$szero\\,\\s|(-?[\\d]*\\,\\s)))([\\$][a|f|g|k|r|v|s|t][a|t|p|\\d]\\,\\s|(\\$szero\\,\\s|(-?[\\d]*\\,\\s)))([\\$][a|f|g|k|r|v|s|t][a|t|p|\\d]|(\\$szero|(-?[\\d]*))))" );

    cout << boolalpha << regexOk( str, expression ) << endl;
    print_regex( str, expression );
}

bool regexOk( const string& str, const regex& expression )
{
    if( regex_search( str, expression ) ){ return true; }
    return false;
}

void print_regex( const string& str, const regex& expression )
{
    string new_str = regex_replace( str, expression, "[$&]");
    cout << new_str << endl;
}

Comment: agora sim, entendi o que vc queria dizer na primeira vez. Eu pensei que bastava uma barra invertida para ele entender como caratere de escape. Muito obrigado, meu caro! Agora funfou.
Comment: E também essa diferença entre o regex_match e o regex_search, que desconhecia. vlws mesmo!

Regex correto em C++ retornando 0


Normalized gradients in Steepest descent algorithm

Question: In general setting of steepest descent algorithm we have,
\begin{equation}
x_{n+1}=x_n-\alpha G_n,
\end{equation}
where $\alpha$ is the step size and $G_n$ is the gradient evaluated at the point $x_n$.
I was trying to write a simple algorithm performs the gradient descent method but I get confused how to select the step size.
I know that if I am going to use normalized gradient descent I will get rid of the magnitude (always 1 by definition) and it will just give us the optimal direction to move. If I used this method with a fixed step the speed of convergence will be extremely large.
I read that it doesn't matter whether we use the normalized or unnormalized gradient but what really matters is how the step size $\alpha$ is selected.
My question is how do I select the step size? Or how do I select the step size depending on steepness? Any suggestion would be greatly appreciated.
Answer: If your gradient is Lipschitz continuous, with Lipschitz constant $L>0$, you can let the step size be $\alpha\leq\frac{1}{L}$ (you want equality, since you want an as large as possible step size). This is guaranteed to converge from any point with a non-zero gradient.
Update: At the first few iterations, you may benefit from a line search algorithm, because you may take longer steps than what the Lipschitz constant allows. However, you will eventually end up with a step $\alpha\leq\frac{1}{L}$.
Comment: I'm not sure what you mean by selecting the step size base on steepness. The Lipschitz constant is an upper bound on how fast the gradient changes, and so takes the "steepness" into account. The Armijo (and the Wolfe) conditions in backtracking line search uses the gradient, and thus takes the "steepness" in account. Are you trying to work out some new condition of your own instead of using the proved and time tested approaches?
Comment: Sorry, I should've used your notation, in which $\nabla f(x_n)=G_n$. Note that $p_n=-G_n$ (its negative!), so $p_n^TG_n=-G_n^TG_n<0$. I have assumed that $x_n$ is a vector, so $\nabla f(x_n)=G_n$ is the gradient at $x_n$.
Comment: I am not familiar with the concept of Lipschitz to be honest. Any simple suggestion how to let the magnitude of the gradient decide the step size?
Comment: No, I am not trying to work out some new condition. I am new in the area of optimization that's why I am asking which conditions people used to use in their algorithms. I tried to read the theory behind these conditions but I am trying to find a source code maybe of steepest descent to see how people use these conditions in their algorithms. It happens to know how to find out the source code of steepest descent?
Comment: The source code depends entierly on what language you are implementing this in. Gradient descent is really simple to implement and you wrote the pseudo code in your question. $x_{n+1}$, $x_n$ and $G_n$ are vectors, so you'll need a matrix library. In e.g., Matlab and R this is available out-of-the-box, for Python you have it in NumPy and SciPy. $G_n$ and $L$ depends on your problem, so you'll have to work them out yourself.
Comment: For $G_n$ I calculated numerical derivatives using a finite approximation. The problem it's the $L$ because I didn't understand actually the idea behind this. Also I have the same problem with the Armijo and the Wolfe conditions. I don't really understand how to connect these in my algorithm. I tried to find the source code in Matlab or R but I couldn't. I found only the description of this method. Could you please help me with this?
Comment: See the pseudo code in: https://en.wikipedia.org/wiki/Wolfe_conditions#Armijo_rule_and_curvature Start with condition i) and let your $p_n=-G_n$ (your descent direction). Let $\alpha_1=1$ and reduce it by some constant $0<\rho<1$ in every iteration until condition i) is fulfilled.
Comment: Regarding the $G_n$, if you used the wolfe conditions I guess makes difference if you use normalised or unnormalised gradients. Since we want the magnitude of the gradient dictate the step size this means that we need to use unnormalised gradients or am I wrong?
Comment: You do not need to normalise the gradient. Note that the subproblem that backtracking line search seeks to solve is $\min_\alpha f(x_n+\alpha_n p)$, and so scaling the gradient is equalent to scaling $\alpha$. The only requirement is that $p$ is a descent direction, i.e. that $p^T\nabla f(x_n) < 0$.
Comment: One question regarding $p^T \bigtriangledown f(x_n)$. The $p_n$ is the descent direction. The  $\bigtriangledown f(x_n)$ is the derivative of the cost function $f$ with respect to the parameters? If so, the $\bigtriangledown f(x_n)$ is the same thing as the $p_n$?
Comment: OK now it makes sense. If I am going to use the Wolfe conditions I need to start with $\alpha_1 =1$? Or can I use a larger $\alpha$ maybe 10? I guess that in each iteration the $\alpha$ it's going to be decreased so has an impact on the speed of convergence. Can I half the size of $\alpha$ in each iteration as a backtracking line search? There is any more efficient way?
Comment: This depends on your algorithm. If you use the Newton algorithm, for instance, you should start with $\alpha_0=1$, because the algorithm will always choose this when it has reached the quadratic phase of the convergence. You can safely let $\alpha_0=1$ for any algorithm (as far as I know).
Comment: If this was at all helpful to you, feel free to upvote and if it answered your question, you should accept the answer. Otherwise you should state that it does not answer the question.
Comment: Sorry for not replying sooner. Your comments were very helpful actually. Thank you very much.
Answer: What you want to be looking at is Line Search algorithms. One of the simplest ones, Backtracking line search will start with a large step size and iteratively shrink it, according to the observed decrease in the objective function.
Comment: Well, that's something that I already tried. In case the $x_{n+1} > x_n$ then repeat the process by halving the step size until  $x_{n+1} < x_n$. But I wanted to add a controlling power regarding the steepness. I am interested to know how to make the step size depending on steepness.
Answer: for getting optimum step size multiply a factor a in step size and repeat multiply with same factor untill unless your new calculated value of function is equal or greater then old value of function (Woolfe's first criteria). If new value of function is less than old one then stop multiplying the factor and this will be your new step size with proper magnitude.


Doubt about conservative fields in 2D and 3D

Question: Regarding a conservative field $\vec{F}$ in a region $D \subseteq R^2$, I know that the requirements are:

Curl of $\vec{F}$ is $0$.
$\vec{F}$ is defined in D (doesn't have singularities in D).

But I have doubts about the conditions that must be met for a vector field to be considered conservative in $R^3$, as I have understood (by the comments of teachers or test solutions I've seen), it is not necessary to show that a vector field is defined in a region $D$ to consider it as conservative in D, it seems that that is enough if the curl is 0, but I never managed to understand it (if it really is like that), why is that so?
Comment: I don't think it would matter as long as you do not go over the singularity. For example the electric field of a point charge contains singularity, yet it is still a conservative field.
Comment: @grdgfgr If that is the case, what is the difference between the radial fields $-r^{-2}e_r$ in two and three dimensions? In a plane through $(0,0,0)$, both are the same, and both have a singularity at zero. Therefore any line integrals with paths in such a plane should behave in the same way, right?
Comment: @Chappers: Radial fields where the strength depends only on the distance to the center are always conservative (no matter what that dependency is), so that is not a really good example.
Comment: @Chappers wouldn't a radial field in two dimensions be $r^{-1}e_r$
Answer: The correct condition is that the field to be defined on a simply connected subset of $\mathbb R^n$ before a local condition is enough to be sure it is conservative.
For example, consider the following field defined on $\mathbb R^3$ except for the $z$-axis:
$$ \vec F(x,y,z) = \frac1{x^2+y^2}(-y,x,0) $$
This is not conservative -- if you go around the unit circle in the $xy$-plane you either win or lose $2\pi$ energy, depending on the direction. But the curl is $0$ everywhere the field is defined.


Segmentation Fault after pthread_create()

Question: Creating a thread with this:
pthread_t thread;
pthread_create(&thread, NULL, (void*)&serve_connection, (void*)sockfd);

The function I am calling is defined as:
void serve_connection (void* sockfd) {
ssize_t  n, result;
char line[MAXLINE];
connection_t conn;
connection_init (&conn);
conn.sockfd = *((int*)sockfd);
while (! shutting_down) {
...
...
}}

The rest of the function is in the '...' but it is irrelevant because I have traced the seg fault to
conn.sockfd = *((int*)sockfd);

Where conn.sockfd is of type 'int'.
Originally serve_connection was:
void serve_connection (int sockfd){
...
conn.sockfd = sockfd;
...
}

But I am calling it from a thread so that had to be changed. I should also note that the sockfd being passed to pthread_create is an int with a value.
I'm also getting these warnings on compiling:
warning: ISO C forbids conversion of function pointer to object pointer type
warning: cast to pointer from integer of different size
warning: ISO C forbids passing argument 3 of âpthread_createâ between function pointer and âvoid *â
note: expected âvoid * (*)(void *)â but argument is of type âvoid *â

These all refer to the line where I call pthread_create. I've ignored the warnings until now because the program runs up until the line specified above so I assume the function is being called correctly. I just can't figure out what is causing the segmentation fault it as I'm still new to working with pthreads (I'm assuming I'm calling or declaring something wrong, but looking at the libraries hasn't really helped).
Answer: In your case, consider replacing
conn.sockfd = *((int*)sockfd);

by
conn.sockfd = (int)sockfd;

You didn't have passed the sockfd variable as a pointer so you cannot dereference it. Take a look at : http://en.wikipedia.org/wiki/Dereference_operator
Answer: I think you should change the assignment as follows:
conn.sockfd = (int)sockfd;


Trouble when running autogen.sh

Question: I have downloaded R tree from http://libspatialindex.github.com/
Since on running ./autogen.sh I was getting file/folder not found, therefore I downloaded the file autogen.sh from the github repository given below:
https://raw.github.com/libspatialindex/libspatialindex/9a5a2f4d83c3ec7be4dbf2c8a86341703d837185/autogen.sh
Now when I run ./autogen.sh I am getting "Permission denied"
And if I run sh ./autogen.sh I am getting:
glibtoolize or libtoolize not found. Giving up!

Please suggest what should I do now
EDIT:Also I want to use libspatialindex inside my C++ project. I am using netbeans. I mean I want to use the functions inside libspatialindex inside my netbeans project. How should I use the same. Right now I have run the config and make command in a separate directory. I am not getting as to how to use them inside my project.
Answer: Install libtool from your package manager.
Comment: Also I want to use libspatialindex inside my C++ project. I am using netbeans. I mean I want to use the functions inside libspatialindex inside my netbeans project. How should I use the same. Right now I have run the config and make command in a seperate directory. I am not getting as to how to use them inside my project.
Comment: Also thanks a lot for the prompt response. A gentle request..pls suggest a solution to my above mentioned problem also.
Comment: See some similar C++-library-in-Netbeans questions [here](http://stackoverflow.com/questions/7799493/include-c-library-in-netbeans-7-0) and [here](http://stackoverflow.com/questions/3264294/netbeans-how-to-include-other-c-static-library-project)
Answer: To fix the 'Permission Denied' error you need to edit the permissions of your autogen.sh file. Run this command:
chmod +x autogen.sh
Answer: I got this error after restoring a library from a Backup to a NTFS directory.
I discovered that another reason this can occur is if the mounted partition has noexec flag on it.

Run mount to see if noexec has been set on the partition.
Update /etc/fstab or add -o exec to the mount command.

Hope, it helps others in the same situation as me.

Trouble when running autogen.sh


finding the closest distance between a point a curve

Question: consider the curve $y=x^2$
what are the points on the curve that are the closest to the point $(1,0)$
using calculus I got the two points but what is the connection between normals and the closest distance to a curve from a point
is it that drawing normals from 1,0 and seeing where it meets the curve gives the points closest to it  - although a normal from 1,0 does go through the origin even though the origin is not the closest to the curve
please explain these observations
Comment: an arbitrary point on the curve is of the form $(x,x^2)$. Find the distance between this point and $(1,0)$ so you will have a function of $x$ that determines the distance. Find its minimum (by differentiating the function)
Comment: The line from $(0,1)$ to $(x,y)$ will be normal to the curve at $(x,y)$ if and only if $(x,y)$ is a local minimum, maximum, or inflection point of the distance function.  In your example, the origin is a local maximum.  (I'm assuming you meant the points on the curve closest to $(0,1)$?)
Comment: @mjqxxxx why is it that this happens - a normal at (x,y) if and only if it is a local min, max or inflection point
Answer: You may construct a cirle with centre in $A$ and radius $R$. It has the following equation:
$$(x-x_a)^2 + (y-y_a)^2 = R^2$$
The lowest $R$ for which this circle intersects $f(x)$ is the solution of your problem. So you have to substitute $y$ in the equation above with expression for $f(x)$ and solve resulting equation for $x$. Then you have to find the lowest $R > 0$ for which exists at least one solution. This value for $R$ will be the answer.
Answer: Distance from point (1,0) is the function:
  $$ d((x,y)) = \sqrt{(x-1)^2+(y-0)^2} $$
It's a function $(x,y) \to (d)$.
Now your curve is a function $(x) \to (x,y)$, so that
  $$ f(x) = (x,x^2) $$.
Now you can use function composition to combine them to $ d(f(x)) $ to find distance of each point.
$$ d(f(x)) = \sqrt{(x-1)^2+(x^2-0)^2} $$. Now your task is to find x with minimum value. Minimum value is found by derivative is zero,
$$ D(d(f(x))) = {{2x^3+x-1}\over{\sqrt{x^4+x^2+2x+1}}} = 0$$
Thus we're left with: $2x^3+x-1=0$, which gives us $x\approx 0.58975$.
Thus the nearest point is $(x,y)= (x,x^2) \approx (0.58975, 0.3478050625)$.
The closest distance is $d(f(0.58975)) \approx 0.537841$.
Answer: $$(1)\quad{y_1-f(x)\over x_1-x}={-1\over f'(x)}$$
Equation (1) is based on the fact that if $f(x)$ has some slope value 'm' at some point (x,y) on $f(x)$, then it also has a slope perpendicular to 'm' at the same point, and given by the negative reciprocal of 'm'.
If we let $f(x)=x^2$, then $f'(x)=2x$.
When $x_1=1$ , and $y_1=0$ , we have:
$${0-x^2\over 1-x}={-1\over 2x}$$
Clearing both sides of fractions and moving everything over to the left hand member we obtain:
$2x^3+x-1=0$
Solving for x we get: $x\approx0.589755...$
Since it's implied that $y=f(x)$, we can write $x=x_2\approx0.589755...$
and $f(x_2)=y_2\approx0.347810...$
We know that the point $(x_2,y_2)$ is on $f(x)$ because it satisfies the conditions of equation (1).  We also know that the shortest distance from our known point $(x_1,y_1)$ not on $f(x)$, will lie on the normal line emanating from the point $(x_2,y_2)$.  Consequently, the shortest distance is:
$\sqrt{(x_1-x_2)^2+(y_1-y_2)^2}\approx0.537841...$
Answer: As correctly ThePortakal mentioned, let  $(x,y)\in C$ where $C$ is the curve. Then $\|(x,y)-(1,0)\|_2=\sqrt {(x-1)^2+y^2}=\sqrt {(x-1)^2+(x^2)^2}$ because $y=x^2$. Set $f(x)=(x-1)^2+x^4$ which is differentiable. Find it's minimum let's say in $x_0$ with $f(x_0)=a$ and then the minimum distance would be $\sqrt a$.


DIY Hadoop Cluster - Heat & Dust issues?

Question: Following are links of my DIY 6-Node Hadoop Cluster using i3 Machines,

What is the best possible way to protect my design from dust & provide better heat transfer? What should I use to cover four side of my rack in order to protect it from dust?
Comment: It's kinda adorable. In a strange kinda way.
Comment: How's the performance?
Comment: good air conditioner. If you can get +15 °C then dust will be less. Much less. Also you can put 400 or 450w PSU because they are designed to provide more power and cool down PSU. So they will produce less heat.
Answer: Use real server cases with good cooling/ventilation paths.
Comment: @TomTom Google started in an era before server hardware was the sort of commodity product it is now. Cargo cult "Google does this, so we can" thinking can be harmful.
Comment: that rack is holding 6U of stuff in 42U of space. Microsoft experimented with putting servers in a tent outdoors. That doesn't make it a good idea.
Comment: "google does this" - yes but google does 'this' (whatever 'this' we're talking about, server hardware right now, sure, but other things too) because google have looked at their needs and come to that conclusion. They're not doing it because "altavista did this", and you shouldn't be doing it "because google does this". Now if you look at something google is doing and it makes sense for you too, then fill your boots. Otherwise... not so much.
Comment: @TomTom OP does not appear to be doing anything like that.
Comment: +1. Exactly what I was going to write. There's a good reason real server cases have all of those plastic ducts - to direct airflow directly onto and away from the components that produce the most heat.
Comment: -1. See, there also is a reason why some companies started not doing that. Among them little home shops that turn into GOOGLE. Yes, this setup is bad - but it is a LOT cheaper. That may be worth a lot.
Comment: @TomTom: Even if it's not the Supermicro style server case, nearly any cheapo case from your local computer shop will be better than this, and likely cheaper than any more DIY stuff, at least from the perspective of time invested. And if you start experiencing (financial) scalability problems, you have to invest a lot more work into a solution than this project.
Comment: @SvenW Yes, sure. That likely is why I have some home build wood setups in the basement - mostly computers carrying up to 6 graphics cards each. Google also started with home made. For some stuff (mostly grids) that is the best way.
Comment: Yes, but today this still is the case if you ahve out ot area requirements. Show me a decent server case to hold 5-6 high end graphics cards please.
Answer: Here's what I'd do.
Get some large sheets of thin Lexan (or even foam board / corrugated plastic board - I know this as Correx, YMMV).
Punch some holes through it, and bolt it to the holes on the uprights.  Build about a foot or more higher on the top, cut out a hole and then mount a 12v automotive radiator fan on the top.
You'll also want to build in some air-path through the "rack".  One way to encourage airflow up and across would be to block alternate shelf-sides, and then build out a "box channel" for it to flow through.  Side view.
<code>                           ^^
                           || Fan Out
            +--+-----------||----------+
            | +-+--------->++          |
   And Up   | ||                       |
            | ||                       |
            | ||-----------------------+
            | ||                       |
            | |<----------------------+|
            | <--+                    ||
            +--+-|--------------------++--+
               | +--------------------+-+ |
               |                       || |
               |                       || |
               +-----------------------|| |Air flows up
               |       +----------------> |
               |   +-----------+       || |
               |   |           |       |+ |
               +---|Filter IN  |-------+--+
               |   |           |       |
               |   +-----------+       |
               +-----------------------+
</code>
Cut out a panel at the bottom, and mount in that hole a filter from a ducted AC unit..
The theory is that air will be drawn up from the bottom (where it's cooler), through the filter panel, up past the servers, and out the hole with the fan in, on the top.
Or just buy a few 2U rack server cases from somewhere like Xcase, and then get a second hand rack to put them in.
Answer: Honestly? Unless its in a very dirty or very hot place (ambient temperature of above 30c in the room), nothing.
Those computers aren't going to generate much heat and there is loads of room around them to dissipate the heat they do generate. Not nearly enough to worry about in any case.
Comment: And if you stand the boards on edge dust will be pretty much a non-issue, as it will tend to just fall down.
Answer: Use mini-itx.
No heat. No dust. No noise. (almost) no electricity bills.
I've been running hadoop 8 nodes cluster for a month+.
The cluster is described here:
http://www.pault.com/p/table-t
The cluster is used to datamine hadoop urls:
http://hostedrobots.com/hadoop/
Comment: How about raspberry Pi?
Comment: Or soekris, yeah, right. No comparison. Raspberry Pi is an R&D toy. Mini-itx is different league, supported by intel and other big names. But then again, I think you were joking, right?
Comment: Er. Kinda.. Not really joking, more just idle ponderings.
Comment: Found this one for you then: http://serverfault.com/questions/405834/raspberry-pi-based-hadoop-cluster


Do statisticians need to be good programmers/coders to do their job well?

Question: I'm interested in majoring in statsitics in my university as an under-grad. I am wondering whether I need to be a good programmer to do statistics because I really struggled in python and java even though I studied them for 1.5 years.
Comment: 1) What is a statistician's job, is it strictly defined? 2) good programmers in a specialized statistical language/syntax or in a general / low level one (such as С++)? 3) Is good programming an ability to implement anything or to implement something efficiently (fast code etc.)?
Comment: @Tim, I can't think of a statistician position in the industry that requires no programming whatsoever. Maybe in academia?
Comment: What do you mean by job for "statistician"? This could range from "data scientist" that does lots of coding and "big data" stuff, to person who makes all the time the same PowerPoints with tables and graphs from SPSS... It really depends on industry and your aspirations. Moreover: people who are good at programming usually aim at the positions that require it, and the ones who are not, do not.
Comment: This is pretty opinion-based: **maybe we should make it wiki**?
Comment: Closely related thread: http://stats.stackexchange.com/questions/195034/what-is-a-data-scientist
Comment: @Aksakal academia, marketing research, some positions in some research companies (surveys) etc. But usually if you want to do more advanced stats, some programming is needed, I agree.
Comment: "Do statisticians need to be good programmers/coders to do their job well?" is a very opinion-based title and question, but I think this *could* be converted to being an on-topic question, if you asked something along the lines of "Are there job roles as a 'statistician' which do not involve programming?", since that seems to be the main intent of your question.
Answer: You increase your chances of getting hired in the industry very significantly if you can code well. You will also be able to ask for much higher salary. Overall, if you keep struggling then your options will be very limited not only at the start but throughout your career.
Now what is a "good programmer"? You don't have to be as good as professional programmers, but you must be able to code any algorithm you came up with. It may not be the best written code, but it must do what's required in terms of the logic of the algorithm. For a statistician that's the definition of "good" in my opinion. You should be able to implement any statistical algorithm and method that you studied so far, that's your measure of how good you are.
UPDATE:
To your struggles with Java: that's not a typical stat language, so I wouldn't hold this against you. Python is used in data science a lot, but look at who uses it: mainly people with some kind of a programming background. Some statisticians like Python, of course, but it is (like Java and C++) a system programming language. I'd call it a "proper programming language", i.e. one that even pro programmers use without reservations. What I'm trying to say is that mere fact that you're struggling with these two particular languages is not yet a sign of an issue. However, if you struggle with programming in any language (any that you tried) then you have to think about the future in this profession seriously.
Comment: As about "good" programmers: actually some argue that statisticians are usually very bad programmers and many statistical packages are badly written ;)
Comment: ... statisticians are often quite good programmers, but usually very bad software engineers.
Comment: I would add that having good programming and computer skills more generally, like understanding [closures](https://en.wikipedia.org/wiki/Closure_\(computer_programming\)) and [JSON](https://en.wikipedia.org/wiki/JSON), is really useful. For anybody, really, but especially for anybody who does data analysis (as opposed to purely mathematical statisticians).
Comment: The acme of achievement for many statisticians is being able to write a script that works for a specific problem, runs from start to finish, & is clear & non-redundant. Then the code serves as a document of precisely what was done, & we ourselves or knowledgeable colleagues can use it to help explain the analysis or easily adapt it to similar problems. But anything like writing *software* requires anticipation of what the program will do in a wide range of circumstances; & it's not, or shouldn't be, surprising, that we're not often very well prepared for it. So I'd reply to @Tim that ...
Comment: @Tim, one could argue then that if they are bad programmers, then they are not "doing their job well" as the OP described.  I think being a decent programmer is essential in modern statistics.
Comment: @StatsStudent if you define statistician as a person who is good at applied programming, that indeed you *need* to be good at programming by the definition you adopted. In essence statistics is *not* about programming, but in many areas it may be ***very*** useful, or even vital skill.
Comment: I agree statistics is not about programming, but much of modern day statistics is accomplished through programming (i.e. bootstrap).  And I'd argue that statistics are essentially worthless without the need to apply them.
Comment: @StatsStudent modern software for stats is very rich, most of the methods are already available out-of-the-box. Yes, in some cases you need to code complicated problem-specific bootstrap algorithm by hand, but in many areas you don't since the tools are already available. This really depends on what you do. You can apply vast majority of stats with no programming at all.
Comment: It can be frustrating. I was just telling my boss this morning "I'm a statistician, not a sql programmer." I can write code in sql but I'm not an expert. In prior jobs I held there were separate teams that assembled the data we needed, performed QA, and then ran statistical analyses on the data.
Comment: @RobertF not every team has dedicated data people. in my current team I write all kinds of SQL and post-SQL myself. you need to be resourceful to thrive
Comment: Part of the problem is many people, including employers and managers, don't know what statisticians do. We can program, but we're not programmers. We're modelers, idea people. Sql programming is important, but sql programmers are a dime a dozen, the companies I've worked for are overflowing with them.


Definition of dispersion parameter for quasipoisson family

Question: I try to model quasi-poisson family in bugs language, to handle overdispersion. According to Introduction to WinBUGS for ecologists, this is done by:
$log(\lambda_i) = f(x_i) + \epsilon_i$
$N_i \sim Poiss(\lambda_i)$
where $\epsilon_i$ does the overdispersion. This is equivalent to scenario 8 in Lindén & Mäntyniemi 2011:
$log(\lambda_i) = f(x_i)$
$N_i \sim Poiss(\lambda_i \theta_i)$
However, how do I get the "dispersion parameter for quasipoisson family", as reported by GLM when using quasipoisson family?
> summary(glm.fit.with.OD)
Call:
glm(formula = C.OD ~ x, family = quasipoisson)
[...]
(Dispersion parameter for quasipoisson family taken to be 1.470301)

Here I include full reproducible code, taken from Introduction to WinBUGS for ecologists, see chapter 14.1 (slightly modified):
set.seed(123)

### 14.1. Overdispersion

### 14.1.2. Data generation
n.site <- 10
x <- gl(n = 2, k = n.site, labels = c("grassland", "arable"))
eps <- rnorm(2*n.site, mean = 0, sd = 0.5)# Normal random effect
lambda.OD <- exp(0.69 +(0.92*(as.numeric(x)-1) + eps) )
lambda.Poisson <- exp(0.69 +(0.92*(as.numeric(x)-1)) ) # For comparison

C.OD <- rpois(n = 2*n.site, lambda = lambda.OD)
C.Poisson <- rpois(n = 2*n.site, lambda = lambda.Poisson)

par(mfrow = c(1,2))
boxplot(C.OD ~ x, col = "grey", xlab = "Land-use", main = "With OD",
ylab = "Hare count", las = 1, ylim = c(0, max(C.OD)))
boxplot(C.Poisson ~ x, col = "grey", xlab = "Land-use", main = "Without OD",
ylab = "Hare count", las = 1, ylim = c(0, max(C.OD)) )

### 14.1.3. Analysis using R
glm.fit.no.OD <- glm(C.OD ~ x, family = poisson)
glm.fit.with.OD <- glm(C.OD ~ x, family = quasipoisson)
summary(glm.fit.no.OD)
summary(glm.fit.with.OD)
anova(glm.fit.no.OD, test = "Chisq")
anova(glm.fit.with.OD, test = "F")

### 14.1.4. Analysis using WinBUGS
# Define model
sink("Poisson.OD.t.test.txt")
cat("
model {
# Priors
 alpha ~ dnorm(0,0.001)
 beta ~ dnorm(0,0.001)
 sigma ~ dunif(0, 10)
 tau <- 1 / (sigma * sigma)
 maybe_overdisp <- mean(exp_eps[])

# Likelihood
 for (i in 1:n) {
    C.OD[i] ~ dpois(lambda[i])
    log(lambda[i]) <- alpha + beta *x[i] + eps[i]
    eps[i] ~ dnorm(0, tau)
    exp_eps[i] <- exp(eps[i])
 }
}
",fill=TRUE)
sink()

# Bundle data
win.data <- list(C.OD = C.OD, x = as.numeric(x)-1, n = length(x))

# Inits function
inits <- function(){ list(alpha=rlnorm(1), beta=rlnorm(1), sigma = rlnorm(1))}

# Parameters to estimate
params <- c("lambda","alpha", "beta", "sigma", "maybe_overdisp")

# MCMC settings
nc <- 3     # Number of chains
ni <- 30000     # Number of draws from posterior per chain
nb <- 10000     # Number of draws to discard as burn-in
nt <- 5     # Thinning rate

# Start Gibbs sampling
out <- bugs(data=win.data, inits=inits, parameters.to.save=params,
model.file="Poisson.OD.t.test.txt", n.thin=nt, n.chains=nc,
n.burnin=nb, n.iter=ni, debug = TRUE)

print(out, dig = 3)

Here is the output of the glm() in R:
> summary(glm.fit.with.OD)

Call:
glm(formula = C.OD ~ x, family = quasipoisson)

Deviance Residuals:
    Min       1Q   Median       3Q      Max
-2.2945  -0.5905  -0.4348   1.0798   1.8159

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)   0.4055     0.3131   1.295  0.21166
xarable       1.2622     0.3546   3.559  0.00224 **
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for quasipoisson family taken to be 1.470301)

    Null deviance: 51.032  on 19  degrees of freedom
Residual deviance: 28.524  on 18  degrees of freedom
AIC: NA

Number of Fisher Scoring iterations: 5

And here is the output of the jags model (using more iterations than in the above code):
> print(out, dig = 3)
Inference for Bugs model at "Poisson.OD.t.test.txt", fit using jags,
 3 chains, each with 300000 iterations (first 100000 discarded), n.thin = 5
 n.sims = 120000 iterations saved
               mu.vect sd.vect   2.5%    25%    50%    75%  97.5%  Rhat  n.eff
alpha            0.275   0.324 -0.415  0.073  0.291  0.498  0.861 1.001  23000
beta             1.289   0.385  0.547  1.035  1.281  1.534  2.071 1.001  41000
lambda[1]        1.163   0.586  0.263  0.740  1.092  1.496  2.512 1.001  24000
lambda[2]        1.368   0.654  0.398  0.914  1.273  1.700  2.934 1.001  27000
lambda[3]        2.173   1.081  0.818  1.429  1.919  2.638  4.976 1.001 120000
lambda[4]        1.367   0.654  0.397  0.912  1.273  1.701  2.927 1.001  26000
lambda[5]        1.370   0.655  0.401  0.914  1.275  1.702  2.929 1.001  20000
lambda[6]        1.602   0.759  0.545  1.086  1.464  1.954  3.503 1.001  24000
lambda[7]        1.365   0.656  0.399  0.909  1.268  1.697  2.941 1.001  34000
lambda[8]        1.366   0.653  0.394  0.912  1.272  1.701  2.919 1.001  43000
lambda[9]        1.368   0.654  0.400  0.916  1.270  1.700  2.934 1.001  16000
lambda[10]       1.872   0.904  0.690  1.260  1.679  2.261  4.198 1.001  84000
lambda[11]       4.608   1.548  1.978  3.525  4.494  5.521  8.032 1.001  54000
lambda[12]       5.058   1.628  2.340  3.937  4.903  5.969  8.818 1.001  52000
lambda[13]       6.544   2.064  3.426  5.091  6.189  7.649 11.521 1.001 120000
lambda[14]       4.170   1.492  1.610  3.095  4.078  5.116  7.355 1.001  67000
lambda[15]       4.613   1.554  1.974  3.524  4.499  5.528  8.073 1.001 120000
lambda[16]       7.066   2.258  3.759  5.439  6.675  8.293 12.477 1.001  49000
lambda[17]       7.615   2.462  4.054  5.802  7.190  9.003 13.472 1.001  42000
lambda[18]       3.385   1.458  0.956  2.281  3.264  4.385  6.403 1.001  61000
lambda[19]       6.538   2.066  3.431  5.089  6.185  7.643 11.505 1.001 120000
lambda[20]       3.385   1.459  0.957  2.279  3.260  4.384  6.399 1.001  95000
maybe_overdisp   1.121   0.179  0.898  1.006  1.076  1.189  1.577 1.001 120000
sigma            0.465   0.236  0.051  0.301  0.449  0.606  0.983 1.001  27000
deviance        74.767   5.985 64.292 70.311 74.343 79.042 86.528 1.001 120000

For each parameter, n.eff is a crude measure of effective sample size,
and Rhat is the potential scale reduction factor (at convergence, Rhat=1).

DIC info (using the rule, pD = var(deviance)/2)
pD = 17.9 and DIC = 92.7
DIC is an estimate of expected predictive error (lower deviance is better).

Edit 2
Modified model:
model {
# Priors
 alpha ~ dnorm(0,0.001)
 beta ~ dnorm(0,0.001)
 sigma ~ dunif(0, 10)
 tau <- 1 / (sigma * sigma)
 maybe_overdisp <- mean(exp_eps[])

# co mi poradili na stats.SE
sigma2 <- sigma*sigma
kappa <- exp(alpha + beta);
mean.x <- exp(alpha + 0.5*sigma2);
vari <- kappa*exp(sigma2/2)+kappa*kappa*exp(2*sigma2) - kappa*kappa*exp(sigma2)
DI <- vari/mean.x

# Likelihood
 for (i in 1:n) {
    C.OD[i] ~ dpois(lambda[i])
    log(lambda[i]) <- alpha + beta *x[i] + eps[i]
    eps[i] ~ dnorm(0, tau)
    exp_eps[i] <- exp(eps[i])
 }
}

output:
> print(out, dig = 6)
Inference for Bugs model at "Poisson.OD.t.test.txt", fit using jags,
 3 chains, each with 30000 iterations (first 10000 discarded), n.thin = 5
 n.sims = 12000 iterations saved
                 mu.vect    sd.vect      2.5%       25%       50%       75%     97.5%     Rhat n.eff
DI             20.691012 574.969428  2.748532  4.908448  7.479553 13.014255 64.410436 1.001834  2100
alpha           0.276339   0.319067 -0.410506  0.081158  0.293487  0.491261  0.859875 1.001180  6500
beta            1.285987   0.378753  0.556607  1.042379  1.276188  1.523705  2.054021 1.001084  9500
lambda[1]       1.173864   0.584403  0.268459  0.749624  1.106648  1.508932  2.499185 1.001344  4300
lambda[2]       1.364399   0.653852  0.395182  0.913774  1.272952  1.693450  2.944849 1.001782  2200
lambda[3]       2.148461   1.056564  0.814731  1.422458  1.892689  2.620223  4.912488 1.001393  3900
lambda[4]       1.373973   0.651289  0.404761  0.922161  1.283126  1.707821  2.930640 1.001074 10000
lambda[5]       1.364438   0.646131  0.397013  0.915541  1.271812  1.700321  2.908050 1.000922 12000
lambda[6]       1.596684   0.737480  0.562846  1.098588  1.463223  1.931152  3.472518 1.001139  7500
lambda[7]       1.372055   0.667968  0.394750  0.912321  1.270109  1.702314  3.030247 1.001004 12000
lambda[8]       1.368805   0.641905  0.393292  0.926187  1.281149  1.694738  2.933341 1.001159  7000
lambda[9]       1.367516   0.644055  0.410916  0.914202  1.279055  1.693786  2.892084 1.001237  5500
lambda[10]      1.874077   0.903156  0.706316  1.261625  1.683053  2.256230  4.224203 1.001380  4000
lambda[11]      4.604620   1.551257  1.983965  3.515142  4.484644  5.530132  8.040010 1.000890 12000
lambda[12]      5.052838   1.631220  2.325490  3.949769  4.904707  5.942355  8.784829 1.000883 12000
lambda[13]      6.506786   2.050675  3.424231  5.043272  6.159473  7.621714 11.341993 1.000896 12000
lambda[14]      4.168782   1.468719  1.617240  3.104178  4.099795  5.114893  7.324785 1.002270  1400
lambda[15]      4.588128   1.529048  1.986595  3.537436  4.479550  5.476045  7.997842 1.000895 12000
lambda[16]      7.035670   2.235785  3.776619  5.428774  6.617842  8.235651 12.389102 1.001082  9600
lambda[17]      7.586794   2.444835  4.078003  5.780102  7.145878  8.986080 13.364148 1.000973 12000
lambda[18]      3.413945   1.459583  0.955955  2.306502  3.321237  4.407808  6.427175 1.002377  1300
lambda[19]      6.559620   2.077231  3.418885  5.098825  6.196538  7.664223 11.574183 1.001324  4400
lambda[20]      3.391437   1.459840  0.949251  2.262276  3.281995  4.407545  6.371617 1.001482  3300
maybe_overdisp  1.119677   0.178304  0.900895  1.006214  1.073253  1.185895  1.565368 1.002841  1000
sigma           0.458185   0.235224  0.048157  0.294464  0.441186  0.597933  0.972298 1.009139   960
deviance       74.818941   5.985537 64.100886 70.435067 74.417487 79.115472 86.443865 1.001312  4600

For each parameter, n.eff is a crude measure of effective sample size,
and Rhat is the potential scale reduction factor (at convergence, Rhat=1).

DIC info (using the rule, pD = var(deviance)/2)
pD = 17.9 and DIC = 92.7
DIC is an estimate of expected predictive error (lower deviance is better).

Answer: The dispersion parameter in the quasi-Poisson model
Let us first see how the dispersion parameter is calculated in the model using quasi-Poisson likelihood. One assumption in Poisson regression is that the conditional variance and the conditional mean of the response $Y$ are the same:
$$
V(Y_{i}|\eta_{i})=E(Y_{i}|\eta_{i})=\mu_{i}
$$
where $\eta_{i}$ is the linear predictor. Sometimes we observe that the variance is greater than the mean which is called overdispersion. The quasi-Poisson likelihood model is a simple remedy for overdispersed count data because it introduces a dispersion parameter ($\phi$) into the Poisson model, so that the conditional variance of the response is now a linear function of the mean:
$$
V(Y_{i}|\eta_{i})=\phi\mu_{i}
$$
If $\phi>1$, the conditional variance increases more rapidly than its mean. Now, $\phi$ is estimated as:
$$
\widehat{\phi}=\frac{1}{n-k}\sum\frac{(Y_{i}-\hat{\mu_{i}})^2}{\hat{\mu_{i}}}
$$
where $n$ is the sample size, $k$ is the number of estimated parameters (including the intercept) and $\widehat{\mu_{i}}=g^{-1}(\widehat{\eta_{i}})$ is the fitted expectation of $Y_{i}$ ($g^{-1}$ is the inverse link function). Note that the formulation above is simply the Pearson $\chi^{2}$ divided by the residual degrees of freedom: $\widehat{\phi}=\chi^{2}/df$. Let's estimate the dispersion parameter in your example in R:
n <- 20
k <- 2

1/(n-k)*sum((C.OD-fitted(glm.fit.no.OD))^2/fitted(glm.fit.no.OD))
[1] 1.4703

# Via Pearson residuals

sum(residuals(glm.fit.no.OD, type="pearson")^2)/df.residual(glm.fit.no.OD)
[1] 1.4703

The estimated dispersion parameter is $1.47$. This is the same as given by the model output from the quasi-Poisson model:
summary(glm.fit.with.OD)
[...]
(Dispersion parameter for quasipoisson family taken to be 1.470301)
[...]

The dispersion parameter in the negative binomial model
There are several approaches to model count data with overdispersion. One very popular approach negative binomial regression. The conditional variance-mean relationship in the negative binomial model is:
$$
V(Y_{i}|\eta_{i})=\mu_{i}+\mu_{i}^{2}/\phi=\mu_{i}(1+\mu_{i}/\phi)
$$
where the second term provides the overdispersion where smaller $\phi$s denote stronger overdispersion. As $\phi\rightarrow\infty$, the variance approaches the mean and the distribution approaches the Poisson distribution as the second term gets very small. Sometimes, $1/\phi$ is used instead and if $1/\phi\rightarrow 0$, the distribution approaches the Poisson. In contrast to the quasi-Poisson model, the conditional variance is now a quadratic function of the mean (see this paper for more information). Note that the dispersion parameter is the multiplicative factor $1+\mu_{i}\phi$, which depends on $\mu_{i}$ (in contrast to the quasi-Poisson model).
We can fit a negative binomial regression using glm.nb from the MASS package:
library(MASS)

glm.negbin <- glm.nb(C.OD ~ x)
summary(glm.negbin)

Coefficients:
            Estimate Std. Error z value Pr(>|z|)
(Intercept)   0.4055     0.2847   1.424 0.154360
xarable       1.2622     0.3381   3.734 0.000189 ***

(Dispersion parameter for Negative Binomial(6.9569) family taken to be 1)

              Theta:  6.96
          Std. Err.:  6.74

The estimate for $\phi$ is $6.96$ (it's called theta in the output). The reciprocal of $\phi$ is sometimes used and is $1/6.96\approx0.144$ in this case. Because $1/\phi>0$ we have overdispersion.
Other methods to model overdispersed count data
I will outline three approaches here which can be found in the book Bayesian Modeling Using WinBUGS by Ioannis Ntzoufras (section 8.31, pages 283-286; section 9.2.3, pages 315-318).

Estimating overdispersion using a negative binomial model
Our model is:
$$
\begin{align}
Y_{i}             &\sim \text{NB}(\pi_{i},r_{i}) \\
\pi_{i}           &= \frac{r_{i}}{r_{i}+\lambda_{i}} \\
\log(\lambda_{i}) &= \beta_{0} + \sum_{j=1}^{p}\beta_{j}X_{ij}
\end{align}
$$
We have two groups, so the two lambdas are $\lambda_{1}=e^{\beta_{0}}, \lambda_{2}=e^{\beta_{0}+\beta_{1}}$. The dispersion index is given by $\text{DI}=1+\lambda/r$. If $\text{DI}>0$ we have overdispersion. Here is our WinBUGS/JAGS model (I used JAGS to sample from the posterior):
library(rjags)
library(R2jags)

sink("Negbin_model.txt")
cat("
model {

 for (i in 1:n) {

 y[i] ~ dnegbin(p.ind[i], r.ind[i])
 p.ind[i] <- r.ind[i]/(r.ind[i] + lambda.ind[i])
 log(lambda.ind[i]) <- beta[1] + beta[2]*x[i]
 r.ind[i] <- r[ x[i] + 1 ]

 }

lambda[1] <- exp(beta[1])
lambda[2] <- exp(beta[1] + beta[2])

beta1 <- exp(beta[2])

for(j in 1:2) {

logr.cont[j] ~ dunif(0, 10)
log(r.cont[j]) <- logr.cont[j]
r[j] <- round(r.cont[j])

#r[j] ~dgamma(0.001, 0.001)

beta[j] ~ dnorm(0.0, 0.0001)

DI[j] <- (1 + lambda[j])/r[j]
vari[j]  <- lambda[j]*DI[j]
p[j] <- r[j]/(r[j]+lambda[j])

}
}
",fill=TRUE)
sink()

# Bundle data
win.data <- list(y = C.OD, x = as.numeric(x)-1, n = length(x))

# Inits function
inits <- function(){ list(beta=rlnorm(2), logr.cont=runif(2, 0,10))}

params <- c("beta", "lambda", "r", "DI", "p", "vari")

# MCMC settings
nc <- 3     # Number of chains
ni <- 50000     # Number of draws from posterior per chain
nb <- 10000     # Number of draws to discard as burn-in
nt <- 1     # Thinning rate

# Start Gibbs sampling
#out <- bugs(data=win.data, inits=inits, parameters.to.save=params,
#            model.file="Negbin_model.txt", n.thin=nt, n.chains=nc,
#            n.burnin=nb, n.iter=ni, debug = TRUE, program="OpenBUGS")

#print(out, dig = 3)

out <- jags(
  data = win.data,
  parameters.to.save = params,
  model.file = "Negbin_model.txt",
  n.chains = nc,
  n.iter = ni,
  n.burnin = nb,
  n.thin=nt,
  inits=inits,
  progress.bar="text")

#out <- update(out, n.iter=50000)

out

The output is:
Inference for Bugs model at "Negbin_model.txt", fit using jags,
 3 chains, each with 50000 iterations (first 10000 discarded)
 n.sims = 120000 iterations saved
           mu.vect  sd.vect   2.5%    25%     50%      75%     97.5%  Rhat  n.eff
DI[1]        0.141    0.347  0.000  0.001   0.010    0.098     1.166 1.001  59000
DI[2]        1.025    1.387  0.000  0.032   0.516    1.520     4.486 1.001  67000
beta[1]      0.378    0.269 -0.176  0.203   0.386    0.562     0.880 1.001  35000
beta[2]      1.287    0.326  0.664  1.066   1.280    1.502     1.950 1.001  22000
lambda[1]    1.512    0.404  0.839  1.225   1.471    1.755     2.412 1.001  35000
lambda[2]    5.381    1.035  3.657  4.704   5.285    5.933     7.700 1.001  27000
p[1]         0.942    0.111  0.585  0.945   0.994    0.999     1.000 1.001 120000
p[2]         0.682    0.271  0.205  0.441   0.699    0.973     1.000 1.001  33000
r[1]      2452.090 4589.758  2.000 25.000 240.000 2326.000 17602.050 1.001  59000
r[2]      1143.373 3351.097  2.000  4.000  12.000  193.000 13614.000 1.001  80000
vari[1]      0.232    0.696  0.000  0.002   0.015    0.143     1.923 1.001  57000
vari[2]      5.964   10.345  0.002  0.170   2.629    7.883    30.075 1.001  56000
deviance    83.371    2.319 80.238 81.701  82.964   84.510    89.135 1.001 120000

The posterior median dispersion index for the group "arable" (DI[2]) is larger than zero indicating overdispersion. On the other hand, the dispersion index for the group "grassland" (DI[1]) is only slightly larger than zero. Let's look at the posterior density of the dispersion index for the group "arable" and calculate the 95% Highest Posterior Density intervals (HDP) for the dispersion indices:
library(ggplot2)
library(runjags)

jagsfit.matrix <- rbind(as.matrix(as.mcmc(out)[[1]]),
                        as.matrix(as.mcmc(out)[[2]]),
                        as.matrix(as.mcmc(out)[[3]]))

name <- "DI[2]"

vect <- jagsfit.matrix[, name]

vect.plot <- vect[vect<=20]

mcmc.combined <- combine.mcmc(as.mcmc(out))

hpd.ints <- HPDinterval(mcmc.combined, prob=0.95)
hpd.ints

#hdr(mcmc.combined[,"DI"], prob=95, h=hdrbw(mcmc.combined[,"DI"], gridsize=1000000, HDRlevel=0.95), nn=5000)

plot.frame <- data.frame(dispersion=vect.plot)

ggplot(plot.frame, aes(x=vect.plot)) +
  geom_density(alpha=0.5, fill="#1B4F97", color="#1B4F97") +
  geom_vline(xintercept = c(0, 3.561465e+00), alpha=0.6, size=1) +
  xlim(c(0,20)) +
  ylab("Density") +
  xlab("Dispersion index") +
  ggtitle("Posterior distribution of the dispersion index for the group \"arable\"") +
  theme(axis.title.y =element_text(vjust=0.4, size=20, angle=90)) +
  theme(axis.title.x =element_text(vjust=0, size=20, angle=0)) +
  theme(axis.text.x =element_text(size=15, colour = "black")) +
  theme(axis.text.y =element_text(size=17, colour = "black")) +
  theme(panel.background =  element_rect(fill = "grey85", colour = NA),
        panel.grid.major =  element_line(colour = "white"),
        panel.grid.minor =  element_line(colour = "grey90", size = 0.25))

The 95% HDP for the dispersion parameter for the group "arable" ranges from $0$ to $3.56$ (marked by the vertical grey lines in the graphic above).

Estimating overdispersion using a Poisson-log-normal model
First, let's define our model:
$$
\begin{align}
Y_{i}             &\sim \text{Poisson}(\lambda_{i}) \\
\log(\lambda_{i}) &= \mu_{i}+b_{i} \\
\mu_{i}           &= \beta_{0} + \sum_{j=1}^{p}\beta_{j}X_{ij} \\
b_{i}             &\sim \mathcal{N}(0, \sigma^{2})
\end{align}
$$
The mean and the variance then are
$$
\begin{align}
E(Y|\lambda,\sigma_{b}^{2})  &= \lambda e^{\sigma_{b}^{2}/2} \\
V(Y|\lambda, \sigma_{b}^{2}) &= \lambda e^{\sigma_{b}^{2}/2} + \lambda^{2}e^{2\sigma_{b}^{2}} - \lambda^{2}e^{\sigma_{b}^{2}}
\end{align}
$$
So we simply add $b_{i}$ to the linear predictor to take the overdispersion into account.
We can build the dispersion index (DI) into the model and estimate it for each group separately:
sink("Poisson.OD.t.test.txt")
cat("
model {
# Priors
 alpha ~ dnorm(0,0.001)
 beta ~ dnorm(0,0.001)
 sigma ~ dunif(0, 10)
 sigma2 <- sigma*sigma
 tau <- 1 / sigma2

 maybe_overdisp <- mean(exp_eps[])

kappa[1] <- exp(alpha)
kappa[2] <- exp(alpha + beta)
mean.x[1] <- exp(alpha + 0.5*sigma2)
mean.x[2] <- exp(alpha + beta + 0.5*sigma2)
vari[1] <- kappa[1]*exp(sigma2/2)+kappa[1]*kappa[1]*exp(2*sigma2) -
kappa[1]*kappa[1]*exp(sigma2)
vari[2] <- kappa[2]*exp(sigma2/2)+kappa[2]*kappa[2]*exp(2*sigma2) -
kappa[2]*kappa[2]*exp(sigma2)

DI[1] <- vari[1]/mean.x[1]
DI[2] <- vari[2]/mean.x[2]

# Likelihood
 for (i in 1:n) {

    C.OD[i] ~ dpois(lambda[i])
    log(lambda[i]) <- alpha + beta*x[i] + eps[i]
    eps[i] ~ dnorm(0, tau)
    exp_eps[i] <- exp(eps[i])
    #di.index.ind[i] <- 1 + exp(eps[i])*(es-1)*sqrt(es)

 }
}
",fill=TRUE)
sink()

# Bundle data
win.data <- list(C.OD = C.OD, x = as.numeric(x)-1, n = length(x))

# Inits function
inits <- function(){ list(alpha=rlnorm(1), beta=rlnorm(1), sigma=rlnorm(1))}

# Parameters to estimate
params <- c("alpha", "beta", "sigma", "sigma2",
            "maybe_overdisp", "DI", "mean.x", "vari", "kappa")

# MCMC settings
nc <- 3         # Number of chains
ni <- 50000     # Number of draws from posterior per chain
nb <- 10000     # Number of draws to discard as burn-in
nt <- 1         # Thinning rate

# Start Gibbs sampling
out2 <- jags(
  data = win.data,
  parameters.to.save = params,
  model.file = "Poisson.OD.t.test.txt",
  n.chains = nc,
  n.iter = ni,
  n.burnin = nb,
  n.thin=nt,
  inits=inits,
  progress.bar="text")

The output is
Inference for Bugs model at "Poisson.OD.t.test.txt", fit using jags,
 3 chains, each with 50000 iterations (first 10000 discarded)
 n.sims = 120000 iterations saved
               mu.vect  sd.vect   2.5%    25%    50%    75%  97.5%  Rhat  n.eff
DI[1]            1.746   16.499  1.004  1.132  1.312  1.666  4.054 1.001 100000
DI[2]            3.573   22.604  1.013  1.486  2.133  3.404 12.319 1.001   8500
alpha            0.273    0.324 -0.416  0.069  0.293  0.496  0.857 1.001   4800
beta             1.294    0.384  0.559  1.042  1.286  1.538  2.076 1.001   7400
kappa[1]         1.382    0.436  0.660  1.072  1.340  1.642  2.355 1.001   4800
kappa[2]         4.911    1.076  2.927  4.199  4.868  5.560  7.167 1.001  23000
maybe_overdisp   1.119    0.176  0.900  1.006  1.075  1.187  1.570 1.001  49000
mean.x[1]        1.581    0.565  0.794  1.220  1.506  1.847  2.802 1.001   7000
mean.x[2]        5.632    1.505  3.591  4.728  5.413  6.225  9.022 1.001  31000
sigma            0.461    0.232  0.050  0.300  0.442  0.601  0.970 1.009   1300
sigma2           0.266    0.260  0.002  0.090  0.195  0.361  0.940 1.009   1300
vari[1]          6.195  846.592  0.925  1.501  1.986  2.844  9.543 1.001  45000
vari[2]         32.314 1013.170  4.830  7.456 11.123 19.352 98.875 1.001  11000
deviance        74.771    5.949 64.349 70.338 74.364 78.967 86.505 1.001   5100

First note the posterior medians of the groups means.x are close to the observed means of the data ($1.51$ vs. $1.5$ and $5.41$ vs. $5.3$). The posterior variances vari for the groups are also close to the observed variances ($1.99$ vs. $1.39$ and $11.12$ vs. $10.68$). Importantly, the posterior median of the estimate $\hat{\beta_{1}}$ (beta) ($1.286$) is very close to the estimate calculated by glm using family="quasipoisson" which was $1.262$. The posterior mean and median of the dispersion index (DI) is $1.75$ and $1.31$ for the group "grassland" and $3.57$ and $2.13$ for the group "arable". It seems that the data for the group "arable" is more overdispersed than the group "grassland". The dispersion parameter estimated by glm with quasi-Poisson likelihood was around $1.47$ which is in between the posterior medians of the two dispersion indices, so our estimations look reasonable. Let's look at the posterior density of the dispersion index for the group "arable" and calculate the 95% Highest Posterior Density intervals (HDP) for the dispersion indices:
library(ggplot2)
library(runjags)

jagsfit.matrix <- rbind(as.matrix(as.mcmc(out2)[[1]]),
                        as.matrix(as.mcmc(out2)[[2]]),
                        as.matrix(as.mcmc(out2)[[3]]))

name <- "DI[2]"

vect <- jagsfit.matrix[, name]

vect.plot <- vect[vect<=20]

mcmc.combined <- combine.mcmc(as.mcmc(out2))

hpd.ints <- HPDinterval(mcmc.combined, prob=0.95)
hpd.ints

                       lower      upper
DI[1]           1.000000e+00  3.0691670
DI[2]           1.000001e+00  8.5232449
alpha          -3.729040e-01  0.8911411
beta            5.598711e-01  2.0766436
deviance        6.397199e+01 86.0493853
kappa[1]        5.908833e-01  2.2448459
kappa[2]        2.821622e+00  7.0389753
maybe_overdisp  8.565536e-01  1.4860521
mean.x[1]       6.856225e-01  2.5876715
mean.x[2]       3.300125e+00  8.3619700
sigma           4.044946e-04  0.8686939
sigma2          9.929906e-08  0.7545791
vari[1]         6.201473e-01  6.6375401
vari[2]         3.416068e+00 61.4973745
attr(,"Probability")
[1] 0.95

plot.frame <- data.frame(dispersion=vect.plot)

ggplot(plot.frame, aes(x=vect.plot)) +
  geom_density(alpha=0.5, fill="#1B4F97", color="#1B4F97") +
  geom_vline(xintercept = c(1, 8.5232449), alpha=0.6, size=1) +
  xlim(c(0,20)) +
  ylab("Density") +
  xlab("Dispersion index") +
  ggtitle("Posterior distribution of the dispersion index for the group \"arable\"") +
  theme(axis.title.y =element_text(vjust=0.4, size=20, angle=90)) +
  theme(axis.title.x =element_text(vjust=0, size=20, angle=0)) +
  theme(axis.text.x =element_text(size=15, colour = "black")) +
  theme(axis.text.y =element_text(size=17, colour = "black")) +
  theme(panel.background =  element_rect(fill = "grey85", colour = NA),
        panel.grid.major =  element_line(colour = "white"),
        panel.grid.minor =  element_line(colour = "grey90", size = 0.25))

The 95% HDP for the dispersion parameter for the group "arable" ranges from $1$ to $8.52$ (marked by the vertical grey lines in the graphic above). It is important to note that we used a uniform prior for the standard deviation of $b_{i}$. There are other possibilities and the posterior distribution of the dispersion index can vary depending on the prior. Other priors include but are not limited to: uniform on the variance ($\sigma^{2}$), half-normal prior on $\sigma$ or $\sigma^{2}$, half-Cauchy on $\sigma$ and others.

Estimating overdispersion using a Poisson-gamma model
We can also model the data using a Poisson-gamma model:
$$
\begin{align}
Y_{i}             &\sim \text{Poisson}(\lambda_{i}u_{i}) \\
u_{i}             &\sim \text{Gamma}(r_{i}, r_{i})
\end{align}
$$
The WinBUGS model (or OpenBUGS, JAGS) is as follows:
sink("gamma_mix.txt")
cat("
model{

for(i in 1:n){

y[i] ~ dpois(mu.ind[i])
mu.ind[i] <- mu[i]*u[i]
log(mu[i]) <- beta[1]+beta[2]*x[i]
u[i] ~ dgamma(r[x[i]+1], r[x[i]+1])

}

mean.u <- mean(u[])

lambda[1] <- exp(beta[1])
lambda[2] <- exp(beta[1] + beta[2])

for (j in 1:2){

r[j] ~ dgamma(0.001, 0.001)
beta[j]  ~ dnorm(0.0, 0.0001)
DI[j] <- (1+lambda[j]/r[j])
vari[j] <- lambda[j]*DI[j]
p[j] <- r[j]/(r[j]+lambda[j])
}
}
",fill=TRUE)
sink()

# Bundle data
win.data <- list(y = C.OD, x = as.numeric(x)-1, n = length(x))

# Inits function
inits <- function(){ list(beta=rlnorm(2), r=rlnorm(2))}

# Parameters to estimate
params <- c("beta", "lambda", "r", "DI", "mean.x", "vari", "tau", "s", "s2", "mean.u")

# MCMC settings
nc <- 3     # Number of chains
ni <- 50000     # Number of draws from posterior per chain
nb <- 10000     # Number of draws to discard as burn-in
nt <- 1     # Thinning rate

out <- jags(
  data = win.data,
  parameters.to.save = params,
  model.file = "gamma_mix.txt",
  n.chains = nc,
  n.iter = ni,
  n.burnin = nb,
  n.thin=nt,
  inits=inits,
  progress.bar="text")

The output is
Inference for Bugs model at "gamma_mix.txt", fit using jags,
 3 chains, each with 50000 iterations (first 10000 discarded)
 n.sims = 120000 iterations saved
          mu.vect sd.vect   2.5%    25%    50%     75%    97.5%  Rhat n.eff
DI[1]       1.180   0.492  1.001  1.008  1.038   1.163    2.196 1.002  5600
DI[2]       2.280   1.734  1.017  1.248  1.774   2.665    6.580 1.001  8500
beta[1]     0.375   0.286 -0.206  0.189  0.383   0.567    0.909 1.002  3100
beta[2]     1.292   0.352  0.612  1.058  1.287   1.523    1.995 1.002  3500
lambda[1]   1.515   0.445  0.814  1.209  1.467   1.763    2.481 1.002  3100
lambda[2]   5.414   1.180  3.524  4.649  5.287   6.009    8.087 1.001 12000
mean.u      1.001   0.093  0.820  0.952  0.998   1.045    1.207 1.001 34000
r[1]      184.429 373.385  1.358  8.872 37.503 172.345 1378.710 1.002  2100
r[2]       37.280 103.862  1.076  3.162  6.733  20.971  303.187 1.001 28000
vari[1]     1.861   2.106  0.863  1.294  1.600   1.998    4.259 1.001 27000
vari[2]    13.170  17.311  4.585  6.442  9.057  14.297   45.626 1.001  6500
deviance   76.089   5.763 65.979 71.679 75.802  80.428   87.121 1.001 16000

Again, the posterior means (lambda) and variances (vari) are very close to the observed ones. The estimate for the coefficient beta[2] is again practically identical to the estimates we've got using the Poisson-log-normal approach (i.e. $\approx 1.29$). The dispersion indices for the two groups are about $1.04$ for "grassland" and $1.77$ for "arable". These are very close to the observed overdispersion which are $0.926$ for "grassland" and $2.01$ for "arable", respectively. The HDPs and the posterior density of the dispersion index for the group "arable" is
jagsfit.matrix <- rbind(as.matrix(as.mcmc(out)[[1]]),
                        as.matrix(as.mcmc(out)[[2]]),
                        as.matrix(as.mcmc(out)[[3]]))

name <- "DI[2]"

vect <- jagsfit.matrix[, name]

vect.plot <- vect[vect<=20]

mcmc.combined <- combine.mcmc(as.mcmc(out))

hpd.ints <- HPDinterval(mcmc.combined, prob=0.95)
hpd.ints
                   lower       upper
DI[1]      1.0002195   1.7847379
DI[2]      1.0022835   5.1658954
beta[1]   -0.1984061   0.9146267
beta[2]    0.5995819   1.9807803
deviance  65.7749045  86.8262578
lambda[1]  0.7592323   2.3828823
lambda[2]  3.2764333   7.6725830
mean.u     0.8060325   1.1907674
r[1]       0.1508372 900.3718394
r[2]       0.2372253 193.6838708
vari[1]    0.6524941   3.2896264
vari[2]    3.5796354  33.4126294
attr(,"Probability")
[1] 0.95

plot.frame <- data.frame(dispersion=vect.plot)

ggplot(plot.frame, aes(x=vect.plot)) +
  geom_density(alpha=0.5, fill="#1B4F97", color="#1B4F97") +
  geom_vline(xintercept = c(1, 5.1658954), alpha=0.6, size=1) +
  xlim(c(0,20)) +
  ylab("Density") +
  xlab("Dispersion index") +
  ggtitle("Posterior distribution of the dispersion index for the group \"arable\"") +
  theme(axis.title.y =element_text(vjust=0.4, size=20, angle=90)) +
  theme(axis.title.x =element_text(vjust=0, size=20, angle=0)) +
  theme(axis.text.x =element_text(size=15, colour = "black")) +
  theme(axis.text.y =element_text(size=17, colour = "black")) +
  theme(panel.background =  element_rect(fill = "grey85", colour = NA),
        panel.grid.major =  element_line(colour = "white"),
        panel.grid.minor =  element_line(colour = "grey90", size = 0.25))

The 95% HDP for the dispersion parameter for the group "arable" ranges from $1$ to $5.17$ (marked by the vertical grey lines in the graphic above). The interval is smaller than the interval obtained by the Poisson-log-normal approach, which was ranging from $1$ to $8.52$.

Calculate dispersion parameter as in the quasi-Poisson model
The dispersion parameter in the quasi-Poisson GLM is estiamted as follows:
$$
\widehat{\mathrm{DI}}=\frac{1}{n-k}\sum_{i}^{n}r_{P,i}^{2}
$$
where $n$ is the sample size, $k$ the number of estimated parameters and $r_{P,i}$ are the Pearson residuals:
$$
r_{P}=\frac{y-\mu}{\sqrt{\mu}}
$$
The dispersion index can be estimated using normal Poisson regression in WinBUGS:
sink("poisson_dispersion.txt")
cat("
    model{

for(i in 1:n){
y[i] ~ dpois(mu[i])
log(mu[i]) <- beta[1] + beta[2]*x[i]
fitted.y[i] <- exp(beta[1]+beta[2]*x[i])
 }

DI.index <- 1/(n-2)*sum(pow((y[]-fitted.y[]),2)/fitted.y[])

for (j in 1:2){

beta[j] ~ dnorm(0.0, 0.0001)
}
}
",fill=TRUE)
sink()

# Bundle data
win.data <- list(y = C.OD, x = as.numeric(x)-1, n = length(x))

# Inits function
inits <- function(){ list(beta=rlnorm(2))}

# Parameters to estimate
params <- c("beta", "DI.index")

# MCMC settings
nc <- 3     # Number of chains
ni <- 50000     # Number of draws from posterior per chain
nb <- 10000     # Number of draws to discard as burn-in
nt <- 1     # Thinning rate

out <- jags(
  data = win.data,
  parameters.to.save = params,
  model.file = "poisson_lognormal.txt",
  n.chains = nc,
  n.iter = ni,
  n.burnin = nb,
  n.thin=nt,
  inits=inits,
  progress.bar="text")

out

         mu.vect sd.vect   2.5%    25%    50%    75%  97.5%  Rhat n.eff
DI.index   1.637   0.272  1.354  1.441  1.560  1.750  2.359 1.001  4500
beta[1]    0.375   0.261 -0.170  0.208  0.388  0.556  0.855 1.002  2700
beta[2]    1.282   0.294  0.729  1.080  1.273  1.474  1.886 1.001  4300
deviance  84.491   2.068 82.536 83.054 83.869 85.265 89.928 1.001 44000

The posterior median of the dispersion index is 1.56 and the 95%-HDI is ranging from $1.345$ to $2.172$ and the value of $1.47$ as estimated by glm is well within the 95%-HDI. Heres the density plot of the posterior distribution of the dispersion index:
Comment: @Tomas: Please read my comments. The WinBUGS model is a Poisson-Log-Normal model and *not* a quasi-Poisson model. The dispersion parameters cannot be compared, they will never be the same. So don't try to get 1.47 using WinBUGS, you won't. The overdispersion parameter in the quasi-Poisson glm is calculated as follows: `1/(n-k)*sum((C.OD-fitted(glm.fit.no.OD))^2/fitted(glm.fit.no.OD))` where `n` is the sample size and `k` the number of parameters (i.e. 2).
Comment: Thank you for your very thorough answer!! But I am sorry I cannot make a big use of it - it is like complete manual for professional statisticians, beyond my capabilities. I expected something simple - like you will have a look at my bugs model and show me how to compute the dispersion parameter from my parameters shown in `print(out)`. Or that you will say: your model has to be extended by adding this and this to be able to find out the dispersion parameter. Sorry if your answer already contains this, I am not able to get the information out of it - too much information and new terms to me...
Comment: I have updated my answer by adding output both from `glm()` and `bugs`.
Comment: @Tomas The Poisson log-normal method (or negative binomial etc.) is perfectly fine for modelling overdispersion, why do you want a quasi-Poisson model in WinBUGS? Quasi-Likelihood is a method to model the relationship between the mean and the variance. Of course the model has a mathematical formulation (just google it)  but I doubt that this will help you in any way. My suggestion is to use the perfectly fine Bayesian methodology to fit your model.
Comment: Try to add the following code to your WinBUGS code:
`kappa <- exp(alpha + beta);
mean.x <- exp(alpha + 0.5*sigma2);
vari <- kappa*exp(sigma2/2)+kappa*kappa*exp(2*sigma2) -
kappa*kappa*exp(sigma2);
DI <- vari/mean.x`
Then set a node for `DI` and paste the output into your question again.
Comment: Thanks. Not correct. Returns 20.96. Please see the updated question.
Comment: @Tomas Both `DI` and `maybe_overdisp` indicate overdispersion. Note that you *cannot* estimate the exact same dispersion coefficient as in the quasi-Poisson model because the model is completely different. So don't search for a coefficient that is exactly equal.
Comment: I was asking how `glm()` computes the overdispersion parameter. I understand that there will be difference, but 1.47 and 20 is a *big* difference for your DI to be the answer. This is certainly not the way it is calculated.
Comment: Nor is `maybe_overdisp` - the mean is 1.121 and the se is 0.179 - the SE is *very* small for it to fit 1.47.
Comment: Aha, then I am trying to compare something which I can't! I thought my WinBUGS model is a quasipoisson! I was trying to implement it! But, how does the quasipoisson model look like then?
Comment: @Tomas You can't run a quasi-Poisson model in WinBUGS. But you can model the overdispersion by the several method that I described: Negative binomial, Poisson log-normal etc.
Comment: Why you can't run quasi-Possion model in WinBUGS? The model must have some formula. Do you know the formula?


Changing the content of HTML body at runtime periodically - NodeJS

Question: index.html
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>

app.js
I have a simple UDP Socket and a simple HTTP Server:
var socket = require( "dgram" ).createSocket( "udp4" );
socket.on("message", function ( message, requestInfo ) {
    document.body.innerHTML = message; // which obviously wrong
    // because the file is running on the client-side
    // I'm looking for something equivalent
});

socket.bind(1247);

var http = require('http'), fs = require('fs');
fs.readFile('./index.html', function (err, html) {
   http.createServer(function(request, response) {
        response.writeHeader(200, {"Content-Type": "text/html"});
        response.write(html);
        response.end();
    }).listen(1247,'xx.xx.xx.xx');
});

I am receiving the UDP messages successfully and periodically (every 5 seconds) from another device.
Is there a way to change the content of the HTML body after the first request from the user every time it receives the UDP message ?
Answer: If you want fast communication between the server and client, and your server side processing is getting the messages on a socket, then I'd recommend using socket.io.
You can establish a web-socket connection between the client and server, and the server can send the message down to all clients when it receives the message. On your client, you'd have code similar to what you've already created. This is an example snippet from socket.io docs.
socket.on('new message', function (data) {
    document.body.innerHTML = data;
    // do something with the new data
});

This answer contains a good socket.io example.