cannot set property 'innerHTML'

Question: Estou tentando fazer um jogo da forca e quero que mostre as letras ja digitadas corretamente aparecerem a previa nas divs, porém da o seguinte erro no chrome

forca.js:95 Uncaught TypeError: Cannot set property 'innerHTML' of null
      at forca (forca.js:95)
      at HTMLButtonElement.onclick (index.html:43)
  forca @ forca.js:95
  onclick @ index.html:43

Se eu tento setar todas as palavras em uma div qualquer funciona, apenas do jeito que era pra funcionar não funciona, alguma solução?
Meu código abaixo.

var i;
var quantidadeClasses = 3;
var lastResult;
var palavras = new Array(quantidadeClasses);
for(i = 0; i < quantidadeClasses; i++) {
 palavras[i] = new Array ();
}
/*
 palavras[0] = Veículos
 palavras[1] = Animais
 palavras[2] = Cor
*/

//Palavras Veículos
 palavras[0][0] = "Carro";
 palavras[0][1] = "Barco";
 palavras[0][2] = "Moto";
 palavras[0][3] = "Onibus"

//Palavras Animais
 palavras[1][0] = "Cachorro";
 palavras[1][1] = "Gato";
 palavras[1][2] = "Cavalo";
 palavras[1][3] = "Camelo";
 palavras[1][4] = "Girafa";
 palavras[1][5] = "Golfinho";
 palavras[1][6] = "Macaco";

//Palavras Cor

 palavras[2][0] = "Branco";
 palavras[2][1] = "Preto";
 palavras[2][2] = "Amarelo";
 palavras[2][3] = "Vermelho";
 palavras[2][4] = "Verde";
 palavras[2][5] = "Azul";
 palavras[2][6] = "Cinza";
 palavras[2][7] = "Rosa";

var erros;
var jogada = 0;
var tentativas = 7;
var letra;
var re;
var checar;
var fimJogo;
var maxClasse;
var randomClasse;
var maxPalavras;
var randomPalavra;
var palavra;
var acertos;
var palavraLength;

window.onload = function carregamento() {
 inicioPartida();
}

function inicioPartida() {
 erros = 0;
 jogada = 0;
 acertos = 0;
 fimJogo = false;
 maxClasse = (palavras.length) - 1;
 randomClasse = Math.floor(Math.random() * (maxClasse + 1));
 maxPalavras = (palavras[randomClasse].length) - 1;
 randomPalavra = Math.floor(Math.random() * (maxPalavras + 1));
 palavra = palavras[randomClasse][randomPalavra];
 palavraLength = palavra.length;
 document.getElementById("teclado").style.display = ""
 document.getElementById("jogarNovamente").style.display = "none";
 for(i = 0; i < palavraLength; i++) {
  document.getElementById("casinha" + i).style.display = "";
 }
}
function forca(letra) {
 document.getElementById(letra).disabled = true;
 document.getElementById(letra).style.color = "#FFF";
 document.getElementById(letra).style.borderColor = "#000";
 document.getElementById("placar").style.display = "";
 if(jogada == 0)
  document.getElementById("avisoTeclado").style.display = "none";
 if(palavra.toUpperCase().indexOf(letra) > -1){
  document.getElementById(letra).style.backgroundColor = "#0F0";
  var lastResult = "acertou";
  document.getElementById("placar").style.color = "#0F0";
  document.getElementById("lastLetra").innerHTML = letra;
  document.getElementById("lastResult").innerHTML = "acertou";
  acertos++;
  for(i = 0; i < palavraLength; i++) {
   var acharLetra = palavra.indexOf(letra);
   document.getElementById("casinha" + acharLetra).innerHTML = letra;
  }
  re = new RegExp(letra, 'gi');
  palavra = palavra.replace(re, '0');
  checar = /^0+$/.test(palavra);
  if(checar == true) {
   setTimeout(function(){ alert("Você venceu. Parabéns!!!"); }, 200);
   document.getElementById("placar").innerHTML = "Você venceu a partida.
Caso queira jogar novamente, clique no botão acima para jogar novamente.";
   fimJogo = true;
  }
 }
 else{
  document.getElementById(letra).style.backgroundColor = "#F00";
  document.getElementById("placar").style.color = "#F00";
  document.getElementById("lastLetra").innerHTML = letra;
  document.getElementById("lastResult").innerHTML = "errou";
  erros++;
  if(erros == tentativas) {
   document.getElementById("img").src = "src/boneco/7.png";
   document.getElementById("placar").innerHTML = "Você perdeu o jogo. A palavra correta era " + palavras[randomClasse][randomPalavra] + ".";
   fimJogo = true;
  }
  else {
   document.getElementById("img").src = "src/boneco/" + erros + ".png";
  }
 }
 if(fimJogo == true) {
  finalizarPartida();
 }
 jogada++;
}
function mostrarJogar() {
 document.getElementById("tutorial").style.display = "none";
 document.getElementById("jogar").style.display = "";;
 document.getElementById("liTutorial").style.backgroundColor = "#EEE";
 document.getElementById("liJogar").style.backgroundColor = "#DDD";
}
function mostrarTutorial() {
 document.getElementById("tutorial").style.display = "";
 document.getElementById("jogar").style.display = "none";
 document.getElementById("liTutorial").style.backgroundColor = "#DDD";
 document.getElementById("liJogar").style.backgroundColor = "#EEE";
}
function gerarDica1() {
 var classe;
 switch (randomClasse) {
  case 0:
  classe = "é um veículo";
  break;
  case 1:
  classe = "é um animal";
  break;
  case 2:
  classe = "é uma cor";
  break;
 }
 document.getElementById("mostrarDica1").innerHTML = classe;
}
function gerarDica2() {
 var primeiraLetra = palavra.charAt(0);
 document.getElementById("mostrarDica2").innerHTML = "Primeira letra: '" + primeiraLetra + "'";
}
function finalizarPartida() {
 document.getElementById("teclado").style.display = "none"
 document.getElementById("jogarNovamente").style.display = "";
}
button {
 color: #777;
 background-color: #EEE;
 border: 1px #EEE solid;
}
button:hover {
 color: #000;
 background-color: #DDD;
 border: 1px #CCC solid;
}
ul#navbar {
 list-style-type: none;
 margin: 0;
 padding: 0;
 overflow: hidden;
 background-color: #EEE;
 border: 1px #DDD solid;
}
li {
 float: left;
}
li a {
 color: #777;
 display: block;
 text-align: center;
 padding: 14px 16px;
 text-decoration: none;
}
li a:hover {
 background-color: #DDD;
 color: #000;
 transition-duration: 0.4s;
 text-decoration: none;
}
.invisivel {
 display: none;
}
#main {
 margin: auto;
 margin-top: 15px;
 margin-bottom: 15px;
 width: 550px;
 min-height: 700px;
 border: 1px #CCC solid;
 background-color: #F5F5F5;
}
#logoDiv {
 background-image: url("../src/logo.jpg");
 height: 200px;
 border-bottom: 1px #CCC solid;
}
#headerDiv {
 border-bottom: 1px #CCC solid;
}
#bodyDiv {
 margin: 10px;
 vertical-align: middle;
}
#leftSide {
 float: right;
 width: 50%;
}
#rightSide {
 float: left;
 width: 50%;
}
.center {
 display: block;
 margin-left: auto;
 margin-right: auto;

}
#teclado {
 width: 370px;
 height: 120px;
 background-color: #DDD;
 border: 1px #CCC solid;
 border-radius: 10px;
}
#teclado-cima {
 margin-bottom: 5px;
 margin-top: 10px;
 margin-left: 10px;
 margin-right: 10px;
}
#teclado-meio {
 margin-bottom: 5px;
}
#teclado-baixo {
 margin-bottom: 10px;
}
.teclado {
 width: 30px !important;
 height: 30px !important;
}
#dicaDiv {
 margin-top: 5px;
 border: 1px #606060 solid;
 border-radius: 10px;
 background-color: #DCDCDC;
 padding: 10px;
}
#pDica1 {
 margin: 0 auto;
}

#placar {
 margin-top: 5px;
}
#avisoTeclado {
 margin-top: 5px;
}
#img {
 border: 1px #606060 solid;
 margin-bottom: 10px;
}
.casinhas  {
 text-decoration: underline;
}
<!DOCTYPE html>

 <title>Jogo da Forca</title>
 <meta charset="utf-8">

 <meta http-equiv="X-UA-Compatible" content="IE=edge">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
 <link rel="stylesheet" type="text/css" href="src/style.css">

Jogar

Tutorial

       <button class="teclado" id="Q" name="nameTeclado" onClick="forca(this.id);">Q</button>
       <button class="teclado" id="W" name="nameTeclado" onClick="forca(this.id);">W</button>
       <button class="teclado" id="E" name="nameTeclado" onClick="forca(this.id);">E</button>
       <button class="teclado" id="R" name="nameTeclado" onClick="forca(this.id);">R</button>
       <button class="teclado" id="T" name="nameTeclado" onClick="forca(this.id);">T</button>
       <button class="teclado" id="Y" name="nameTeclado" onClick="forca(this.id);">Y</button>
       <button class="teclado" id="U" name="nameTeclado" onClick="forca(this.id);">U</button>
       <button class="teclado" id="I" name="nameTeclado" onClick="forca(this.id);">I</button>
       <button class="teclado" id="O" name="nameTeclado" onClick="forca(this.id);">O</button>
       <button class="teclado" id="P" name="nameTeclado" onClick="forca(this.id);">P</button>

       <button class="teclado" id="A" name="nameTeclado" onClick="forca(this.id);">A</button>
       <button class="teclado" id="S" name="nameTeclado" onClick="forca(this.id);">S</button>
       <button class="teclado" id="D" name="nameTeclado" onClick="forca(this.id);">D</button>
       <button class="teclado" id="F" name="nameTeclado" onClick="forca(this.id);">F</button>
       <button class="teclado" id="G" name="nameTeclado" onClick="forca(this.id);">G</button>
       <button class="teclado" id="H" name="nameTeclado" onClick="forca(this.id);">H</button>
       <button class="teclado" id="J" name="nameTeclado" onClick="forca(this.id);">J</button>
       <button class="teclado" id="K" name="nameTeclado" onClick="forca(this.id);">K</button>
       <button class="teclado" id="L" name="nameTeclado" onClick="forca(this.id);">L</button>

       <button class="teclado" id="Z" onClick="forca(this.id);">Z</button>
       <button class="teclado" id="X" name="nameTeclado" onClick="forca(this.id);">X</button>
       <button class="teclado" id="C" name="nameTeclado" onClick="forca(this.id);">C</button>
       <button class="teclado" id="V" name="nameTeclado" onClick="forca(this.id);">V</button>
       <button class="teclado" id="B" name="nameTeclado" onClick="forca(this.id);">B</button>
       <button class="teclado" id="N" name="nameTeclado" onClick="forca(this.id);">N</button>
       <button class="teclado" id="M" name="nameTeclado" onClick="forca(this.id);">M</button>

      _
      _
      _
      _
      _
      _
      _
      _
      _
      _
      _
      _
      _
      _
      _

     <button id="jogarNovamente" class="center" style="display: none;" onClick="window.location.reload(false);">Jogar Novamente</button>

Clique em alguma tecla do teclado para jogar.

Você jogou  e .

Dica 1: mostrar dica.

Dica 2: mostrar dica.

Nesse tópico, você verá como jogar o Jogo da Forca.

Comment: Paulo, qual é exatamente a linha 95? Aparentemente não achou o elemento, por exemplo nessa linha `document.getElementById("casinha" + acharLetra).innerHTML`, pode ser que a junção de "casinha" com a variável **acharLetra** gere um ID que não existe
Answer: Eu coloquei um console.log antes da chamada problemática e retornou o seguinte: "casinha-1" e seu ID da casinha é "casinha1".
for(i = 0; i < palavraLength; i++) {
    var acharLetra = palavra.indexOf(letra);
    console.log("casinha" + acharLetra);
    document.getElementById("casinha" + acharLetra).innerHTML = letra;
}

Verifica onde está vindo o '-'
Comment: Provavelmente o `-1` é retornado por `indexOf`, já que este é o valor retornado quando não é encontrada nenhuma ocorrência: https://www.w3schools.com/jsref/jsref_indexof.asp
Comment: Então colocar um IF resolve o problema.
Comment: tentei usar um if mas do mesmo jeito nao deu, a solução abaixo mudou algumas coisas e acabou funcionando :)
Answer: Incluí o acharLetra na hora em que ele verifica que a letra existe, que é
...
if((acharLetra = palavra.toUpperCase().indexOf(letra)) > -1){
  document.getElementById(letra).style.backgroundColor = "#0F0";
  var lastResult = "acertou";
  document.getElementById("placar").style.color = "#0F0";
  document.getElementById("lastLetra").innerHTML = letra;
...

Para isso, declarei acharLetra um pouco antes, perto do início de forca(),
function forca(letra) {
  var acharLetra;
  document.getElementById(letra).disabled = true;
  document.getElementById(letra).style.color = "#FFF";
....

var i;
var quantidadeClasses = 3;
var lastResult;
var palavras = new Array(quantidadeClasses);
for(i = 0; i < quantidadeClasses; i++) {
 palavras[i] = new Array ();
}
/*
 palavras[0] = Veículos
 palavras[1] = Animais
 palavras[2] = Cor
*/

//Palavras Veículos
 palavras[0][0] = "Carro";
 palavras[0][1] = "Barco";
 palavras[0][2] = "Moto";
 palavras[0][3] = "Onibus"

//Palavras Animais
 palavras[1][0] = "Cachorro";
 palavras[1][1] = "Gato";
 palavras[1][2] = "Cavalo";
 palavras[1][3] = "Camelo";
 palavras[1][4] = "Girafa";
 palavras[1][5] = "Golfinho";
 palavras[1][6] = "Macaco";

//Palavras Cor

 palavras[2][0] = "Branco";
 palavras[2][1] = "Preto";
 palavras[2][2] = "Amarelo";
 palavras[2][3] = "Vermelho";
 palavras[2][4] = "Verde";
 palavras[2][5] = "Azul";
 palavras[2][6] = "Cinza";
 palavras[2][7] = "Rosa";

var erros;
var jogada = 0;
var tentativas = 7;
var letra;
var re;
var checar;
var fimJogo;
var maxClasse;
var randomClasse;
var maxPalavras;
var randomPalavra;
var palavra;
var acertos;
var palavraLength;

window.onload = function carregamento() {
 inicioPartida();
}

function inicioPartida() {
 erros = 0;
 jogada = 0;
 acertos = 0;
 fimJogo = false;
 maxClasse = (palavras.length) - 1;
 randomClasse = Math.floor(Math.random() * (maxClasse + 1));
 maxPalavras = (palavras[randomClasse].length) - 1;
 randomPalavra = Math.floor(Math.random() * (maxPalavras + 1));
 palavra = palavras[randomClasse][randomPalavra];
 palavraLength = palavra.length;
 document.getElementById("teclado").style.display = ""
 document.getElementById("jogarNovamente").style.display = "none";
 for(i = 0; i < palavraLength; i++) {
  document.getElementById("casinha" + i).style.display = "";
 }
}
function forca(letra) {
    var acharLetra;
 document.getElementById(letra).disabled = true;
 document.getElementById(letra).style.color = "#FFF";
 document.getElementById(letra).style.borderColor = "#000";
 document.getElementById("placar").style.display = "";
 if(jogada == 0)
  document.getElementById("avisoTeclado").style.display = "none";
 if((acharLetra = palavra.toUpperCase().indexOf(letra)) > -1){
  document.getElementById(letra).style.backgroundColor = "#0F0";
  var lastResult = "acertou";
  document.getElementById("placar").style.color = "#0F0";
  document.getElementById("lastLetra").innerHTML = letra;
  document.getElementById("lastResult").innerHTML = "acertou";
  acertos++;
  for(i = 0; i < palavraLength; i++) {
   document.getElementById("casinha" + acharLetra).innerHTML = letra;
  }
  re = new RegExp(letra, 'gi');
  palavra = palavra.replace(re, '0');
  checar = /^0+$/.test(palavra);
  if(checar == true) {
   setTimeout(function(){ alert("Você venceu. Parabéns!!!"); }, 200);
   document.getElementById("placar").innerHTML = "Você venceu a partida.
Caso queira jogar novamente, clique no botão acima para jogar novamente.";
   fimJogo = true;
  }
 }
 else{
  document.getElementById(letra).style.backgroundColor = "#F00";
  document.getElementById("placar").style.color = "#F00";
  document.getElementById("lastLetra").innerHTML = letra;
  document.getElementById("lastResult").innerHTML = "errou";
  erros++;
  if(erros == tentativas) {
   document.getElementById("img").src = "src/boneco/7.png";
   document.getElementById("placar").innerHTML = "Você perdeu o jogo. A palavra correta era " + palavras[randomClasse][randomPalavra] + ".";
   fimJogo = true;
  }
  else {
   document.getElementById("img").src = "src/boneco/" + erros + ".png";
  }
 }
 if(fimJogo == true) {
  finalizarPartida();
 }
 jogada++;
}
function mostrarJogar() {
 document.getElementById("tutorial").style.display = "none";
 document.getElementById("jogar").style.display = "";;
 document.getElementById("liTutorial").style.backgroundColor = "#EEE";
 document.getElementById("liJogar").style.backgroundColor = "#DDD";
}
function mostrarTutorial() {
 document.getElementById("tutorial").style.display = "";
 document.getElementById("jogar").style.display = "none";
 document.getElementById("liTutorial").style.backgroundColor = "#DDD";
 document.getElementById("liJogar").style.backgroundColor = "#EEE";
}
function gerarDica1() {
 var classe;
 switch (randomClasse) {
  case 0:
  classe = "é um veículo";
  break;
  case 1:
  classe = "é um animal";
  break;
  case 2:
  classe = "é uma cor";
  break;
 }
 document.getElementById("mostrarDica1").innerHTML = classe;
}
function gerarDica2() {
 var primeiraLetra = palavra.charAt(0);
 document.getElementById("mostrarDica2").innerHTML = "Primeira letra: '" + primeiraLetra + "'";
}
function finalizarPartida() {
 document.getElementById("teclado").style.display = "none"
 document.getElementById("jogarNovamente").style.display = "";
}
button {
 color: #777;
 background-color: #EEE;
 border: 1px #EEE solid;
}
button:hover {
 color: #000;
 background-color: #DDD;
 border: 1px #CCC solid;
}
ul#navbar {
 list-style-type: none;
 margin: 0;
 padding: 0;
 overflow: hidden;
 background-color: #EEE;
 border: 1px #DDD solid;
}
li {
 float: left;
}
li a {
 color: #777;
 display: block;
 text-align: center;
 padding: 14px 16px;
 text-decoration: none;
}
li a:hover {
 background-color: #DDD;
 color: #000;
 transition-duration: 0.4s;
 text-decoration: none;
}
.invisivel {
 display: none;
}
#main {
 margin: auto;
 margin-top: 15px;
 margin-bottom: 15px;
 width: 550px;
 min-height: 700px;
 border: 1px #CCC solid;
 background-color: #F5F5F5;
}
#logoDiv {
 background-image: url("../src/logo.jpg");
 height: 200px;
 border-bottom: 1px #CCC solid;
}
#headerDiv {
 border-bottom: 1px #CCC solid;
}
#bodyDiv {
 margin: 10px;
 vertical-align: middle;
}
#leftSide {
 float: right;
 width: 50%;
}
#rightSide {
 float: left;
 width: 50%;
}
.center {
 display: block;
 margin-left: auto;
 margin-right: auto;

}
#teclado {
 width: 370px;
 height: 120px;
 background-color: #DDD;
 border: 1px #CCC solid;
 border-radius: 10px;
}
#teclado-cima {
 margin-bottom: 5px;
 margin-top: 10px;
 margin-left: 10px;
 margin-right: 10px;
}
#teclado-meio {
 margin-bottom: 5px;
}
#teclado-baixo {
 margin-bottom: 10px;
}
.teclado {
 width: 30px !important;
 height: 30px !important;
}
#dicaDiv {
 margin-top: 5px;
 border: 1px #606060 solid;
 border-radius: 10px;
 background-color: #DCDCDC;
 padding: 10px;
}
#pDica1 {
 margin: 0 auto;
}

#placar {
 margin-top: 5px;
}
#avisoTeclado {
 margin-top: 5px;
}
#img {
 border: 1px #606060 solid;
 margin-bottom: 10px;
}
.casinhas  {
 text-decoration: underline;
}
<!DOCTYPE html>

 <title>Jogo da Forca</title>
 <meta charset="utf-8">

 <meta http-equiv="X-UA-Compatible" content="IE=edge">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
 <link rel="stylesheet" type="text/css" href="src/style.css">

Jogar

Tutorial

       <button class="teclado" id="Q" name="nameTeclado" onClick="forca(this.id);">Q</button>
       <button class="teclado" id="W" name="nameTeclado" onClick="forca(this.id);">W</button>
       <button class="teclado" id="E" name="nameTeclado" onClick="forca(this.id);">E</button>
       <button class="teclado" id="R" name="nameTeclado" onClick="forca(this.id);">R</button>
       <button class="teclado" id="T" name="nameTeclado" onClick="forca(this.id);">T</button>
       <button class="teclado" id="Y" name="nameTeclado" onClick="forca(this.id);">Y</button>
       <button class="teclado" id="U" name="nameTeclado" onClick="forca(this.id);">U</button>
       <button class="teclado" id="I" name="nameTeclado" onClick="forca(this.id);">I</button>
       <button class="teclado" id="O" name="nameTeclado" onClick="forca(this.id);">O</button>
       <button class="teclado" id="P" name="nameTeclado" onClick="forca(this.id);">P</button>

       <button class="teclado" id="A" name="nameTeclado" onClick="forca(this.id);">A</button>
       <button class="teclado" id="S" name="nameTeclado" onClick="forca(this.id);">S</button>
       <button class="teclado" id="D" name="nameTeclado" onClick="forca(this.id);">D</button>
       <button class="teclado" id="F" name="nameTeclado" onClick="forca(this.id);">F</button>
       <button class="teclado" id="G" name="nameTeclado" onClick="forca(this.id);">G</button>
       <button class="teclado" id="H" name="nameTeclado" onClick="forca(this.id);">H</button>
       <button class="teclado" id="J" name="nameTeclado" onClick="forca(this.id);">J</button>
       <button class="teclado" id="K" name="nameTeclado" onClick="forca(this.id);">K</button>
       <button class="teclado" id="L" name="nameTeclado" onClick="forca(this.id);">L</button>

       <button class="teclado" id="Z" onClick="forca(this.id);">Z</button>
       <button class="teclado" id="X" name="nameTeclado" onClick="forca(this.id);">X</button>
       <button class="teclado" id="C" name="nameTeclado" onClick="forca(this.id);">C</button>
       <button class="teclado" id="V" name="nameTeclado" onClick="forca(this.id);">V</button>
       <button class="teclado" id="B" name="nameTeclado" onClick="forca(this.id);">B</button>
       <button class="teclado" id="N" name="nameTeclado" onClick="forca(this.id);">N</button>
       <button class="teclado" id="M" name="nameTeclado" onClick="forca(this.id);">M</button>

      _
      _
      _
      _
      _
      _
      _
      _
      _
      _
      _
      _
      _
      _
      _

     <button id="jogarNovamente" class="center" style="display: none;" onClick="window.location.reload(false);">Jogar Novamente</button>

Clique em alguma tecla do teclado para jogar.

Você jogou  e .

Dica 1: mostrar dica.

Dica 2: mostrar dica.

Nesse tópico, você verá como jogar o Jogo da Forca.

Comment: muito obrigado, funcionou certinho, porém queria entender como o if((acharLetra = palavra.toUpperCase().indexOf(letra)) > -1) funciona desse jeito e o meu modo ali não, poderia dar uma breve explicação? sou novato em js ainda
Comment: uma outra duvida, quando tem 2 letras repetidas ele só pega a primeira, como eu arrumaria isso nesse metodo?
Comment: Você comparou `palavra` com a `letra`, que é maiúscula. E como a comparação é sensível à caixa, ele não achou as letras minúsculas correspondentes, em `palavra`. Faltou colocar `.toUpperCase()`. Como você tinha usado isso uma vez, nesta linha que mostrei, eu só reaproveitei o código.
Comment: Pra achar mais ocorrências da letra na string, é só adicionar um argumento a mais na chamada de `.indexOf()`. Este segundo argumento é a posição a partir da qual você vai procurar. Por exemplo, digamos que você queira saber onde ocorre a letra pela primeira vez; você faz `var primeiraVez = minhaString.indexOf("A");`. Daí, para a segunda ocorrência, você faz `var segundaVez = minhaString.indexOf("A", primeiraVez + 1);`.
Comment: obrigado, consegui alterando o jeito que eu transformava na string a letra achada para 0 e transformando todas as palavras para tudo maisculo. Codigo completo para caso ajude alguem: https://github.com/phgrund/jogo-da-forca

cannot set property 'innerHTML'


Centralizer of $\mathfrak{so}_{n}(\mathbb{R})$

Question: I want to compute the centralizer of $\mathfrak{so}_{n}(\mathbb{R})$ as a subalgebra of $\mathfrak{gl}_n(\mathbb{R})$:
$$
C_{\mathfrak{gl}_n}(\mathfrak{so}_{n}(\mathbb{R}))=\{X\in \mathfrak{gl}_{n}(\mathbb{R}),\ \forall S\in\mathfrak{so}_{n}(\mathbb{R})\ \ [X,S] = 0\}
$$
My claim is that if $n\neq 2$ then,
$$
C_{\mathfrak{gl}_n}(\mathfrak{so}_{n}(\mathbb{R}))= \{\lambda Id_n,\ \lambda\in\mathbb{R}\}
$$
and if $n=2$ then
$$
C_{\mathfrak{gl}_2}(\mathfrak{so}_{2}(\mathbb{R}))= \mathfrak{so}_{2}(\mathbb{R})
$$
more generaly how to compute the centralizer of $\mathfrak{so}_{p,q}(\mathbb{R})$ as a subalgebra of $\mathfrak{gl}_{p+q}(\mathbb{R})$ ?
Comment: Certainly $\lambda \operatorname{Id}_2$, $\lambda \in \Bbb R$ is in the centralizer $C_{\mathfrak{gl}_2}(\mathfrak{so}_2(\Bbb R))$. Computing directly shows together with $\mathfrak{so}_2$ this accounts for everything, though, that is, that $$C_{\mathfrak{gl}_2}(\mathfrak{so}_2(\Bbb R)) = \mathfrak{so}_2(\Bbb R) \oplus \operatorname{span}(\operatorname{Id}_2) .$$ Sometimes we denote this latter algebra $\mathfrak{cso}_2(\Bbb R)$ and call it the **conformal special orthogonal algebra**.
Answer: Hint The usual matrix representation of $\mathfrak{so}_n$---the space of antisymmetric $n \times n$ matrices---is spanned by the matrices $$-E_{ij} + E_{ji}, \qquad i < j$$ where $E_{ij}$ is the matrix with $(i, j)$ entry $1$ and all other entries $0$, so it suffices find the intersections of the centralizers of all of these matrices.
So, suppose $X = (x_{ij}) \in C_{\mathfrak{gl}_2} (\mathfrak{so}_2)$ (herein I usually suppress the notation $(\Bbb R)$), so that $[X, -E_{ij} + E_{ji}] = 0$ for all $i < j$; write this matrix system in terms of its entries, and solve for the entries $x_{ij}$.

Additional hint Doing so gives a system of equations equivalent to $$x_{ii} = x_{jj}, \qquad x_{ji} = -x_{ij}, \qquad \textrm{and} \qquad x_{ik} = x_{ki} = x_{jk} = x_{kj} = 0 \quad \textrm{for} \quad k \not\in \{i, j\} .$$

N.B. that the case $n = 2$ is exceptional: Here there is only one choice for $(i, j)$, namely $(1, 2)$, and the last condition hidden above is vacuous, leaving just the first two equations there. By relabeling entries we can write the centralizer of $\mathfrak{so}_2$ in $\mathfrak{gl}_2$ is
$$C_{\mathfrak{gl}_2} (\mathfrak{so}_2) = \left\{\pmatrix{x&-y\\y&x} : x, y \in \Bbb R\right\} = \mathfrak{so}_2 \oplus \operatorname{span}\{\operatorname{Id}_2\} .$$
Remark Computing gives that this latter Lie algebra preserves the standard inner product up to a scalar multiple, so we sometimes call it the conformal (special) orthogonal Lie algebra and denote it $\mathfrak{cso}_2(\Bbb R)$.
The procedure for $\mathfrak{so}_{p, q}$ is essentially the same: (1) Pick a faithful matrix representation, (2) pick a convenient basis $(F_a)_{a \in A}$ of matrices, (3) impose the conditions $[X, F_a] = 0$, $a \in A$, on a general matrix $X \in \mathfrak{gl}_{p + q}$, and (4) write these equations in terms of their entires and solve.
It will require a few more observations, but probably one can handle all of the cases $\mathfrak{so}_{p, q}$ for a given $n := p + q$ simultaneously by computing $C_{\mathfrak{gl}_n(\Bbb C)}(\mathfrak{so}_n(\Bbb C))$ (the computation is essentially the same as for $\mathfrak{so}_n(\Bbb R))$.


How to make Taxonomy replacement tokens available to the HTML email action in Rules?

Question: I have created a rule for a client that triggers an HTML email to them every time an authenticated site visitor downloads one of their PDF brochures.
I have no problem including things such as the username, email address, filename and other info, but the client wants to have the "vertical" of the PDF displaying as additional information on the outgoing email.
The PDF's are uploaded as a unique content type and are categorised by using taxonomy terms through a select field.
Unfortunately, when editing the HTML email action element on the rule, there are a whole bunch of replacement tokens, except any related to taxonomy. I tried to "wing it" and create a taxonomy token, but of course this did not work and it seems logical that there would naturally be a disconnect here as how would the rule know to relate the correct term to the file being downloaded.
Any advice with regards to possible workarounds?
Answer: Make sure to add a Rules condition Entity has field (related to your field you indicated via the "through a select field..." in your question).
That's also what is mentioned in the Rules UI, e.g. when you're adding a "data comparison" condition: somewhere it says "The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')".
Your question seems to be related to using such field in a Rules Action (instead of a Rules Condition). However, have a look at the sample rule in included in my answer to "How to specify a Rules condition related to select list values?". That rule doesn't have a "Rules Action" that uses that field (as you seem to try to do). Though using the Rules UI to (eg) edit the message I'd want to display in my sample rule, within the list of tokes available for Replacement patterns for created content, one of them is actually [node:field-optionlist]. And the 'created content' in my case is because of the Rules Event node_insert that's used in my sample rule.
For a video tutorial that illustrates the importance of this Entity has field condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in it.
PS: To have such field available to use it in any other Rules Condition also, I always add such Entity has field condition BEFORE any other Rules Conditions, if any.


Generalized Least Squares vs Ordinary Least Squares under a special case

Question: This question regards the problem of Generalized Least Squares. Vectors and matrices will be denoted in bold.
Premises. Let $N,K$ be given integers, with $K \gg N > 1$. The transpose of matrix $\mathbf{A}$ will be denoted with $\mathbf{A}^T$. Suppose the following statistical model holds
$$
(*) \quad \mathbf{y} = \mathbf{Hx + n}, \quad \mathbf{n} \sim \mathcal{N}_{K}(\mathbf{0}, \mathbf{C})
$$
where $\mathbf{y} \in \mathbb{R}^{K \times 1}$ are the observables, $\mathbf{H} \in \mathbb{R}^{K \times N}$ is a known full-rank matrix, $\mathbf{x} \in \mathbb{R}^{N \times 1}$ is a deterministic vector of unknown parameters (which we want to estimate) and finally $\mathbf{n} \in \mathbb{R}^{K \times 1}$ is a disturbance vector (noise) with a known (positive definite) covariance matrix $\mathbf{C} \in \mathbb{R}^{K \times K}$. The Maximum Likelihood (ML) estimate of $\mathbf{x}$, denoted with $\hat{\mathbf{x}}_{ML}$, is given by
$$
(1) \quad \hat{\mathbf{x}}_{ML} = (\mathbf{H}^T \mathbf{C^{-1}} \mathbf{H})^{-1} \mathbf{H}^T \mathbf{C}^{-1} \mathbf{y}
$$
and this is also the standard formula of Generalized Linear Least Squares (GLLS). Consider the standard formula of Ordinary Least Squares (OLS) for a linear model, i.e.
$$
(2) \quad \hat{\mathbf{x}}_{OLS} = (\mathbf{H}^T \mathbf{H})^{-1} \mathbf{H}^T \mathbf{y}
$$
As a final note on notation, $\mathbf{I}_K$ is the $K \times K$ identity matrix and $\mathbf{O}$ is a matrix of all zeros (with appropriate dimensions).
Now, for the problem at hand, assume that $\mathbf{C}^{-1} = \mathbf{I}_K + \mathbf{X}$, where $\mathbf{X} \in \mathbb{R}^{K \times K}$ is a symmetric, invertible matrix (and, for the formalism to make sense, $\mathbf{X}$ is such that $\mathbf{I}_K + \mathbf{X}$ is invertible and the inverse is positive definite). In this case, it can be proven (using matrix inversion lemma) that
$$
(3) \quad (\mathbf{H}^T \mathbf{C^{-1}} \mathbf{H})^{-1} \mathbf{H}^T \mathbf{C}^{-1} = (\mathbf{H}^T \mathbf{H})^{-1} \mathbf{H}^T + \mathbf{Q}
$$
where the expression for the matrix $\mathbf{Q} \in \mathbb{R}^{N \times K}$ can be found (I will omit it here). Now, finally,
Proposition 1. If $\mathbf{H}^T\mathbf{X} = \mathbf{O}_{N,K}$, then equation $(1)$ degenerates in equation $(2)$, i.e., there exists no difference between GLLS and OLS.
The proof is straigthforward and is valid even if $\mathbf{X}$ is singular. Now, my question is
Question: Can an equation similar to eq. $(3)$ (which "separates" an OLS-term from a second term) be written when $\mathbf{X}$ is a singular matrix?
I am not interested in a closed-form of $\mathbf{Q}$ when $\mathbf{X}$ is singular. But I do am interested in understanding the concept beyond that expression: what is the actual role of $\mathbf{Q}$? In which space does it operate?
I found this problem during a numerical implementation where both OLS and GLLS performed roughly the same (the actual model is $(*)$), and I cannot understand why OLS is not strictly sub-optimal. I found this slightly counter-intuitive, since you know a lot more in GLLS (you know $\mathbf{C}$ and make full use of it, why OLS does not), but this is somehow "useless" if some conditions are met. What are these conditions?
As a final note, I am rather new to the world of Least Squares, since I generally work within a ML-framework (or MMSE in other cases) and never studied the deep aspects of GLLS vs OLS, since, in my case, they are just intermediate steps during the derivation of MLE for a given problem.
If the question is, in your opinion, a bit too broad, or if there is something I am missing, could you please point me in the right direction by giving me references? Preferably well-known books written in standard notation.
Comment: The matrix inversion lemma in the form you use it relies on the matrix $\mathbf X$ being invertible. Intuitively, I would guess that you can extend it to non-invertible (positive-semidifenite?) matrices by using the Moore-Penrose pseudo-inverse, but of course this is very far from a mathematical proof ;-)
Comment: Thank you for your comment. It was the first thought I had, but, intuitively, it is a bit too hard problem and, if someone managed to actually solve it in closed form, a full-fledged theorem would be appropriate to that result. Anyway, if you have some intuition on the other questions I asked, feel free to add another comment.
Comment: Two questions.  One: I'm confused by what you say about the equation $C^{-1}=I+X$.  There is no assumption involved in this equation, is there?  Doesn't the equation serve to define $X$ as $X=C^{-1}-I$?  And doesn't $X$, as the difference between two symmetric matrixes, have to be symmetric--no assumption necessary?  Two: I'm wondering if you are assuming either that $y$ and the columns of $H$ are each zero mean or if you are assuming that one of the columns of $H$ is a column of 1s.  It would be very unusual to assume neither of these things when using the linear model.
Comment: 1. $X$ is symmetric without assumptions, yes. However, $X = C^{-1} - I$ is correct but misleading: $X$ is not defined that way, $C^{-1}$ is (because of its structure). Consider the simple case where $C^{-1}$ is a diagonal matrix, where each element on the main diagonal is of the form: $1 + x_{ii}$, with $x_{ii} > 1$. You would write that matrix as $C^{-1} = I + X$. 2. Unfortunately, no matter how unusual it seems, neither assumption holds in my problem. However, if you can solve the problem with the last column of $H$ being all 1s, please do so, it would still be an important result.
Answer: There are two questions.  First, there is a purely mathematical question about the possibility of decomposing the GLS estimator into the OLS estimator plus a correction factor.  Second, there is a question about what it means when OLS and GLS are the same.  (I will use ' rather than T throughout to mean transpose).
Also, I would appreciate knowing about any errors you find in the arguments.
Question 1
Ordinary Least Squares (OLS) solves the following problem:
\begin{align}
min_x\;\left(y-Hx\right)'\left(y-Hx\right)
\end{align}
leading to the solution:
\begin{align}
\hat{x}_{OLS}=\left(H'H\right)^{-1}H'y
\end{align}
Generalized Least Squares (GLS) solves the following problem:
\begin{align}
min_x\;\left(y-Hx\right)'C^{-1}\left(y-Hx\right)
\end{align}
leading to the solution:
\begin{align}
\hat{x}_{OLS}=\left(H'C^{-1}H\right)^{-1}H'C^{-1}y
\end{align}
Now, make the substitution $C^{-1}=X+I$ in the GLS problem:
\begin{align}
min_x\;&\left(y-Hx\right)'\left(X+I\right)\left(y-Hx\right)\\~\\
min_x\;&\left(y-Hx\right)'X\left(y-Hx\right) + \left(y-Hx\right)'\left(y-Hx\right)\\
\end{align}
The solution is still characterized by first order conditions since we are assuming that $C$ and therefore $C^{-1}$ are positive definite:
\begin{align}
0=&2\left(H'XH\hat{x}_{GLS}-H'Xy\right) +2\left(H'H\hat{x}_{GLS}-H'y\right)\\
\hat{x}_{GLS}=&\left(H'H\right)^{-1}H'y+\left(H'H\right)^{-1}H'Xy
               -\left(H'H\right)^{-1}H'XH\hat{x}_{GLS}\\
\hat{x}_{GLS}=& \hat{x}_{OLS} + \left(H'H\right)^{-1}H'Xy
               -\left(H'H\right)^{-1}H'XH\hat{x}_{GLS}\\
\end{align}
I can see two ways to give you what you asked for in the question from here.  First, we have a formula for the $\hat{x}_{GLS}$ on the right-hand-side of the last expression, namely $\left(H'C^{-1}H\right)^{-1}H'C^{-1}y$.  Thus, the above expression is a closed form solution for the GLS estimator, decomposed into an OLS part and a bunch of other stuff.  The other stuff, obviously, goes away if $H'X=0$.  To be clear, one possible answer to your first question is this:
\begin{align}
\hat{x}_{GLS}=& \hat{x}_{OLS} + \left(H'H\right)^{-1}H'Xy
               -\left(H'H\right)^{-1}H'XH\left(H'C^{-1}H\right)^{-1}H'C^{-1}y\\
\hat{x}_{GLS}=& \hat{x}_{OLS} + \left(H'H\right)^{-1}H'X \left(I
               -H\left(H'C^{-1}H\right)^{-1}H'C^{-1}\right)y
\end{align}
I can't say I get much out of this.  That awful mess near the end multiplying $y$ is a projection matrix, but onto what?
Another way you could proceed is to go up to the line right before I stopped to note there are two ways to proceed and to continue thus:
\begin{align}
\left(I+\left(H'H\right)^{-1}H'XH\right)\hat{x}_{GLS}=& \hat{x}_{OLS} + \left(H'H\right)^{-1}H'Xy\\
\hat{x}_{GLS}=& \left(I+\left(H'H\right)^{-1}H'XH\right)^{-1}\left(\hat{x}_{OLS} + \left(H'H\right)^{-1}H'Xy\right)
\end{align}
Again, GLS is decomposed into an OLS part and another part.  The other part goes away if $H'X=0$. I still don't get much out of this.  What this one says is that GLS is the weighted average of OLS and a linear regression of $Xy$ on $H$.  I guess you could think of $Xy$ as $y$ suitably normalized--that is after having had the "bad" part of the variance $C$ divided out of it.
I should be careful and verify that the matrix I inverted in the last step is actually invertible:
\begin{align}
\left(I+\left(H'H\right)^{-1}H'XH\right) &= \left(H'H\right)^{-1}\left(H'H+H'XH\right)\\
                                         &= \left(H'H\right)^{-1}H'\left(I+X\right)H\\
                                         &= \left(H'H\right)^{-1}H'C^{-1}H
\end{align}
Question 2
The question here is when are GLS and OLS the same, and what intuition can we form about the conditions under which this is true?  I will only provide an answer here for a special case on the structure of $C$.  The requirement is:
\begin{align}
\left(H'C^{-1}H\right)^{-1}H'C^{-1}Y = \left( H'H\right)^{-1}H'Y
\end{align}
To form our intuitions, let's assume that $C$ is diagonal, let's  define $\overline{c}$ by $\frac{1}{\overline{c}}=\frac{1}{K}\sum \frac{1}{C_{ii}}$, and let's write:
\begin{align}
\left(H'C^{-1}H\right)^{-1}H'C^{-1}Y &=
\left(H'\overline{c}C^{-1}H\right)^{-1}H'\overline{c}C^{-1}Y\\
&=\left( H'H\right)^{-1}H'Y
\end{align}
One way for this equation to hold is for it to hold for each of the two factors in the equation:
\begin{alignat}{3}
\left(H'\overline{c}C^{-1}H\right)^{-1}
&=\left( H'H\right)^{-1} & \iff& & H'\left(\overline{c}C^{-1}-I\right)H&=0\\
H'\overline{c}C^{-1}Y&=H'Y & \iff& & H'\left(\overline{c}C^{-1}-I\right)Y&=0
\end{alignat}
Remembering that $C$, $C^{-1}$, and $I$ are all diagonal and denoting by $H_i$ the $i$th row of $H$:
\begin{alignat}{3}
H'\left(\overline{c}C^{-1}-I\right)H&=0 & \iff&
  & \frac{1}{K} \sum_{i=1}^K H_iH_i'\left( \frac{\overline{c}}{C_{ii}}-1\right)=0\\~\\
H'\left(\overline{c}C^{-1}-I\right)Y&=0 & \iff&
  & \frac{1}{K} \sum_{i=1}^K H_iY_i\left( \frac{\overline{c}}{C_{ii}}-1\right)=0
\end{alignat}
What are those things on the right-hand-side of the double-headed arrows?  They are a kind of sample covariance.  To see this, notice that the mean of $\frac{\overline{c}}{C_{ii}}$ is 1, by the construction of $\overline{c}$.  Finally, we are ready to say something intuitive.  In this special case, OLS and GLS are the same if the inverse of the variance (across observations) is uncorrelated with products of the right-hand-side variables with each other and products of the right-hand-side variables with the left-hand-side variable.  This is a very intuitive result.
In estimating the linear model, we only use the products of the RHS variables with each other and with the LHS variable, $(H'H)^{-1}H'y$.  In GLS, we weight these products by the inverse of the variance of the errors.  When does that re-weighting do nothing, on average?  Why, when the weights are uncorrelated with the thing they are re-weighting!  Yes?  When is a weighted average the same as a simple average?  When the weights are uncorrelated with the things you are averaging.
This insight, by the way, if I am remembering correctly, is due to White(1980) and perhaps Huber(1967) before him---I don't recall exactly.
Comment: A very detailed and complete answer, thanks! Matrix notation sometimes does hide simple things such as sample means and weighted sample means. $Q = (H′H)^{−1}H′X(I−H(H′C^{−1}H)^{−1}H′C^{−1})$ does seem incredibly obscure. However, I'm glad my intuition was correct in that GLS can be decomponsed in such a way, regardless if $X$ is invertible or not. Anyway, thanks again!


Using one stack to find number of permutations

Question: Suppose I have a stack and I want to find the permutations of numbers 1,2,3,...n.
I can push and pop. e.g. if n=2: push,pop,push,pop 1,2 and push,push,pop,pop 2,1
if n=4 I can only get 14 from the 24 permutations using the stack.. Does anyone know any function F(n) that could produce the number of permutations the stack (only one) can produce?
eg f(1)=1
f(2)=2
f(4)=14
Thank you
Answer: The number corresponds to the Catalan Numbers which are of the form $\displaystyle \frac{{2n \choose n}}{n+1}$.
I believe this particular problem is an exercise Knuth's Art of Programming Volume I.
For a hint of proof: Number of pushes $\ge$ Number of pops in any prefix of the string of pushes and pops.


Compute the limit: $\lim_{x\to \infty}x\ \log\left(\frac{x+c}{x-c}\right)$

Question: Does anyone know how o compute the following limit?
$$\lim_{x\to \infty}x\ \log\left(\frac{x+c}{x-c}\right)$$
I tried to split it up as follows:
$\lim_{x\to \infty}\left[x\ \log(x+c)-x\ \log(x-c)\right]$ but still this is indeterminate form of type $\infty-\infty$. Any thoughts please?
Comment: $$\frac{x+c}{x-c} = \frac{1 + \frac{c}{x}}{1-\frac{c}{x}}$$
Answer: Using L'Hospital:
$$\lim_{x\to \infty}x\ \log\left(\frac{x+c}{x-c}\right)=\lim_{x\to \infty}\frac{\log\left(\frac{x+c}{x-c}\right)}{\frac 1x}\underbrace{=}_{\mathrm{L'Hospital}} \lim_{x\to \infty} \frac{\frac{x-c}{x+c}\cdot \frac{-2c}{(x-c)^2}}{-\frac {1}{x^2}}=\lim_{x\to \infty} \frac{x-c}{x+c}\cdot \frac{2cx^2}{(x-c)^2}=2c$$
Without using L'Hospital:
$$\lim_{x\to \infty}x\ \log\left(\frac{x+c}{x-c}\right)=\lim_{x\to \infty} \log\left(1+\frac{2c}{x-c}\right)^x=\log \lim_{x\to \infty}\left(1+\frac{2c}{x-c}\right)^x\\=\log \lim_{x\to \infty}\left(\left(1+\frac{2c}{x-c}\right)^{x-c}\right)^{\frac{x}{x-c}}=\log e^{2c}=2c.$$
Comment: In the second expression in the "without" section, that should be $1+\frac{2c}{x-c}$, not minus. That will make the second answer the same as the first.
Comment: @RoryDaulton Fixed. Thank you for noticing it.
Answer: We have:$$\lim_{x\to \infty}x\ \log\left(\frac{x+c}{x-c}\right) = \lim_{x\to \infty}\ \log\left(\frac{x+c}{x-c}\right)^x = \log \lim_{x \to +\infty}\left(\frac{1+\frac{c}{x}}{1-\frac{c}{x}}\right)^x = \log \lim_{x \to +\infty} \frac{\left(1+\frac{c}{x}\right)^x}{\left(1-\frac{c}{x}\right)^x}$$
Using the fundamental limit for $e$: $$= \log \frac{e^c}{e^{-c}} =  \log e^{2c} = 2c.$$
Answer: Let $u = \dfrac{c}{x}$, then:
Note that: $x\log\left(\dfrac{x+c}{x-c}\right) = c\dfrac{\log\left(\dfrac{1+u}{1-u}\right)}{u} = c\left(\dfrac{\log(1+u)}{u} - \dfrac{\log(1-u)}{u}\right) \to c(1-(-1)) = 2c$ since $x \to \infty \iff u \to 0$.
Answer: Hint; Let $t=\frac1x$${}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}$


Mean or Median or something else for representation of large and small list of values

Question: I'm working on a project that generates a list of decimal numbers every hour. The amount of values in the list can range between 1 - 6000 depending on the some variables (time of day etc). Each of the values will range between -1.0 and 1.0. Anything below -0.1 is considering a negative result and anything greater than 0.1 a positive result as there is a -0.1 - 0.1 rate of error in the calculations (anything in that range being regarded as neutral). The more the negative or positive the number is indicating an overall more negative or positive for that specific calculation.
I need to produce a single number that is representative of the list for each hour. While technically the values can range -1.0 - 1.0 most will be around the -0.4 - 0.4 range.
Would it be best to use mean, median, weighted-mean, something else I haven't thought of, or a combination (e.g. outputting two things that when looked at together give a good representation), to get the best representation of the lists?
EDIT
The project is preforming sentiment analysis on messages. At at time interval messages as collected, processed, and then assigned a score as above. What I need is to generate a single number from each interval that is representative of the general sentiment. It doesn't matter too much if the number is wrong in some outside cases as it's only used as a guide, looked at in perspective with other data (number of total messages, ratio of positive/negative/neutral).
I initially did try simply calculating the average but that result in all the lists (there are 8 per interval) coming out around the same +/- 0.01 which when looking at the raw data was indicative of the actual collected results. I've also tried running median calculations on it and that seems to produce more representative figures but I don't know enough about statistics to know if that is true and a good formula to use, or if I should be using something else.
Basically the important part is that you can compare the current outputted value to other lists outputted values and previously outputted values for the same list to get a feel to the up or down trend.
Comment: It makes a difference what the single number would be used for, and what happens if it is in some sense wrong (e.g., due to a highly unusual sample), because the effects of inaccuracy on downstream processes are what determine, to a large extent, which formulae are good or bad.   So if you could help us out with that, we'd (probably!) give you a better answer!
Comment: @jbowman I've edited the question with some more information.
Answer: Which one-number summary is "best" will depend very much on what you plan on doing with it, as jbowman notes.
You write that you would like to get an idea of a trend in data. Beyond the mean and the median, one thing that comes to mind would be the percentage of positive results (i.e., the proportion of results greater than your cutoff of 0.1) - either as a percentage of all results for this time bin, or only of all non-neutral ones. Alternatively, of course, the percentage of negative result.
Another thing that might be interesting is the interquartile range, to give you an idea about whether the variability or noise is increasing.
Note that all of these one number summaries will be more variable in themselves if they are based on small result lists, so you may want to also collect how many results they are based on.
Comment: Sorry it took me so long to accept. Ultimately I decided to go with a display that shows the median and number of positive, negative, and neutral divisions.


A riddle about guessing hat colours (which is not among the commonly known ones)

Question: This is a riddle I heard recently, and my question is if someone happens to know the solution. I'm asking this out of curiosity more than anything else.
So here it is. The riddle is one of the countless variations of the "prisoners have to guess their hat colour" puzzle. $n$ prisoners are put a hat on top of their head, which can be red or blue. The colours are chosen at random by $n$ independent fair coin tosses. Then each prisoner can guess their own hat colour (red or blue) or pass. The prisoners can see each other, but not hear each other's calls and of course they have no other means of communication. This means that each call can only depend on the other prisoners' hat colours. However, before the distributing of hats begins, the prisoners are told the rules and can agree on a strategy. The prisoners win iff no prisoner guesses wrong and at least one prisoner guesses right. Which strategy should the prisoners use so that the winning probability becomes maximal?
Some remarks:

A simple strategy is that one player just guesses and all other players pass, so that the maximal probabilty is at least 1/2. For $n=2$ this strategy is optimal.
For $n=3$, there is a strategy that wins in 6 out of 8 cases: When a player sees (red,red) he guesses blue, for (blue,blue) he guesses red, and otherwise he passes. More generally this shows that the maximal probability is at least 3/4 for $n\ge 3$.
It's possible to show that any strategy fails for at least 2 hat colour configurations (unless $n=1$), which shows that the above strategy is optimal for $n=3$.
For $n=4$ there are more than $10^{15}$ strategies, and for $n=5$ it's about $10^{38}$ strategies, making it quite infeasible to just use a brute-force computer program (maybe for $n=4$ it's possible when exploiting the obvious symmetries).
When changing the rules slightly by forbidding players to pass, then the maximal winning probability is always 1/2. This is a nice little exercise.

Actually I heard the riddle only for $n=3$ and then thought about the general $n$. So it's entirely possible that there is no nice solution.
Answer: After writing up this answer I found this paper that comes to the same conclusions and also generalizes the problem to $q$ hat colours. I'm posting the answer anyway to have it here on math.SE in self-contained form.

As described in the Wikipedia article Gerry linked to and this book it references, an optimal strategy concentrates the wrong guesses onto as few configurations as possible. Each individual player guesses incorrectly exactly half the time if she doesn't pass, and ideally these incorrect guesses should all be concentrated on configurations where everyone guesses incorrectly whereas the correct guesses should ideally be spread out one per configuration.
Let's denote the set $\def\red{\text{red}}\def\blue{\text{blue}}\def\pass{\text{pass}}\{\red,\blue\}$ of hat colours by $H$ and the set $\{\red,\blue,\pass\}$ of guesses by $G$. Then a strategy for $n$ prisoners is a function $H^n\to G^n$ such that the $k$-th entry of the value doesn't depend on the $k$-th entry of the argument.
Given a strategy, we're interested in the proportion of vectors of $H^n$ for which the strategy prescribes a value which is not the constant $\pass$ vector and in which all non-pass entries match the corresponding entries in the argument. Let's call such vectors good and the others bad.
Adjacent to every good vector $g\in H^n$ is at least one bad vector $b\in H^n$ that differs from $g$ only in the hat colour of one of the prisoners who guess correctly for $g$ (of which there is at least one). Conversely, given a subset $S\subseteq H^n$ of bad vectors such that every vector is adjacent to at least one bad vector in this sense, we can make all other vectors good by assigning an adjacent bad vector to each of them (arbitrarily if there's more than one) and letting only the prisoner in whose entry the two vectors differ guess.
Thus, an optimal strategy is defined by a minimal subset $S\subseteq H^n$ such that all vectors in $H^n$ are adjacent to at least one element of $S$. Such a minimal subset is called a binary optimal covering code of length $n$ and radius $1$, and the number of vectors in such a minimal subset is denoted by $K(n,1)$. This table (linked to from this page) gives the known bounds on $K(n,1)$ up to $n=33$.
For $n=2^k-1$ the Hamming codes described in the article and the book are optimal binary covering codes with $2^{n-k}$ vectors, with winning probability $1-2^{n-k}/2^n=1-2^{-k}=n/(n+1)$. For other values of $n$, the values of $K(n,1)$ are only known up to $n=9$, and for $n$ a power of $2$; the lower bound for $K(27,1)$ was improved only recently.
Comment: Thanks for you answer joriki, what can I conclude from your answer if there're 100 prisoners?
Answer: The puzzle is discussed at http://en.wikipedia.org/wiki/Hat_Puzzle, in the section on Ebert's version and Hamming codes.
Comment: @Ilan, it would seem, from joriki's answer, that exact answers are known only for $n\le9$ (and for powers of $2$), and estimates are tabulated for $n\le33$. I'd recommend you go to the links in joriki's answer and see what can be applied to get bounds for $n=100$. You might want to post a new question (linnking to this question) instead of asking in a comment here where it's unlikely to get much attention.
Comment: Mike answered it: https://math.stackexchange.com/questions/3272959/hat-guessing-with-100-hats-case/3272988#3272988
Comment: Thanks for you answer Gerry, what can I conclude from your answer if there're 100 prisoners?


I need a advanced search block (by using views) on home page of site

Question: I'm beginner in drupal.
I'm developing a site contains products that are displayed some product blocks by using views module on front page like featured products and top rated products.
Now, I also need to add a advanced search block (by using views module) on front page like I've attached image below. This search will only search from the one type of content named product and show another page.
How to add input field name titled, dropdown list, radio buttons and Search button while creating views block?
Answer: For Drupal 7 you can create mentioned output via setting Filters and set the option "Expose this filter to the user"
Moreover, you can add checkbox using BEF(Better Exposed Filters).
I hope this helps. :)
Comment: welcome..... :)


What is 'task' in F#?

Question:              let CreateEventSourcingConnection() =
             task {
                 let connection =
                     let ipEndPoint = IPEndPoint(IPAddress.Loopback, 1113)
                     EventStoreConnection.Create(ipEndlPoint)
                 do! connection.ConnectAsync()
                 return connection
             }

For task I get:

The value of constructor 'task' is not defined.

So, what is this and how can I define it?
Comment: This code is likely to be referencing one of the (many) TaskBuilder implementations available.  At some point a standard version will likely by added to F# (see @Caramirel's link)
Comment: A task computation builder: https://github.com/fsharp/fslang-suggestions/issues/581 and https://learn.microsoft.com/en-us/dotnet/fsharp/language-reference/computation-expressions
Answer: I assume that the question is in the context of Logary, which gets the task computation builder from the TaskBuilder.fs NuGet package (as we can see from Paket references). The TaskBuilder.fs project is available here with some documentation.
So, task is a variable that represents an instance of the TaskBuilder computation builder. This is an F# computation expression, which lets you create computations that create the .NET Task<T> type as the result. Inside the computation expression, you can use let! and do! for the same purpose as await in C#, that is for waiting until some asynchronous operation completes (without blocking a thread):
task {
  do! Console.Out.WriteLineAsync("Enter a filename:")
  let! name = Console.In.ReadLineAsync()
  use file = File.CreateText(name)
  for i in Enumerable.Range(0, 100) do
    do! file.WriteLineAsync(String.Format("hello {0}", i))
  do! Console.Out.WriteLineAsync("Done")
  return name
}

Here, WriteLineAsync and ReadLineAsync are .NET methods that return Task and we can use them as if they were returning just string or unit.
It is also worth adding that Logary is perhaps not the easiest piece of F# code to look into. It is very clever and nice, but relies on the HOPAC concurrency library which requires a fair bit of background knowledge and uses a number of fancy operators, which can make code quite tricky to understand. So if you are relatively new to F#, understanding HOPAC code might be a bit of a struggle!

What is 'task' in F#?


Datatables - after first button click the button is no longer responsive in each row. How to fix?

Question: I have a datatable called skiTable.  It consists of rows of ski mountains.  In each row, there is a button called FlyTo with latitude and longitude (aa_x, aa_y).  When clicked it zooms into the ski mountain using mapbox gl js (map.flyTo).  Once the map is zoomed in, I then use map.queryRenderedFeatures() to return data to datatable of just the displayed mountain in aDemoItems.  Sometimes there can be surrounding mountains and therefore the row count can be anywhere from 1 mountain to 10 mountains.
On the first initiation of the datatable, clicking the FlyTo button works fine, however, none of the buttons work after the first click.  Dead.  Here is the button's click event handler;
        $('#ski_index').on('click', 'button', function () {
            var data = skiTable.row($(this).parents('tr')).data();
            x = data.properties["aa_x"];
            y = data.properties["aa_y"]
            map.flyTo({center: [x, y], zoom: 15});
        });

Again, the data for the datatable comes via mapbox's map.queryRenderedFeatures() which is stringified (JSON.stringify(uniqueFeatures)) and passed to datatables as data:           aDemoItems.
let skiTable =      $('#ski_index').DataTable({
            stateSave:      true,
            stateDuration:  60 * 60 * 48, // save the state for 2 days.
            responsive:     true,
            info:           true,
            destroy:        true,
            data:           aDemoItems,
            dataType:       'json',
            "columns": [{
                    data: "properties.name",
                    "defaultContent": "Not set",
                    render: function (data, type, row){
                        return '<button>FlyTo</button>'
                    }
                }];
           });

Everything works well except any second click on the button FlyTo doesn't respond.  As I zoom in and out of the map, the datatable shows only the ski mountains displayed.  Any help much appreciated to get the button working from the second click.
I just realized this is a error message on the second click of the FlyTo button as follows;
Uncaught TypeError: Cannot read properties of undefined (reading 'properties')

If I add console.log(row) to the column definition as follows;
                {
                    data: "properties.name",
                    "defaultContent": "Not set",
                    render: function (data, type, row){
                        console.log(row);
                        return '<button>Click!</button>'
                    }
                },

... the console.log(row) does show properties with values in aa_x and and aa_y.
Answer: It seen this line  var data = skiTable.row($(this).parents('tr')).data(); caused the error because "data" is undefined, Did you try destroy and reinitialize whole the datatable like this https://datatables.net/forums/discussion/44956/how-to-destroy-and-reinitialize-the-datatable
Comment: Thanks. Why would data be undefined there? Not sure where to clear and destroy and initialize. I tried var tableId = "#skiTable"; if(skiTable!=null){ skiTable.clear(); skiTable.destroy(); } $(skiTable + " tbody").empty(); $(skiTable + " thead").empty(); let skiTable = $('#ski_index').DataTable({... But of course I get Cannot access 'skiTable' before initialization. Any ideas. thank you.
Comment: //Destroy the old Datatable
$('#skiTable').DataTable().clear().destroy();

//Create new Datatable
$('#skiTable').DataTable({...})
Comment: I have //Destroy the old Datatable   $('#skiTable').DataTable().clear().destroy();
 $('#ski_index').DataTable({...}) but get error Cannot read properties of undefined (reading 'properties').  No getting how this is to work unfo.
Comment: you try logging by console $('#ski_index').DataTable() to data
Comment: Cannot get it working.  Where would I put the destroy code?
Comment: @spreaderman when you update data of DataTable
Answer: Strange, I took parts of both mark_b and buithienquyet and some other suggestion from datatables forum to make a solution.  I changed the datatables source to ajax as per buithienquyet's suggestion and used $('#ski_index').DataTable().ajax.reload();  In the click handled I needed to add 'off' as follows:  $('#ski_index tbody').off( 'click', 'button').on( 'click', 'button', function () {}.
Answer: Use safe operator ?.properties?.name if possible
Javascript now supports safe operator.

or If you can use function instead of string and pass parameters:
...
data: (params) => {
    if(params) {
        return "properties?.name";
    }
},
...

Comment: sorry, not understand you comment.  The problem I have is that the first time I click a button, it works but the second time not.
Answer: Try not to use the table destroy methods, which in my experience cause more problems than they solve, and are rarely needed unless you want to change some of the table structure, such as the number of columns.
Instead make use of the ajax.reload() method to refresh the data in your table. You say that your data is coming from an external source, which likely means you cannot directly apply it to your table. To solve this, define your ajax property in the table options as a function like this (also store your table as a variable):
let my_array = [];

const skiTable = $('#ski_index').DataTable({
    ajax: function(data, callback) {
        callback({ data: my_array })
    }
});

Next grab your data, do whatever ajdustments you need to do to it, and store the results in my_array.
my_array = some_new_data;

Now you can call the reload() function to refresh the data in your DataTable
skiTable.ajax.reload();

Comment: the data is not being load with ajax so reload will not work.
Comment: @spreaderman Perhaps I did not explain myself properly. If you update a local javascript array with some new data, you can use the `ajax.reload()` function to refresh your table as I explained above. You don't need to actually use Ajax.
Comment: So how would you reload if the data is not ajax? The data comes from aDemoData = map.queryRenderedFeatures(); which is triggered each time the map zooms in and out and retrurns the data in view.  Possible to show more code how that would work please?
Comment: I think I am getting you now.  Sorry.                  ajax:           function(data, callback) {
                                    callback({ data: aDemoItems })
                                }, works to bring in the data.  I placed   skiTable.ajax.reload(); in   $('#ski_index tbody').on( 'click', 'button', function () {} at the end but get same error DataTables warning: table id=ski_index - Cannot reinitialise DataTable


Pegar imagem dentro da pasta storage

Question: Estou fazendo o upload de imagens na pasta storage, app/public, dentro desta criei uma pasta /banners e estou fazendo o upload dessas imagens dentro desta pasta.
Como posso pegar essas imagens e exibir na view?
Comment: A versão do Laravel é 5.2 mesmo?
Comment: Sim essa mesmo.
Comment: a resposta não foi satisfatório, precisa entender mais alguma coisa, tem algo a dizer?
Answer: Crie um link simbólico dentro da pasta /public. Como criar link simbólico, exemplos aqui no SOPt?:

Como listar os links simbólicos de uma pasta no Linux?
Linux - Link Simbolico + Dropbox
Como criar um link simbólico para um código em Python no Linux?

Todos os exemplos são para linux bash e no Windows desde o Windows Vista é possível criar com o comando mklink:
Sintaxe

MKLINK [[/d] | [/h] | [/j]] <Link><Target>

Parâmetros

/d Cria um link simbólico do diretório. Por padrão, o mklink cria um
  link simbólico do arquivo.
/h Cria um vínculo real em vez de um vínculo simbólico.
/j Cria uma junção de diretório.
<Link> Especifica o nome do vínculo simbólico que está sendo criado.
<Target> Especifica o caminho (relativo ou absoluto) ao qual se refere o novo vínculo simbólico.
/? Exibe a Ajuda no prompt de comando.

Referencia: Microsoft TechNet -  MKLINK

Na versão laravel-5.3, com o comando php artisan storage:link cria um link simbólico para a pasta public/storage.

Observação: no Windows desde do Vista pode criar link simbólico com o comando mklink
Referencias:

Link Simbólico e HardLink
Filesystem / Cloud Storage
Criando Links Simbólicos no Windows com Mklink
Criando Link Simbólico no Windows
Criando links simbólicos no Windows
Answer: Uma forma mais simples seria:
asset("storage/app/public/banners/banner.png");

Pegar imagem dentro da pasta storage


Independence of transformed variables

Question: There are two independent variables X and Y. Y is an input for non deterministic algorithm f, and the output of f(Y) is Z. How to prove that X and Z are independent?
Comment: You have to specify in what way $f$ is non deterministic. Why can't $f(Y)=X+Y$ for example? Do you mean that $f$ is non deterministic and independent of $X$?
Answer: Let $X,Y$ (real-valued) random variables on a probability space $(\Omega,\mathcal{A},\mathbb{P})$ and $f: \mathbb{R} \to \mathbb{R}$. Then
$$\begin{align*} \mathbb{P}[X \in B, Z \in C] &= \mathbb{P}[X \in B, Y \in f^{-1}(B)] = \mathbb{P}[X \in B] \cdot \mathbb{P}[Y \in f^{-1}(B)] \\ &= \mathbb{P}[X \in B] \cdot \mathbb{P}[Z \in C] \end{align*}$$
for Borel sets $B,C$. This proves the independence of $Z=f(Y)$ and $X$. (Note that $f^{-1}(B)$ denotes the preimage of $B$ under $f$, there does not necessarily exist a inverse function.)

Independence of transformed variables


Getting error 'Redirects to external URLs are not allowed by default'

Question: Getting the error after created this .htacces in root folder.
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} !^/web
RewriteRule ^(.*)$ /web/
I want to redirect visitors to /web folder. I can login as Admin and enable modules, install themes and create content without any issues.
When a theme is installed, content created and publish it I get a blankpage with:
"Redirects to external URLs are not allowed by default, use \Drupal\Core\Routing\TrustedRedirectResponse for it."
I have trusted hostsettings configured like this in settings.php
$settings['trusted_host_patterns'] = array(
  '^my-domain\.com$',
  '^my-domain\.com\.web$',
  '^.+\.my-domain\.com$',
  '^.+\.my-domain\.com\.web$',
according to this issue uncomment RewriteBase / didn't work out either
Hope someone has a solution to this.
Answer: If you still haven't figured this out, check this comment on d.o: https://www.drupal.org/project/drupal/issues/2612160#comment-11767977
It suggests a workaround by removing the subdir from the script name, adding to settings.php the following:

if (isset($GLOBALS['request']) and
'/subdirectory/index.php' === $GLOBALS['request']->server->get('SCRIPT_NAME')) {
$GLOBALS['request']->server->set('SCRIPT_NAME', '/index.php');
}

Answer: You should change move the content of web to the root directory,
this a step by step to do it.
https://tecnovatorexperts.com/articles/fixing-drupal-redirect-error-how-use-trustedredirectresponse-external-urls
Comment: Welcome to Drupal Answers! Whilst this may theoretically answer the question, [it would be preferable](//meta.stackoverflow.com/q/8259) to include the essential parts of the answer here, and provide the link for reference.


Lateral surface area of a region

Question: This question stumped me on a recent calculus test... I would really like an explanation.
The region $\mathbf{R}$ is bounded by
\begin{equation*}
h(x) = -0.8(x-2)^2 + 8~\text{and}~p(x) = x\cos(x) - \ln(2x+2).
\end{equation*}
Find the lateral surface area of the solid formed when $\mathbf{R}$ is revolved around the line $y=11$.
I tried to convert both functions into terms of y so that I could get the arc length, but that didn't get me very far. Any help would be greatly appreciated.
Comment: Was an exact answer expected? Or a numerical approximation was enough?
Comment: We had calculators, so a numerical approximation.
Answer: First, let's shift the functions down so that instead of revolving about $y=11$, we're revolving about the x-axis, $y=0$: $h_1(x)=h(x)-11$, $p_1(x)=p(x)-11$.  Let $a< b$ be the x-coordinates of the points of intersection of $h_1(x)$ and $p_1(x)$ (in the vicinity of -2 and 5)--that is, the least and greatest x-coordinates of any points in $\mathbf{R}$.  There are two lateral surface areas to compute: the "inner" part bounded by $h_1$, and the "outer" part bounded by $p_1$.  For each, the surface area is given by $\int_{a}^{b}2\pi y(x)\sqrt{1+(y'(x))^2}dx$, replacing $y$ with $h_1$ or $p_1$ (and $y'$ with its derivative) as appropriate.

Lateral surface area of a region


Upper Bound on the shortest non-zero non-negative vector in an integer lattice

Question: Suppose we have an integer lattice of full rank $L\subseteq\Bbb{Z}^n$, say of determinant $D$.
Do we have a nice bound on the smallest non-zero vector $x\in L$ s.t. $x_i\geq0$ for all $i$? Perhaps using the determinant?
From Minkowski's theorem, we know that there is an $x\in L$ s.t. $||x||_\infty \leq D^{1/n}$, but $x$ might not be non-negative.
My best guess would be that there is a constant $c\geq 1$ (that might depend on $n$) s.t. $||x||_\infty \leq cD^{1/n}$, here is an example of a heuristic I cannot make formal:
Let $B=[0,cD^{1/n}]^n$, since $B$'s volume is greater than that of the fundamental parallelogram of $L$ we need at least two of them to cover $B$. Hence there are two fundamental parallelograms of $L$ that intersect inside $B$ and so there must be a non-zero element $x\in L\cap B$ so $||x||_\infty \leq cD^{1/n}$
Answer: The answer is no, which we can see already for $n=2$. Let $v_1=(1,1)$ and $v_2=(1,-1)$ (so that $v_1 \perp v_2$), and consider the lattice spanned by $Mv_1$ and $v_2$, where $M$ is a large positive integer. This lattice has determinant $2M$, but the shortest vector nonzero vector in the positive quadrant is $Mv_1$ itself which has infinity-norm equal to $M$.
Comment: But the lattice $L$ is a sublattice of $\Bbb{Z}^n$ so you cannot divide by large $M$
Comment: Thanks for pointing out that I misread the problem. I'll update my answer now.


Muting during tapping

Question: When playing tapping licks that involve string skips or lots of movement between strings, how are you supposed to mute the other strings? The strings above the note being played can be muted with the fretting hand, but below that note I no longer can use my palm for muting.
I've tried using the unused fingers to mute but this only works with very specific patterns.
Is there any way to mute with my hands or do I have to keep hair bands around the neck?
Comment: This is something that I've struggled with from my bass.  Hair bands are not big enough to mute for the bass as effectively as I'd like.  This product seems promising and at the price point, I may just give it a try even though I don't tap very much. https://reverb.com/item/437090-gruv-gear-fret-wraps-hd-large-single-sky?_aid=pla&pla=1&gclid=CjwKEAjwtLO7BRDax4-I4_6G71USJAA6FjN1KyQlpB8-YFfSy5OtPDUgvoc3ATB8Y69S3ltl86urURoC2-Dw_wcB
Answer: Fret wraps (or hair bands, basically anything that can wrap around a fretboard and mute the strings) are used to mute the open strings while performing a tapping passage. They are placed around the strings near the nut of the instrument to prevent the open strings from sounding. This limits the use of open strings during performance.
A sponge mute can also be placed, either under the strings at the nut or bridge. This is used more commonly with bass players to achieve a more "thumpy" sound.
Comment: Isn't the OP aware of this, as mentioned in the question?
Comment: "is there any way to mute with my hands or do i have to keep hair bands around the neck." I guess my answer boils down to, use hair bands/fret wraps, consider sponge. Muting strings in the manner the OP asks is nigh on impossible. :)
Answer: I think I've (almost) found a solution, at least for situations involving just one tapping finger. it involves using the palm to mute similar to normal playing. the trick is to instead aiming for the very tip of the tapping finger and pulling off towards the adjacent string, hammer-on very slightly below the string and pull of upwards. i got the idea from andy mckee talking about how some acoustic players pull off more upwards than side ways. as a side benefit the tapping finger now has no chance of bumping the next string with the pull off.
the only problem is it doesn't seem to work for the string right next to the tapped note as that puts the tapping finger at an odd an uncomfortable angle. this also doesn't work with tapping for 2 or more fingers nearly as well as it works with one. but for situations were it can be used it drastically improves string skipping runs.

Muting during tapping


Traffic shaping L2TP/IPsec VPN (via accounts not connection)

Question: I need to be able to control the amount of bandwidth a specific user account can use on a VPN connection. One account I want to be able to use the VPN with no restrictions and another account I want to limit to a reasonable amount of bandwidth (say 10GB or so a month).
I'm aware that you can traffic shape individual connections but that does not quite solve the problem as the limited account can just disconnect and reconnect to get a new connection. I need to be able to limit bandwidth on a login basis for a given period of time (monthly limit).
I'm really not that familiar with traffic shaping in general so any advice would be appreciated.
Thank you.
Comment: In chap-secrets file set static IPs for clients and use some 3rd party software to control that traffic.
Comment: As it stands this doesn't really answer the question. Can you elaborate how to accomplish this with either an example or more specific steps?
Comment: There is nothing to elaborate. File located in /etc/ppp/chap-secrets open it and you will see example right there. Set ip for VPN user. Your future steps are to find desired traffic control software, like this: [link](http://www.funtoo.org/wiki/Traffic_Control) Manipulate with users IP addresses you defined in chap-secrets file, they wont get any other IP after relogin. OR set up abills+radius server+your vpn
Comment: You appear to be equating traffic shaping (limiting speeds in various situations) with download/upload limiting (limiting the amount someone can transfer in a given amount of time). To help decide which you need, answer these questions: 1) If I'm a limited account and I have yet to download 10GB this month, how should my connection behave? 2) If I'm a limited account and I have downloaded 10GB this month, how should my connection behave?
Comment: @hrunting OK I guess I mean bandwidth limiting rather than traffic shaping.
Comment: What are you using to build the VPN? Is it Cisco hardware, Microsoft software, Linux or BSD?
Comment: @krugger Linux. Debian 6 or Ubuntu Server 12.04 LTS.
Answer: I wouldn't call it "traffic shaping" with a time resolution of one month... You do not want to impose any restrictions before this hard limit is reached? I think you need to watch the traffic and disable the account when the limit is reached (or activate traffic shaping then, making the connection quite slow).
You may add rules (without target) for each of the connections (after configuring static addresses as mentioned before) in order to see the amount of traffic from and to this user. Every hour or so you can call a script / program which reads this amount of data, adds it to the user's traffic log, resets the counter (iptables --zero), sum up the traffic log and take the appropriate action if the user's limit turnes out to be reached.


Ubuntu Server apt-get upgrade - will it downgrade PHP?

Question: I have PHP 5.3 installed on an Ubuntu Server using the Debian packages.
I've just run the commands apt-get update and apt-get upgrade - the latter wishes to upgrade certain PHP5 related packages "without verification".
If I let it, will this downgrade my PHP 5.3 installation down to PHP 5.2?
Answer:
If I let it, will this downgrade my PHP 5.3 installation down to PHP 5.2?
  No, because the installed version is newer. You may hold packages:

sudo echo "package_name" hold | sudo dpkg --set-selections


$\pi$, $e$, $\phi$, and sunflowers

Question: While reading some internet materials on design, I came across this picture and comment:

I found it a little bit surprising. I knew that the real sunflower follows golden ratio in some way (but I don't know the details). But how come the patterns for $\pi$ and $e$ are still "periodic", but different? What affects "sparseness" of the pattern? Is there any tool to display the sunflower pattern for different values of the "constant" that generates it?
Are the claims in the picture and in its comment for real at all?
What is the math background beyond all this?
Is the resulting shape different for rational and irrational numbers? What about transcendent numbers?
NOTE: I just saw there is a mistake (most likely a typo) in the picture: $1.681$ should be $1.618$, right?
Comment: Surely it is a biology question how it follows the golden ratio.
Comment: A good reference is http://en.wikipedia.org/wiki/Golden_ratio. See section 3.7 and the references given there.
Answer: This is pure biomathematical misinformed popularization. These famous constants have no more reason to appear than any other real value, and even if they did, this could be approximately true to the first or second decimal and unverifiable for the next.
The pseudo-fitness of $\phi$ as shown on the figure is just due to a smaller value of the constant, resulting in better compactness. And there is no other "periodicity" than that caused by the revolution (actually, there is no periodicity at all, these are spirals).
Besides that, there is a rationale for the golden ratio to appear in nature, due to its relation to the Fibonacci numbers ($F_n=F_{n-1}+F_{n-2}$): when a physical process involves this recurrence (like in reproduction of rabbits, unlike the pattern of sunflowers), the golden ratio is there in the limit. It also appears with rotational symmetry of order 5 (which, by the way, is known to be impossible as a symmetry order in crystals). Note that any recurrence with integer coefficients can only generate algebraic numbers.
$\pi$ can appear if you roll out the skin of a cylinder of revolution.
I can't think of a simple process that would generate $e$. (Exponential curves arise in many situations in the frame of linear systems, but the basis has no reason to be specifically $e$.)
Last but not least, there is no real relation between aesthetics and the golden ratio, this is folklore. No one would notice a difference between $\phi$ proportions and, say $1.6$ or $\sqrt3$ or $e-1$.
Comment: I assume you've seen Markowsky's [Misconceptions about the Golden Ratio](http://www.umcs.maine.edu/~markov/GoldenRatio.pdf)? He debunks a number of popular beliefs about the golden ratio such as how esthetically pleasing the golden rectangle is, its appearance in the human body, and alleged use in antiquity. The occurrence of the golden ratio in phyllotaxis is *not* addressed. Certainly, one can adjust the golden angle by some small but positive amount and generate similar patterns. But the connection with Fibonacci numbers (which do occur in nature) is real.
Comment: @MarkMcClure Can you explain this connection ?
Comment: The connection between the Fibonacci numbers and the golden ratio that I alluded to? Yes, I can explain that. I suspect that you mean the mysterious occurrence of the golden ratio in nature. My belief is that $\pi$, $e$, and $\phi$ all appear so frequently because they arise in the solutions of simple equations with small, integer coefficients: $y''=-y$, $y'=y$, and $x^2-x-1=0$. You allude to a similar phenomenon with Fibonacci numbers. Not so mysterious. :)
Comment: @MarkMcClure No I allude to your statement that Fibonacci numbers do occur in nature, while you describe no single instance of that. In what specific phenomenon are there Fibonacci numbers (besides the Rabbit population scenario) or the Golden Ratio ?
Comment: I'm not at all under the impression that every plant has a Fibonacci number of leaves or seeds or any such nonsense. As Coxeter said, "We must face the fact that phyllotaxis is really not a universal law but only a fascinatingly prevalent tendency". But even a tendency, along with a reasonable mathematical basis (such as economy of packing), is intriguing.
Comment: In my understanding, Fibonacci-like phyllotaxis needn't have a very accurate ratio.
Answer: How are the patterns for a number $a$ generated? Plot the points with polar coordinates $r=r_0\cdot c^n$, $\theta = \theta_0+n\cdot a\cdot 2\pi$ for $n=1,2,\ldots$, where $c$ is a suitable constant just slightly below $1$ (or above $1$ if wyou want the pattern to grow from inside to outside)
Even though it is not transcendent, $\phi$ is the "most irrational number", and that's what ultimately causes the pattern to be most efficient (and pleasing).
The statement "most irrational" can be made more precise with the use of continued fractions.
Patterns for rational $a=\frac uv$ would look like a straight "windmill" with $v$ wings. The pattern for $\pi$ looks almost like a straight windmill with $7$ wings. That's from the famous approximation $\pi\approx\frac{22}7$.
Comment: There are not enough turns for the rational/algebraic/transcendent character of these numbers to clearly appear. The "pleasing" aspect of the figure is probably more due to Moiré patterns rather than any "efficiency property". The difference in the effects of the different constants are more due to the curve slope (order of magnitude, first digit of the constant) and density (chosen arbitrarily by the artist to support his claim).
Answer: These kind of patterns comes from biological activities as cell division. The spiral form come from a method of growth and development and the pattern on the curved surface of the base of the composite seems to be the first surface-filling spiral pattern.
The seeds creates in the center and grows bigger as the surface grows wider in a time varying surface filling pattern.
It's masterful geometry.

$\pi$, $e$, $\phi$, and sunflowers


How can I programatically prevent users from saving the same entity twice in a row?

Question: My server sometimes gets overloaded, and sometimes people press the "Save" button on an entity creation page several times, which results in multiple versions of the same entity being created.
So, I want to prevent users from saving the same entity (an entity that has the exact same field content as the immediately previous entity saved by the user).
One fix is to get a better server.  I'm working on that.
Still, I would like to programmatically prevent users from saving the exact same entity twice in a row.  In my specific use case, this entity is a new private message from the Private Message module.
Is there a "best practice" way to do this?
Here is what I have considered.

On hook_entity_presave(), query the database and check if the last entity saved by the user had the same values.
Add an entity reference to the user profile for the last saved entity, and update the user profile entity reference field with the value of the new entity every time it is saved.  When saving a new entity, check it against the values of the entity reference entity.
Answer: I find this to be a UX issue. 1 thing I would recommend is to allow certain high-traffic forms on your site to show a throbbing/progress/submit indicator upon click.
I believe you can do this using the Form API by overridding the default submit element on your site forms as needed. This is explained some in this related SO post with links to documentation:
https://stackoverflow.com/questions/6100970/how-do-you-remove-the-throbber-from-drupal-7-ajax-link
Comment: Follow-up question: https://drupal.stackexchange.com/questions/198956/how-can-i-programatically-add-the-default-ajax-throbber-to-a-form-submit
Answer: You can use jQuery to change the save button to a loading gif when the save button is clicked. Thus, preventing any more clicks.
(function($) {
  $('.form-submit').click(function() {
     $('.form-submit').html('');
  });
})(jQuery);

JS Fiddle Example
When you edit nodes it uses the admin theme (seven), so you need to add the jQuery to the admin theme (seven).
Now I don't know if private message uses the admin theme. So you will have to check that. My guess it that it does, but if it doesn't, then you add the jQuery to your theme rather than the admin theme (seven)

Note: The default admin theme for Drupal 7 is "Seven", if you have changed your admin theme, then just edit that theme instead.
Answer: This seems to be a classic question in the drupal world, did you search already for similar posts?
Here is what my research provided:
This is a two-fold issue, you can start by working on the Client-Side, but to avoid duplicates, you should ultimately work on the Server-Side.
Here are what I found to be the "best practice" ways to go about this problem.
Client-Side:
Client-side solution:
https://www.drupal.org/project/hide_submit
But what if the javascript is not there?
Server-Side:
Closer to the direction you started out with:
https://drupal.stackexchange.com/a/152181/57183
I would apply both approaches, starting with the "Server-Side" approach.
Good luck!


XP_CMDSHELL how to capture return value?

Question: I need to write an console application that returns a return code that can be captured through xp_cmdshell.
I started with c# code as follows,
class Program
    {
        static int Main(string[] args)
        {
            //make sure the correct number of arguments are being passed.
            if (args.Length !=5)
            {
                Console.WriteLine("not thr right number of args. \nUsage SFTPUploadFile <host> <port> <username> <password> <localFilePath>");
                return 1;
            }

            return 0;
        }

    }

The XP_cmdhsell I am using some code I found
declare  @rc int

create table #output (id int identity(1,1), output nvarchar(255) null)
insert #output (output) exec @rc = master..xp_cmdshell 'd:\FILENAME PARA1 PARA2 PARA3 PARA4 PARA5'
select * from #output where output is not null order by id
drop table #output

but when I run my xp_cmdshell, I just get null.  Shouldn't I be getting 1 or 0?
Thanks
Comment: You probably should add your call to `xp_cmdshell` and how you verify its value.
Answer: It looks like your program checks to see whether or not there are 5 parameters, and does nothing (returns 0) if there are.
The xp_cmdshell command, in turn, supplies all the parameters. xp_cmdshell will return NULL if it does not receive any output.
If you changed the code to read something like this:
class Program
    {
        static int Main(string[] args)
        {
            //make sure the correct number of arguments are being passed.
            if (args.Length !=5)
            {
                Console.WriteLine("not thr right number of args. \nUsage SFTPUploadFile <host> <port> <username> <password> <localFilePath>");
                return 1;
            }

            Console.WriteLine("You had the right number of args.");
            return 0;
        }

    }

(Alternatively, you can do Console.WriteLine("0"); and Console.WriteLine("1"); if you really want 0 or 1 back.)
You'd get back You had the right number of args.. This is because return 0; and return 1; do not print anything out to the console, which is what xp_cmdshell will send back to the client.
You can prove this by doing EXEC master..xp_cmdshell 'cd ..' ... it's a command that does not return results. On the other hand, EXEC master..xp_cmdshell 'dir *.exe' will return you the directory contents, as this is what would be output (or written) to the console.
Comment: on my local it actually outputs the success or error messages.  But on the production server it just returns null or both cases... could there be a permission issue?
Comment: You're right - xp_cmdshell runs under your username / password when attempting to run (and you're a sysadmin), otherwise it will use the proxy user. You (or the proxy user) may or may not have the right permissions on the server in production to see a result. More can be found [here](http://msdn.microsoft.com/en-us/library/ms175046.aspx)


Como retirar commits indevidos de uma branch remota?

Question: A empresa em que trabalho contrata alguns estagiários que cuidam de tasks pequenas de varias linguagens e diferentes partes do programa (afim de capacita-los), porém recentemente um dos nossos estagiários fez alguns commits de uma branch em outra no nosso repositório remoto, afim de não excluir a branch, recria-la e fazer as mudanças em alguns commits para maquiar isso, gostaria de saber se existe algum método de:

"Reescrever" os commits, ignorando aqueles que
não tem nexo com a branch, refazendo o histórico da branch remota.
Guardar as alterações feitas nos commits na branch errada, para que no futuro sejam colocadas na branch correta
Manter o histórico com as alterações na data e hora certa

Estou trabalhando com bitbucket e TortoiseGit.
Answer: Me parece um caso onde revert e cherry-pick podem ser bem usados, sem os branches não forem tão diferentes entre si.
Pegue no histório os hashes dos commits feitos no branch errado e faça uma lista.
Depois ainda no branch errado faça: git revert <hash> para cada um na ordem inversa (do mais recente pro mais antigo). Isso vai fazer com que o código seja removido do branch errado sem reescrever o histórico, mantendo as alterações como foram - vai criar um commit revertendo cada um dos errados.
Quando tiver o branch novo onde as alterações devem ser aplicadas basta fazer git cherry-pick <hash> para cada um dos hashes na ordem certa (do mais antigo pro mais recente). Isso vai aplicar as alterações exatamente como foram feitas no outro branch.
Comment: Acho que vale a pena colocar um adendo para commits mortais, como enviar a senha do banco sem querer no arquivo
Comment: A pergunta falava em manter o histórico e guardar as alterações, não parece ser o caso. A única coisa realmente segura a fazer quando se envia a senha do banco pro GIT é trocar a senha do banco.
Comment: Bem, isso é verdade, mas as vezes a gente faz bobeira e precisa reescrever o histórico. Eu sei que isso é além do que foi pedido pelo @Paz, mas é algo que eu sempre acho importante citar, por neurose mesmo. O GitHub tem [uma postagem sobre esse assunto](https://help.github.com/articles/removing-sensitive-data-from-a-repository/)