Problemas ao utilizar Dropzone.js em um formulário

Question: Estou querendo adicionar campos à um formulário que utiliza o Dropzone.js para fazer o upload de arquivos.

Quando adiciono os arquivos para upload, a tela fica assim:

var Galerias = function () {

    return {
        //main function to initiate the module
        initForm: function() {

            Dropzone.options.myDropzone = {
                autoProcessQueue: false,
                uploadMultiple: true,
                previewsContainer: ".dropzone-previews",
                clickable: ".dropzone-previews",
                parallelUploads: 100,
                maxFiles: 100,
                maxFilesize: 5, // mb
                init: function() {
                    this.on("addedfile", function(file) {
                        // Create the remove button
                        var removeButton = Dropzone.createElement("<button class='btn btn-xs red btn-block'>Excluir</button>");

                        // Capture the Dropzone instance as closure.
                        var _this = this;

                        // Listen to the click event
                        removeButton.addEventListener("click", function(e) {
                          // Make sure the button click doesn't submit the form:
                          e.preventDefault();
                          e.stopPropagation();

                          // Remove the file preview.
                          _this.removeFile(file);
                          // If you want to the delete the file on the server as well,
                          // you can do the AJAX request here.
                        });

                        // Add the button to the file preview element.
                        file.previewElement.appendChild(removeButton);
                    });
                }
            }

        }
    };
}();
/* The MIT License */
.dropzone,
.dropzone *,
.dropzone-previews,
.dropzone-previews * {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}
.dropzone {
  position: relative;
  border: 1px solid rgba(0,0,0,0.08);
  background: rgba(0,0,0,0.02);
  padding: 1em;
}
.dropzone.dz-clickable {
  cursor: pointer;
}
.dropzone.dz-clickable .dz-message,
.dropzone.dz-clickable .dz-message span {
  cursor: pointer;
}
.dropzone.dz-clickable * {
  cursor: default;
}
.dropzone .dz-message {
  opacity: 1;
  -ms-filter: none;
  filter: none;
}
.dropzone.dz-drag-hover {
  border-color: rgba(0,0,0,0.15);
  background: rgba(0,0,0,0.04);
}
.dropzone.dz-started .dz-message {
  display: none;
}
.dropzone .dz-preview,
.dropzone-previews .dz-preview {
  background: rgba(255,255,255,0.8);
  position: relative;
  display: inline-block;
  margin: 17px;
  vertical-align: top;
  border: 1px solid #acacac;
  padding: 6px 6px 6px 6px;
}
.dropzone .dz-preview.dz-file-preview [data-dz-thumbnail],
.dropzone-previews .dz-preview.dz-file-preview [data-dz-thumbnail] {
  display: none;
}
.dropzone .dz-preview .dz-details,
.dropzone-previews .dz-preview .dz-details {
  width: 100px;
  height: 100px;
  position: relative;
  background: #ebebeb;
  padding: 5px;
  margin-bottom: 22px;
}
.dropzone .dz-preview .dz-details .dz-filename,
.dropzone-previews .dz-preview .dz-details .dz-filename {
  overflow: hidden;
  height: 100%;
}
.dropzone .dz-preview .dz-details img,
.dropzone-previews .dz-preview .dz-details img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100px;
  height: 100px;
}
.dropzone .dz-preview .dz-details .dz-size,
.dropzone-previews .dz-preview .dz-details .dz-size {
  position: absolute;
  bottom: -28px;
  left: 3px;
  height: 28px;
  line-height: 28px;
}
.dropzone .dz-preview.dz-error .dz-error-mark,
.dropzone-previews .dz-preview.dz-error .dz-error-mark {
  display: block;
}
.dropzone .dz-preview.dz-success .dz-success-mark,
.dropzone-previews .dz-preview.dz-success .dz-success-mark {
  display: block;
}
.dropzone .dz-preview:hover .dz-details img,
.dropzone-previews .dz-preview:hover .dz-details img {
  display: none;
}
.dropzone .dz-preview .dz-success-mark,
.dropzone-previews .dz-preview .dz-success-mark,
.dropzone .dz-preview .dz-error-mark,
.dropzone-previews .dz-preview .dz-error-mark {
  display: none;
  position: absolute;
  width: 40px;
  height: 40px;
  font-size: 30px;
  text-align: center;
  right: -10px;
  top: -10px;
}
.dropzone .dz-preview .dz-success-mark,
.dropzone-previews .dz-preview .dz-success-mark {
  color: #8cc657;
}
.dropzone .dz-preview .dz-error-mark,
.dropzone-previews .dz-preview .dz-error-mark {
  color: #ee162d;
}
.dropzone .dz-preview .dz-progress,
.dropzone-previews .dz-preview .dz-progress {
  position: absolute;
  top: 100px;
  left: 6px;
  right: 6px;
  height: 6px;
  background: #d7d7d7;
  display: none;
}
.dropzone .dz-preview .dz-progress .dz-upload,
.dropzone-previews .dz-preview .dz-progress .dz-upload {
  display: block;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  width: 0%;
  background-color: #8cc657;
}
.dropzone .dz-preview.dz-processing .dz-progress,
.dropzone-previews .dz-preview.dz-processing .dz-progress {
  display: block;
}
.dropzone .dz-preview .dz-error-message,
.dropzone-previews .dz-preview .dz-error-message {
  display: none;
  position: absolute;
  top: -5px;
  left: -20px;
  background: rgba(245,245,245,0.8);
  padding: 8px 10px;
  color: #800;
  min-width: 140px;
  max-width: 500px;
  z-index: 500;
}
.dropzone .dz-preview:hover.dz-error .dz-error-message,
.dropzone-previews .dz-preview:hover.dz-error .dz-error-message {
  display: block;
}
.dropzone {
  border: 0;
  min-height: 360px;
  -webkit-border-radius: 0;
  border-radius: 0;
  background: rgba(0,0,0,0.03);
  padding: 0;
}
.dropzone-previews {
  border: 1px solid rgba(0,0,0,0.03);
  min-height: 360px;
  -webkit-border-radius: 3px;
  border-radius: 3px;
  background: rgba(0,0,0,0.03);
  padding: 23px;
}
.dropzone .dz-default.dz-message {
  opacity: 1;
  -ms-filter: none;
  filter: none;
  -webkit-transition: opacity 0.3s ease-in-out;
  -moz-transition: opacity 0.3s ease-in-out;
  -o-transition: opacity 0.3s ease-in-out;
  -ms-transition: opacity 0.3s ease-in-out;
  transition: opacity 0.3s ease-in-out;
  background-image: url("../images/spritemap.png");
  background-repeat: no-repeat;
  background-position: 0 0;
  position: absolute;
  width: 428px;
  height: 123px;
  margin-left: -214px;
  margin-top: -61.5px;
  top: 50%;
  left: 50%;
}
@media all and (-webkit-min-device-pixel-ratio:1.5),(min--moz-device-pixel-ratio:1.5),(-o-min-device-pixel-ratio:1.5/1),(min-device-pixel-ratio:1.5),(min-resolution:138dpi),(min-resolution:1.5dppx) {
  .dropzone .dz-default.dz-message {
background-image: url("../email@example.com");
-webkit-background-size: 428px 406px;
-moz-background-size: 428px 406px;
background-size: 428px 406px;
  }
}
.dropzone .dz-default.dz-message span {
  display: none;
}
.dropzone.dz-square .dz-default.dz-message {
  background-position: 0 -123px;
  width: 268px;
  margin-left: -134px;
  height: 174px;
  margin-top: -87px;
}
.dropzone.dz-drag-hover .dz-message {
  opacity: 0.15;
  -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=15)";
  filter: alpha(opacity=15);
}
.dropzone.dz-started .dz-message {
  display: block;
  opacity: 0;
  -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
  filter: alpha(opacity=0);
}
.dropzone .dz-preview,
.dropzone-previews .dz-preview {
  -webkit-box-shadow: 1px 1px 4px rgba(0,0,0,0.16);
  box-shadow: 1px 1px 4px rgba(0,0,0,0.16);
  font-size: 14px;
}
.dropzone .dz-preview.dz-image-preview:hover .dz-details img,
.dropzone-previews .dz-preview.dz-image-preview:hover .dz-details img {
  display: block;
  opacity: 0.1;
  -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=10)";
  filter: alpha(opacity=10);
}
.dropzone .dz-preview.dz-success .dz-success-mark,
.dropzone-previews .dz-preview.dz-success .dz-success-mark {
  opacity: 1;
  -ms-filter: none;
  filter: none;
}
.dropzone .dz-preview.dz-error .dz-error-mark,
.dropzone-previews .dz-preview.dz-error .dz-error-mark {
  opacity: 1;
  -ms-filter: none;
  filter: none;
}
.dropzone .dz-preview.dz-error .dz-progress .dz-upload,
.dropzone-previews .dz-preview.dz-error .dz-progress .dz-upload {
  background: #ee1e2d;
}
.dropzone .dz-preview .dz-error-mark,
.dropzone-previews .dz-preview .dz-error-mark,
.dropzone .dz-preview .dz-success-mark,
.dropzone-previews .dz-preview .dz-success-mark {
  display: block;
  opacity: 0;
  -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
  filter: alpha(opacity=0);
  -webkit-transition: opacity 0.4s ease-in-out;
  -moz-transition: opacity 0.4s ease-in-out;
  -o-transition: opacity 0.4s ease-in-out;
  -ms-transition: opacity 0.4s ease-in-out;
  transition: opacity 0.4s ease-in-out;
  background-image: url("../images/spritemap.png");
  background-repeat: no-repeat;
}
@media all and (-webkit-min-device-pixel-ratio:1.5),(min--moz-device-pixel-ratio:1.5),(-o-min-device-pixel-ratio:1.5/1),(min-device-pixel-ratio:1.5),(min-resolution:138dpi),(min-resolution:1.5dppx) {
  .dropzone .dz-preview .dz-error-mark,
  .dropzone-previews .dz-preview .dz-error-mark,
  .dropzone .dz-preview .dz-success-mark,
  .dropzone-previews .dz-preview .dz-success-mark {
background-image: url("../email@example.com");
-webkit-background-size: 428px 406px;
-moz-background-size: 428px 406px;
background-size: 428px 406px;
  }
}
.dropzone .dz-preview .dz-error-mark span,
.dropzone-previews .dz-preview .dz-error-mark span,
.dropzone .dz-preview .dz-success-mark span,
.dropzone-previews .dz-preview .dz-success-mark span {
  display: none;
}
.dropzone .dz-preview .dz-error-mark,
.dropzone-previews .dz-preview .dz-error-mark {
  background-position: -268px -123px;
}
.dropzone .dz-preview .dz-success-mark,
.dropzone-previews .dz-preview .dz-success-mark {
  background-position: -268px -163px;
}
.dropzone .dz-preview .dz-progress .dz-upload,
.dropzone-previews .dz-preview .dz-progress .dz-upload {
  -webkit-animation: loading 0.4s linear infinite;
  -moz-animation: loading 0.4s linear infinite;
  -o-animation: loading 0.4s linear infinite;
  -ms-animation: loading 0.4s linear infinite;
  animation: loading 0.4s linear infinite;
  -webkit-transition: width 0.3s ease-in-out;
  -moz-transition: width 0.3s ease-in-out;
  -o-transition: width 0.3s ease-in-out;
  -ms-transition: width 0.3s ease-in-out;
  transition: width 0.3s ease-in-out;
  -webkit-border-radius: 2px;
  border-radius: 2px;
  position: absolute;
  top: 0;
  left: 0;
  width: 0%;
  height: 100%;
  background-image: url("../images/spritemap.png");
  background-repeat: repeat-x;
  background-position: 0px -400px;
}
@media all and (-webkit-min-device-pixel-ratio:1.5),(min--moz-device-pixel-ratio:1.5),(-o-min-device-pixel-ratio:1.5/1),(min-device-pixel-ratio:1.5),(min-resolution:138dpi),(min-resolution:1.5dppx) {
  .dropzone .dz-preview .dz-progress .dz-upload,
  .dropzone-previews .dz-preview .dz-progress .dz-upload {
background-image: url("../email@example.com");
-webkit-background-size: 428px 406px;
-moz-background-size: 428px 406px;
background-size: 428px 406px;
  }
}
.dropzone .dz-preview.dz-success .dz-progress,
.dropzone-previews .dz-preview.dz-success .dz-progress {
  display: block;
  opacity: 0;
  -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
  filter: alpha(opacity=0);
  -webkit-transition: opacity 0.4s ease-in-out;
  -moz-transition: opacity 0.4s ease-in-out;
  -o-transition: opacity 0.4s ease-in-out;
  -ms-transition: opacity 0.4s ease-in-out;
  transition: opacity 0.4s ease-in-out;
}
.dropzone .dz-preview .dz-error-message,
.dropzone-previews .dz-preview .dz-error-message {
  display: block;
  opacity: 0;
  -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
  filter: alpha(opacity=0);
  -webkit-transition: opacity 0.3s ease-in-out;
  -moz-transition: opacity 0.3s ease-in-out;
  -o-transition: opacity 0.3s ease-in-out;
  -ms-transition: opacity 0.3s ease-in-out;
  transition: opacity 0.3s ease-in-out;
}
.dropzone .dz-preview:hover.dz-error .dz-error-message,
.dropzone-previews .dz-preview:hover.dz-error .dz-error-message {
  opacity: 1;
  -ms-filter: none;
  filter: none;
}
.dropzone a.dz-remove,
.dropzone-previews a.dz-remove {
  background-image: -webkit-linear-gradient(top, #fafafa, #eee);
  background-image: -moz-linear-gradient(top, #fafafa, #eee);
  background-image: -o-linear-gradient(top, #fafafa, #eee);
  background-image: -ms-linear-gradient(top, #fafafa, #eee);
  background-image: linear-gradient(to bottom, #fafafa, #eee);
  -webkit-border-radius: 2px;
  border-radius: 2px;
  border: 1px solid #eee;
  text-decoration: none;
  display: block;
  padding: 4px 5px;
  text-align: center;
  color: #aaa;
  margin-top: 26px;
}
.dropzone a.dz-remove:hover,
.dropzone-previews a.dz-remove:hover {
  color: #666;
}
@-moz-keyframes loading {
  from {
background-position: 0 -400px;
  }
  to {
background-position: -7px -400px;
  }
}
@-webkit-keyframes loading {
  from {
background-position: 0 -400px;
  }
  to {
background-position: -7px -400px;
  }
}
@-o-keyframes loading {
  from {
background-position: 0 -400px;
  }
  to {
background-position: -7px -400px;
  }
}
@keyframes loading {
  from {
background-position: 0 -400px;
  }
  to {
background-position: -7px -400px;
  }
}

       Galeria

      <form role="form" action="#" id="my-dropzone" class="dropzone form-horizontal" method="post" enctype="multipart/form-data">
       <input type="hidden" name="gal_id" value="{$galeria.gal_id}">

         <button class="close" data-close="alert"></button>
         Você tem alguns erros no formulário. Por favor, verifique abaixo.

         <button class="close" data-close="alert"></button>
         O formulário foi validado com sucesso! Aguarde.

         Ativo

          <input type="checkbox" name="active" value="1" class="make-switch" data-on-color="success" data-off-color="danger" data-on-text="SIM" data-off-text="NÃO" {if $galeria.gal_active == 1 or !$livre}checked{/if}>

         Título  *

          <input type="text" name="title" placeholder="Título" class="form-control required" minlength="2" maxlength="100" value="{$galeria.gal_title}">

Imagens

          <button type="submit" class="btn green-meadow">{if !$livre}Adicionar{else}Salvar{/if}</button>
          Cancelar

      </form>

Como posso fazer para que a mensagem "Drop files to upload" suma após os itens serem adicionados?
Comment: Eles deveriam ficar dentro do quadro cinza, parece que está sendo alinhado no final da tag
Answer: Defina nas configurações do Dropzone o item previewTemplate:
Dropzone.options.myDropzone = {
    previewTemplate: document.querySelector('.dropzone-previews').innerHTML,
    // ....
}

Comment: Sem sucesso amigo. Li no site oficial sobre a opção, tentei colocar sem a classe (.) e com um id na div, mas não funcionou.
Comment: Hm, vi que existe o item `previewsContainer`, testa o seguinte `previewsContainer: '.dropzone-previews'` ao invés do `previewTemplate` @MarcusDavid
Comment: Estava vendo essa opção agora @LúcioRubens. Adicionei essas duas opções: previewsContainer: ".dropzone-previews", clickable: ".dropzone-previews". Vou editar o post com a imagem de como ficou
Comment: No seu css a altura da classe `.dropzone-previews` esta fixo: `height:100px`. Remove esta propriedade @MarcusDavid
Comment: Tive que mexer um pouco mais no `CSS`, esse do `height: 100px` era da altura da miniatura. Tive que mexer na classe `.dropzone` e adicionar a classe `.dropzone-previews` algumas configurações. O problema agora é que a mensagem fica "por cima" dos arquivos que irão ser enviados, impossibilitando o clique em alguns...
Answer: Você pode modificar a mensagem da seguinte forma:
data: function(){ return {   dropzoneOptions: { dictDefaultMessage: '' }}}

Onde o dictDefaultMessage modifica sua mensagem, então é só definir como branco.


Por que declarar ponteiro para array se arrays já são ponteiros?

Question: se um array  char já é um ponteiro, por que declarar um ponteiro para o array?
E qual é a diferença entre char exemplo[10] e char *exemplo[10]?
Comment: Você pode aceitar uma resposta se ela resolveu seu problema. Você pode votar em todos os posts do site também. Alguma lhe ajudou mais? Precisa que algo seja melhorado?
Comment: Quando estudei C eu tive esta dúvida tbm, mas hoje em dia tenho consciea da necessidade de se apontar para um ponteiro
Answer: Você não está declarando um ponteiro para array. Está declarando um ponteiro para char. Ao contrário da crença popular, eles são coisas distintas.
No primeiro exemplo tem um array com 10 chars. No segundo tem um array com 10 ponteiros para char.
O ponteiro para char é praticamente um sinônimo para string. A linguagem C não tem o tipo string, mas isto é o mais próximo de uma.
Obviamente o ponteiro precisa apontar para uma área da memória que tenha uma sequência de chars.
Coloquei no GitHub para referência futura.
Comment: Um literal entre aspas, em C, tem tipo array de `N` caracteres em que `N` é o suficiente para os caracteres do literal e o terminador. `"exemplo"` tem tipo `char [8]`.
Comment: Quando é usado como valor, o array é convertido para um ponteiro para o seu primeiro elemento. No caso de string literais esta conversão é para o tipo `char *` (não `const char *`) embora o resultado seja *read-only*. Para evitar surpresas muita gente acrescenta o `const` especificamente.
Comment: @pmg é verdade, ele decai para um `const char *` apenas. Consertei isso.
Answer: Um array char (ou outro tipo) NÃO É um ponteiro.
Um array é um array; um ponteiro é um ponteiro (ver secção 6 do c-faq).
Quando um array é usado como valor, ele é convertido para um ponteiro para o seu primeiro elemento.
A diferença entre char exemplo[10] e char *exemplo[10] é que o primeiro declara um array de 10 caracteres e o segundo declara um array de 10 ponteiros.
Comment: +1 pelo "Um array char (ou outro tipo) NÃO É um ponteiro".
Tenho visto várias respostas que indicam: na linguagem C arrays não existem de verdade, ou que são o mesmo que apontadores.


In the NFL, how have teams fared against odds from Las Vegas?

Question: Is a home team more or less likely to beat the spread than an away team? Do favored teams or underdogs win against the spread more often? Please include statistics/studies instead of just guessing.

Team A is favored by three points. They beat Team B by two points. Team B won against the spread (or beat the spread).
Team A is favored by three points. Team B wins. Team B won against the spread.
Team A is favored by three points. They win by five points. Team A won against the spread.
Answer:
Is a home team more or less likely to beat the spread than an away team?

Less likely.
Against the spread, the home team is 2001-2074-109 (.47825) since 2003.
Source | Range: Since 2003 | Show: All | Situation: As Home Team

Do favored teams or underdogs win against the spread more often?

Underdogs win against the spread more often than favored teams.
Against the spread, the favored team is 1999-2068-110 (.4786) since 2003.
Source | Range: Since 2003 | Show: All | Situation: As Favored Team


What is the slug of mainpage?

Question: I am editing blocks in /admin/structure/block - when I click "Configure" for a block, I see:

Show block on specific pages
All pages except those listed
Only the listed pages
Pages on which this PHP code returns TRUE (experts only)

I need to show the block only on the mainpage. How to do this? I don't know what is the slug for mainpage.
Answer: If by 'mainpage' you mean the front page, the token is simply
<code><front>
</code>

What is the slug of mainpage?


Invariant set for SIRS model

Question: A SIRS model is a set of ODE used to describe the evolution of epidemic/pandemic. It is defined as follows:
$$\begin{cases}
\dot{s} = -\beta s i + \omega r\\
\dot{i} = \beta s i - \gamma i \\
\dot{r} = \gamma i - \omega r
\end{cases},$$
where $s$, $i$ and $r$ represent the share of susceptible, infected and recovered individuals, respectively, and $\beta$, $\omega$ and $\gamma$ are positive parameters.
First of all, one notice that:
$$\dot{s} + \dot{i} + \dot{r} = 0.$$
As a direct consequence, if $s(0) + i(0) + r(0) = 1,$ then $s(t) + i(t) + r(t) = 1 ~\forall t > 0.$
Anyway, this does not ensure that no state variable can assume negative value or ca be bigger than $1$ for some time instant $t' > 0$. This is what I want to prove.
In other words, how can I prove that the set:
$$S = \left\{(s(t), i(t), r(t)) : s(t) \geq 0 \wedge i(t) \geq 0 \wedge r(t) \geq 0 \wedge s(t) + i(t) + r(t) = 1 ~\forall t > 0\right\}$$
is invariant for the ODE system reported at the beginning of this post?
Thanks in advance.
Answer: Let $z(t,z(0))=(s(t),i(t),r(t))$ be the solution to the SIRS with initial condition $z(0)\in S$ with $z(0)\overset{\Delta}=(s(0), i(0), r(0))\neq 0$ (since $s(0)+i(0)+r(0)=1$).
Let $T\overset{\Delta}=\inf\limits_{t\geq 0}\left\{z(t,z(0))\in S^{c}\right\}$ be the hitting time to the complement of $S$. Assume $T<\infty$. Since $S$ is closed, at the instant $T$, the solution lies at the boundary of $S$: either i) $s(T)=0$ or ii) $i(T)=0$ or iii) $r(T)=0$. Note that $z(T,z(0))\neq 0$ ($z(t,0)=0$ is the unique $0$ solution), therefore some state-variable should be positive. Say $i(T)>0$ is the only positive one. Then, $r(T)=0$, but $\dot{r}(T)=\gamma i(T)>0$. Further, $s(T)=0$ and $\dot{s}(T)=0$, but $\ddot{s}(T)=-\beta\dot{s}(T)i(T)-\beta s(T) \dot{i}(T)+\omega \dot{r}(T)=\omega \dot{r}(T)>0$. Since $z(t,z(0))$ is smooth, there exists $\epsilon>0$ so that $i(t)>0$ and $s(t)>0$ and $r(t)>0$ for all $t\in (T,T+\epsilon)$. This conclusion can be obtained in the other cases as well when $i(T)=0$. This contradicts the assumption $T<\infty$, therefore $T=\infty$.
Comment: Thanks a lot, +1. But what if $s(T) = 1$ or $i(T) = 1$ or $r(T) = 1$?
Comment: As you pointed, $s(t)+i(t)+r(t)=1$ for all $t$ (since $\dot{s}(t)+\dot{i}(t)+\dot{r}(t)=0$ and $s(0)+r(0)+i(0)=1$). This implies that if say $i(T)=1$, then $r(T)=s(T)=0$ which reduces to the case highlighted in the answer. Since $s(t)>0$ and $r(t)>0$ for all $t\in(T,T+\epsilon)$ (as shown in the answer) and given that  $s(t)+i(t)+r(t)=1$, we have that $i(t)<1$ for $t\in (T,T+\epsilon)$. You can alternatively observe that for $i(T)=1$, we have $\dot{i}(T)=-\gamma$ (since $s(T)=0$) and this is consistent with the previous observation: $i(t)<1$ for $t\in (T,T+\epsilon)$.

Invariant set for SIRS model


Reference Error when calling function inside setTimeout

Question: I keep getting a Reference Error inside the setTimeout function.
Below is the code in javascript file
( function( $, undefined ) {

  $( document ).ready( init );

  function init() {
    registerEventListeners();
  }

  function registerEventListeners() {
    $( '.start_countdown').click( handleStart );
    $( '.end_countdown').click( handleEnd );
  }

  var countdown;
  var countdown_number;

  function handleStart() {
    countdown_number = 11;
    countdown_trigger(countdown_number);
  }

  function countdown_trigger() {
    if (countdown_number > 0) {
      countdown_number --;
      document.getElementById('countdown_text').innerHTML = countdown_number;
      if (countdown_number > 0) {
          countdown = setTimeout('countdown_trigger()', 1000);
      }
    }
  }

  function handleEnd() {
    clearTimeout(countdown);
  }

})( jQuery );

In the jade.js file:
extends layout

append scripts
  script(src='/javascripts/countDownRedirect.js')

block content
  h1= title

  p Redirecting you to your documents shortly

  div
    button.start_countdown#start Start Countdown
    button.end_countdown#end End Countdown

  div#countdown_text Placeholding text

Reference Error: 'countdown_trigger()' not defined
When the page is loaded everything appears to work fine.
Clicking the start button displays 10 but then throws the reference error.
Any suggestions?
Thanks
Answer: When you use quotes in setTimeout you're invoking eval which is not a good idea. Try passing a reference to the function instead of a string:
countdown = setTimeout(countdown_trigger, 1000);

Answer: To explain what's going on and why it doesn't work - when you pass a string to setTimeout(), the string is evaluated by eval() in the global scope.  That means that no local functions or variables are available in that global scope.  Since your countdown_trigger() function is declared inside another function, it is not in the global scope and thus won't be available to eval() and thus it doesn't work when you pass it to setTimeout().
This is one of many reasons to never pass strings to setTimeout().
Instead pass a real function reference which is evaluated in your current scope like this:
setTimeout(countdown_trigger, 1000);


React/Material UI - Prevent body scrolling on popover

Question: New to React and MUI, and having a UX issue where when we have a popover (dropdown menu, or autoselect dropdown) we can still scroll the main body of the site. I see that its fixed in the new beta V1 for MUI, but using the current stable release, Ive been asked to see if we can hack it up to stop the  scrolling - but I cant seem to target/catch anything when we have a popover appear.
Examples: Current MUI - http://www.material-ui.com/#/components/auto-complete
V1 Beta MUI - https://material-ui-next.com/demos/autocomplete/
So, if you were to input something in those examples and trigger the downdown/popover, youll see that in the current MUI, you can still scroll the

I was hoping someone may have had this issue and had a solution they'd like to share?
Thanks guys!
Comment: I've also run into this issue. I think the key is to attach a ref to the appropriate popover element that you want to scroll. However, since the popover renders at the window level and not the component level, you most likely do not have the scope to apply different scroll positions or styles.
Answer: I had a similar problem and solve it using 'disablePortal' Autocomplete property:
You can take a look at 'disablePortal' definition in here:
https://material-ui.com/api/autocomplete/#props
disablePortal: Disable the portal behavior. The children stay within it's parent DOM hierarchy.
I also had to add some styles to get pop up get positioned relative to input component.
Here is some sort of example:
<code>const useStyles = makeStyles({
    popperDisablePortal: {
      position: 'relative',
    }
  })

const classes = useStyles()

<Autocomplete
  classes={classes}
  disablePortal={true}
  {...props}
/>
</code>
So you may have to:

set up disablePortal property
define associated popperDisablePortal style with 'relative' position

EDIT: actually this error should not happen as part of default MUI Autocomplete set up. In my case, the error was some conflicting CSS property that was generating this scroller bug. Not sure in your case, but to me it happens to be some overflow: auto property defined on page HTML tag (sometimes you can find it on body tag). Replace with overflow: 'visible' and scrolling error should be gone without even changing one line of autocomplete component definition.


Homomorphisms of a Finite Group & Perfect Squares

Question: I'm working on a textbook problem:
Come up with a finite group $G$ and homomorphism: $f: G \rightarrow G$ such that $3$% of the elements of in $G$ satisfy $f(x) = x^2$ (where $x$ is an element in $G$).
So far, I've tried a lot of different ideas. When I made the binary operator for $G$ additive, I had a tough time since the homomorphism must follow a lot of conditions such as $f(2) = 2f(1)$, not leaving a lot of space for me to try and come up with a way to get $f(x) = x^2.$
I tried making the group a power group and multiplicative. In both scenarios, I didn't really get anything too useful – every idea that I tried ultimately failed.
Does anyone know how to do this?
Answer: Here is a solution where I explain all the "false starts" I tried along the way. Let's start by looking at a very simple example, namely the multiplication-by-$m$ map $f(x) = mx$ on the cyclic group $C_n \cong \mathbb{Z}/n$ (written additively). The subset of elements satisfying $f(x) = mx = 2x$ is the subset of elements satisfying $(m-2) x = 0$, which has size $\gcd(m-2, n)$ (exercise). So the density of this subset is $\frac{\gcd(m-2, n)}{n}$, which unfortunately as a fraction in lowest terms always has numerator $1$ and so cannot be equal to $\frac{3}{100}$. So no example of this form can work.
The next group I tried was $\mathbb{Z}/n \times \mathbb{Z}/n$, but I ran into the following problem generalizing the previous observation: if $A$ is any abelian group and $f : A \to A$ is a homomorphism then the subset of elements satisfying $f(a) = 2a$ is $\text{ker}(f - 2)$ which is a subgroup, so its density always has numerator $1$ when written as a fraction in lowest terms (with denominator the index). This means an example must be nonabelian.
However, abelian examples do help us for the following reason: if $f_1 : G_1 \to G_1$ is an endomorphism of a group and $f_2 : G_2 \to G_2$ is an endomorphism of another group, we can take their direct product to get an endomorphism $f_1 \times f_2 : G_1 \times G_2 \to G_1 \times G_2$. If we write $d(G, f)$ for the density of elements satisfying $f(g) = g^2$, then
$$d(G_1 \times G_2, f_1 \times f_2) = d(G_1, f_1) d(G_2, f_2).$$
So when we're looking for nonabelian examples it suffices to find a nonabelian group with density of the form $\frac{3}{n}$ where $n \mid 100$, and then we can take the direct product with a suitable abelian group to get density $\frac{3}{100}$.
If $f : G \to G$ is a complicated endomorphism of a complicated nonabelian group then it could be quite hard to count the number of elements satisfying $f(g) = g^2$, so for starters let's see what happens if we just set $f(g) = e$ to be the zero endomorphism. Then we're counting the elements satisfying $g^2 = e$, which when $G$ is nonabelian need not be a subgroup. For example, $G = S_3$ has $4$ such elements, with density $\frac{4}{6} = \frac{2}{3}$, which does not have numerator $1$, so this is promising.
Let's see if we can get density $\frac{3}{4}$. The smallest possible example with this property would be a group of order $8$, so let's consider the dihedral group $D_4$. The dihedral group consists of a copy of $C_4$, of which $2$ elements square to the identity, plus $4$ reflections, all of which square to the identity, so the density is $\frac{6}{8} = \frac{3}{4}$ as desired.
So we're done. We can take our final group $G$ to be $\boxed{ D_4 \times C_{25} }$ and our final endomorphism to be $\boxed{ f(g, h) = (e, h) }$.
Comment: Well done! I wasted a lot of time on this, but I had misread the question, and I was looking for automorphism $f$ of $G$. I suspect that is not possible.
Comment: @QiaochuYuan It looks like this question, along with every single other question the same user has asked, came directly from the [MIT PRIMES 2021 application](https://math.mit.edu/research/highschool/primes/materials/2021/entpro21.pdf). Flagging them all would create a lot of work for moderators, and I think accomplish very little, since this answer and others have already been up for a while. Do you have any suggestions?
Comment: @QiaochuYuan Okay. I've sent them an email.
Comment: @Derek: that does seem a lot trickier! If $f(g) = e$ hadn't worked I might've tried taking $f$ to be an inner automorphism next.
Comment: when working with the abelian groups, you talked about $f(a) = 2a$. Is this a typo? Shouldn't it have been $f(a) = a^n$? Am I missing something?
Comment: @delhimaths: I'm just writing the group operation additively. It means the same thing.
Comment: why does it mean the same thing? I don't really understand
Comment: @delhimaths: if $m$ denotes the group operation, squaring refers to $m(g, g)$. If you write the group operation multiplicatively this is $g \times g = g^2$. If you write the group operation additively this is $g + g = 2g$.
Comment: @QiaochuYuan but doesn't the original problem statement just say ()=2? Shouldn't that mean that even if it was an additive group, if I put 3 into the function, I should get 9 and not 6?
Comment: @delhimaths: for a group, $g^2$ always refers to $m(g, g)$ where $m$ is the group operation and sometimes has to be inferred from context. $\mathbb{Z}/n$ is not a group under multiplication, only under addition, and the problem refers only to groups, which can be written either additively (for abelian groups) or multiplicatively
Comment: @QiaochuYuan Thanks for the help! I'm curious – do you know how to figure out what the largest possible value of $k$ could be? I know that in order to get it, we would need to have a group that cannot be written as a direct product of other groups. But after that, I don't really see a way to maximize it.
Comment: @delhimaths: sorry, what is $k$?
Comment: @QiaochuYuan Oh my bad. I think when it got edited by Shaun, he removed it. $k$ is just the percent of elements that satisfy $f(x) = x^2.$ So in this example, you gave a group with $k = 75$%. On the other thread that I made about partioning a group into smaller sets, I had asked that because I wanted to see if I could just say that all groups can be written as cyclic, dihedral, symmetric groups (or maybe some other super simple/very often used type of group) so that it would be easiest to maximize $k$.
Comment: @QiaochuYuan When you tried $\mathbb{Z}/n \times \mathbb{Z}/n$, shouldn't the density just be the density of $\mathbb{Z}/n$ squared based off of the formula you gave right after ($d(G_1 \times G_2, f_1 \times f_2) = d(G_1, f_1) d(G_2, f_2).$)?
Comment: @delhimaths: that formula only applies to an endomorphism of the form $f_1 \times f_2$. Generally an endomorphism of $\mathbb{Z}/n \times \mathbb{Z}/n$ is given by a $2 \times 2$ matrix over $\mathbb{Z}/n$.
Comment: @delhimaths: as for your other question, groups are much more complicated than that, and I don't know what the highest density could be. As in my previous comment, it doesn't follow that the group can't be written as a direct product because the endomorphism can "mix" the two factors.
Comment: @QiaochuYuan What is the difference between $\mathbb{Z}/n \times \mathbb{Z}/n$ and $f_1 \times f_2$? Also, what would such a matrix look like? Do you of any source that talks about this?
Comment: @delhimaths: one of those is a group and one of those is an endomorphism. The "diagonal" endomorphisms of $\mathbb{Z}/n \times \mathbb{Z}/n$ of the form $f_1 \times f_2$ are precisely the ones which, when viewed as $2 \times 2$ matrices over $\mathbb{Z}/n$, correspond to diagonal matrices. And there are lots of non-diagonal matrices, such as $\left[ \begin{array}{cc} 1 & 1 \\ 0 & 1 \end{array} \right]$, which corresponds to the endomorphism $(a, b) \mapsto (a, a + b)$. I don't know of any sources that talk about this specifically; these are basically exercises.
Comment: (That is, the exercise: show that every endomorphism of $\mathbb{Z}/n \times \mathbb{Z}/n$ is given by multiplication by a unique $2 \times 2$ matrix with coefficients in $\mathbb{Z}/n$. You can prove a more general version of this for endomorphisms of the direct product / sum $A \times B$ of two arbitrary abelian groups also.)
Comment: @Misha: oof. Well, at the very least PRIMES should be notified. Do you want to do it?


At What Level is a $\chi^2$ test Mathematically Identical to a $z$-test of Proportions?

Question: BACKGROUND: Skip safely - it's here for reference, and to legitimize the question.
The opening of this paper reads:
"Karl Pearson's famous chi-square contingency test is derived from another statistic, called the z statistic, based on the Normal distribution. The simplest versions of $\chi^2$ can be shown to be mathematically identical to equivalent z tests. The tests produce the same result in all circumstances. For all intents and purposes "chi-squared" could be called "z-squared". The critical values of $\chi^2$ for one degree of freedom are the square of the corresponding critical values of z."
This has been asserted multiple times in CV (here, here, here and others).
And indeed we can prove that $\chi^2_{1\,df}$ is equivalent to $X^2$ with $X\sim N(0,1)$:
Let's say that $X \sim N(0,1)$ and that $Y=X^2$ and find the density of $Y$ by using the $cdf$ method:
$p(Y \leq y) = p(X^2 \leq y)= p(-\sqrt{y} \leq x \leq \sqrt{y})$. The problem is that we cannot integrate in close form the density of the normal distribution. But we can express it:
$$ F_X(y) = F_X(\sqrt{y})- F_X(-\sqrt[]{y}).$$ Taking the derivative:
$$ f_X(y)= F_X'(\sqrt{y})\,\frac{1}{2\sqrt{y}}+
F_X'(\sqrt{-y})\,\frac{1}{2\sqrt{y}}.$$
Since the values of the normal $pdf$ are symmetrical:
$ f_X(y)=
F_X'(\sqrt{y})\,\frac{1}{\sqrt{y}}$. Equating this to the $pdf$ of the normal (now the $x$ in the $pdf$ will be $\sqrt{y}$ to be plugged into the $e^{-\frac{x^2}{2}}$ part of the normal $pdf$); and remembering to in include $\frac{1}{\sqrt{y}}$ at the end:
$$ f_X(y)=
F_X'(\sqrt[]{y})\,\frac{1}{\sqrt[]{y}}=
\frac{1}{\sqrt{2\pi}}\,e^{-\frac{y}{2}}\,
\frac{1}{\sqrt[]{y}}=\frac{1}{\sqrt{2\pi}}\,e^{-\frac{y}{2}}\,
y^{\frac{1}{2}- 1}$$
Compare to the pdf of the chi square:
$$ f_X(x)= \frac{1}{2^{\nu/2}\Gamma(\frac{\nu}{2})}e^{\frac{-x}{2}}x^{\frac{\nu}{2}-1}$$
Since $\Gamma(1/2)=\sqrt{\pi}$, for $1$ df, we have derived exactly the $pdf$ of the chi square.
Further, if we call the function prop.test() in R we are invoking the same $\chi^2$ test as if we decide upon chisq.test().
THE QUESTION:
So I get all these points, yet I still don't know how they apply to the actual implementation of these two tests for two reasons:

A z-test is not squared.
The actual test statistics are completely different:

The value of the test-statistic for a $\chi^2$ is:
$\chi^2 = \sum_{i=1}^{n} \frac{(O_i - E_i)^2}{E_i} =  N \sum_{i=1}^n p_i \left(\frac{O_i/N - p_i}{p_i}\right)^2$
where
$\chi^2$ = Pearson's cumulative test statistic, which asymptotically approaches a $\chi^2$ distribution. $O_i$ = the number of observations of type $i$; $N$ = total number of observations; $E_i$ = $N p_i$ = the expected (theoretical) frequency of type $i$, asserted by the null hypothesis that the fraction of type $i$ in the population is  $p_i$;
$n$ = the number of cells in the table.
On the other hand, the test statistic for a $z$-test is:
$ \displaystyle Z = \frac{\frac{x_1}{n_1}-\frac{x_2}{n_2}}{\sqrt{p\,(1-p)(1/n_1+1/n_2)}}$ with $\displaystyle p = \frac{x_1\,+\,x_2}{n_1\,+\,n_2}$, where $x_1$ and $x_2$ are the number of "successes", over the number of subjects in each one of the levels of the categorical variables, i.e. $n_1$ and $n_2$.
This formula seems to rely on the binomial distribution.
These two tests statistics are clearly different, and result in different results for the actual test statistics, as well as for the p-values: 5.8481 for the $\chi^2$ and 2.4183 for the z-test, where $\small 2.4183^2=5.84817$ (thank you, @mark999). The p-value for the $\chi^2$ test is 0.01559, while for the z-test is 0.0077. The difference explained by two-tailed versus one-tailed: $\small 0.01559/2=0.007795$ (thank you @amoeba).
So at what level do we say that they are one and the same?
Comment: In `chisq.test()`, have you tried using `correct=FALSE`?
Comment: Indeed, Antoni. Both tests exist with or without the Yates. Could it be that you compute one with but the other without it?
Comment: Thank you! You were (predictably) correct. With the Yates correction off, one is just the square of the other. I edited the question accordingly, although a bit fast. I still would like to prove algebraically that both test statistics are the same (or one  the square of the other), and understand why the p-values are different.
Comment: But these are two identical tests. Z squared is the chi-square statistic. Let you have 2x2 frequency table where columns are the two groups and the rows are "success" and "failure". Then the so called expected frequencies of the chi-square test in a given column is the weighted (by the groups' N) _average column (group) profile_ multiplied by that group's N. Thus, it comes that chi-square tests the deviation of each of the two groups profiles from this average group profile, - which is equivalent to testing the groups' profiles difference from each other, the z-test of proportions.
Comment: In the example on the last hyperlink the $\chi^2$ is almost the square of the z-test statistic, but not quite, and the p-values are different. Also, when you look at the formulas for the rest statistics above, is it truly immediate that they are identical? Or even one the square of the other?
Comment: The first could be a matter of rearranging terms, and splicing nomenclature, and I could tackle it later when I have time. The second is a bit more hairy. In any event, it would be great to just get a formal answer from another member I can upvote and accept.
Comment: I guess that one p-value is one-sided and another is two-sided; hence the difference by the factor of two.
Answer: Let us have a 2x2 frequency table where columns are two groups of respondents and rows are the two responses "Yes" and "No". And we've turned the frequencies into the proportions within group, i.e. into the vertical profiles:
      Gr1   Gr2  Total
Yes   p1    p2     p
No    q1    q2     q
      --------------
     100%  100%   100%
      n1    n2     N

The usual (not Yates corrected) $\chi^2$ of this table, after you substitute proportions instead of frequencies in its formula, looks like this:
$$n_1[\frac{(p_1-p)^2}{p}+\frac{(q_1-q)^2}{q}]+n_2[\frac{(p_2-p)^2}{p}+\frac{(q_2-q)^2}{q}]= \frac{n_1(p_1-p)^2+n_2(p_2-p)^2}{pq}.$$
Remember that $p= \frac{n_1p_1+n_2p_2}{n_1+n_2}$, the element of the weighted average profile of the two profiles (p1,q1) and (p2,q2), and plug it in the formula, to obtain
$$...= \frac{(p_1-p_2)^2(n_1^2n_2+n_1n_2^2)}{pqN^2}$$
Divide both numerator and denominator by the $(n_1^2n_2+n_1n_2^2)$ and get $$\frac{(p_1-p_2)^2}{pq(1/n_1+1/n_2)}=Z^2,$$
the squared z-statistic of the z-test of proportions for "Yes" response.
Thus, the 2x2 homogeneity Chi-square statistic (and test) is equivalent to the z-test of two proportions. The so called expected frequencies computed in the chi-square test in a given column is the weighted (by the group n) average vertical profile (i.e. the profile of the "average group") multiplied by that group's n. Thus, it comes out that chi-square tests the deviation of each of the two groups profiles from this average group profile, - which is equivalent to testing the groups' profiles difference from each other, which is the z-test of proportions.
This is one demonstration of a link between a variables association measure (chi-square) and a group difference measure (z-test statistic). Attribute associations and group differences are (often) the two facets of the same thing.

(Showing the expansion in the first line above, By @Antoni's request):
$n_1[\frac{(p_1-p)^2}{p}+\frac{(q_1-q)^2}{q}]+n_2[\frac{(p_2-p)^2}{p}+\frac{(q_2-q)^2}{q}] = \frac{n_1(p_1-p)^2q}{pq}+\frac{n_1(q_1-q)^2p}{pq}+\frac{n_2(p_2-p)^2q}{pq}+\frac{n_2(q_2-q)^2p}{pq} = \frac{n_1(p_1-p)^2(1-p)+n_1(1-p_1-1+p)^2p+n_2(p_2-p)^2(1-p)+n_2(1-p_2-1+p)^2p}{pq} = \frac{n_1(p_1-p)^2(1-p)+n_1(p-p_1)^2p+n_2(p_2-p)^2(1-p)+n_2(p-p_2)^2p}{pq} = \frac{[n_1(p_1-p)^2][(1-p)+p]+[n_2(p_2-p)^2][(1-p)+p]}{pq} = \frac{n_1(p_1-p)^2+n_2(p_2-p)^2}{pq}.$


help in interpreting x(t)

Question: I dont know if the wording is confusing but I know x(.) is just $ \mathbb{R} \rightarrow \mathbb{R}$. Can I say that as my precise definition.
and then say its just a mapping of real numbers to real numbers. I dont know if its right please help out
"Every  magnitude  which grows continually  but  not  beyond all limits
must certainly  approach  a limiting value."
We can  interpret "magnitude" as a real  number  x  that  changes  in time,  thus, as a real valued  function  x(t), t ∈ R.  The  above sentence  is a theorem  about  the behaviour  of such a function as t approaches  $\infty$.
(a) The assumptions of the theorem are that  the function x(t) is monotone ("grows") and is bounded  ("not  beyond all limits").   Give a precise definition  of each of these properties  of the function x($\cdot$).
(b)  State  the theorem in your own words.
and also if someone could tell me what this line means
"The side and the diagonal of a square are incommensurable."
like how would i rephrase that if i want to explain this to someone?
Comment: a) $f$ is monotone increasing iff $f(x)<f(y) \quad \forall x<y$.  Furthermore $f$ is bounded by $c<\infty$ from above , iff $f(x)\leq c \quad \forall x$.
Comment: Of course you have to adapt it, as $x$ is your function and $t$ the argument, thus instead of $f(x)$ you have to rewrite it as $x(t)$.
Comment: i dont get it. like i know it is giving you a function where the domain pertains to all real numbers, or in other words in x(t), t cannot be complex. but i dont know what it meant by put it as a precise definiton
Answer: If a function $f:\mathbb{R}\to\mathbb{R}$ is monotonously increasing then it's first derivative (i.e. it's rate of change) is greater than or equal to $0$ for it's entire domain, i.e.:
$$f(t)\text{ is monotonously increasing} \iff f'(t)\geq0, \forall t\in\mathbb{R}$$
Similarly, if a function $g:\mathbb{R}\to\mathbb{R}$ is monotonously decreasing, then it's first derivative is less than or equal to $0$ for it's entire domain, i.e.:
$$g(t) \text{ is monotonously decreasing} \iff g'(t)\leq0, \forall t \in\mathbb{R}$$
For a function $h:\mathbb{R}\to\mathbb{R}$ to be bounded from above, it must be the case that for it's entire domain, i.e. $\forall t \in \mathbb{R}$, there exists some constant $x\in\mathbb{R}$ such that the function does not exceed $x$. That is:
$$h(t)\text{ is bounded above by }x\in\mathbb{R}\iff \exists x\in\mathbb{R}:\forall t \in \mathbb{R} \space h(t)\leq x$$
Comment: thank you @shaktal, that made sense.
Comment: I was wondering would you know what this line means. its bothering me "The side and the diagonal of a square are incommensurable."
Answer:
a) $x(\cdot)$ is monotone increasing iff $x(t_l)<x(t_r) \quad \forall t_l<t_r\quad   t_l,t_r \in \mathbb{R}$.  Furthermore $x$ is bounded by $c<\infty$ from above , iff $x(t)\leq c \quad \forall t\in \mathbb{R}$.
b) If $x(\cdot)$ is montone increasing and bounded from above, then $\exists x_{\infty}\in \mathbb{R}: \lim_{t\rightarrow\infty}x(t) = x_{\infty}$

Note, that b) also reads: Every montone increasing (decreasing) sequence which is bounded from above (below) does converge.
Edit: From this source I quote

incommensurable
b. Having an irrational ratio.

This the case, because if a square as an side length of $a$, its diagonal has length $\sqrt{2}a$, thus the ratio is $\sqrt{2}$ which is irrational.

help in interpreting x(t)


Excel Macro: How to change the cell color of a row within a range

Question: I have a range from C17:W39. I would like to make the row within the range Grey or White depending on the value in column E. If the volume is Actual, I would like the row to be grey and if the value is guess, I would like the row to be white. I need it so that only the cell color within the range is changed not the entire row. The below code works on the first row but I can't figure out how to make it loop through the rest of the range. Any help would be appreciated. Thanks.
Sub Color()
    Dim myRange As Range
    Dim cell As Range
    Set myRange = Range("C17:W17")
        For Each cell In myRange
        If cell.Value = "ACTUAL" Then myRange.Interior.ColorIndex = 15
        If cell.Value = "GUESS" Then myRange.Interior.ColorIndex = 0
    Next
End Sub

Comment: I agree with @pnuts. Why not use conditional formatting? You can conditional format the cells with or without using VBA Code.
Answer: You could change your code like this:
Sub Color()
    Dim myRange As Range
    Dim cell As Range
    Set myRange = Range("E17:E39")
        For Each cell In myRange
        If cell.Value = "ACTUAL" Then
            Range("C" & cell.Row & ":W" & cell.Row).Interior.ColorIndex = 15
        End If
        If cell.Value = "GUESS" Then
            Range("C" & cell.Row & ":W" & cell.Row).Interior.ColorIndex = 0
        End If
    Next
End Sub

This loops through each cell in range E17:E39 and formats the cells from column C to W in response to the value found in the E-column.


How to show separate values in Views from multi-value field

Question: I made Multi-valued field in content type. I created image type of field and let it has unlimited number of images.
Is it possible in Views to show only first image from this field? And only 5th?
Answer: Adjust these settings in your view for the image field:


Numerically solve Lotka-Volterra equations using Euler-Cromer

Question: I am trying to solve this coupled pair of equations
$$
{dx\over dt}=\alpha x - \beta xy,\\
{dy\over dt}=\delta xy - \gamma y
$$
using the numerical method Euler-Cromer. It doesn't matter which method, as long as it is symplectic. But I'm lost on how to use this method for a system that doesn't have a Hamiltonian (or does it?), at least isn't mechanical. Is it possible to solve this using Euler-Cromer? I am looking for something like a recurrence relation so that I can calculate each new value from the old.
Best regards //
Answer: As
$$
\frac{dx}{x}(δx−γ)=\frac{dy}{y}(α−βy)
$$
there is indeed a first integral
$$
F(x,y)=δx-γ\ln|x|+βy-α\ln|y|
$$
Taking this as a Hamiltonian for a potentially different time scale results in the system
\begin{align}
\frac{dx}{ds}&=-F_y=\fracαy-β&&=\frac{αx-βxy}{xy}\\
\frac{dy}{ds}&=~~~F_x=δ-\fracγx&&=\frac{δxy-γy}{xy}\\
\end{align}
so that for $xy>0$ the relation between the time scales is $\frac{dt}{ds}=\frac1{xy}$
To this Hamiltonian system you can apply the symplectic Euler method, which should yield orbits that are closer to closed than the simple application of Euler. With some more effort in the initial step one can easily modify this method to leapfrog Verlet, which has even better theoretical properties. To get not only the curve but the solution, you also need to integrate the equation for $t$.


Ajuda em passar um código do jsFiddle para um arquivo HTML

Question: Eu tenho um código nesse jsFiddle que eu alterei, porém agora estou a ter dificuldades em passá-lo para um arquivo HTML.
Meu código:
<!DOCTYPE html>

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

    <form action="testeste.html" method="post">
        <select>
            <option value="trechoorigem">Trecho Origem</option>
            <option value="trechodestino">Trecho Destino</option>
            <option value="dataprocessamento">Data Processamento</option>
            <option value="statusintegracao">Status Integração</option>
            <option value="tipoproduto">Tipo Produto</option>
            <option value="datasaida">Data Saida</option>
            <option value="dataconclusaovenda">Conclusão Venda</option>
            <option value="idpostoatendimento">ID P.Atendimento</option>
            <option value="tipointegracao">Tipo Integração</option>
            <option value="confirmacao">Confirmação</option>
            <option value="idintegracao">ID Integração</option>
            <option value="dataemissaovenda">Data Emissao Venda</option>
            <option value="fornecedor">Fornecedor</option>
            <option value="idproduto">ID Produto</option>
            <option value="nomepassageiro">Nome Passageiro</option>
            <option value="idsolicitacao">ID Solicitação</option>
            <option value="datacriacaovenda">Data Criação Venda</option>
            <option value="datachegada">Data Chegada</option>
            <option value="localizadorgds">Localizador GDS</option>
            <option value="postoatendimento">Posto de Atendimento</option>

        </select>
        <input type="text" />
        <button onclick="executa()">Pesquisar</button>
    </form>

Alguma dica?
Comment: Coloca o teu script no final da página. Do jeito que está o browser vai rodar o script antes de renderizar os elementos...
Comment: o jsfiddle contém autoload no corpo, então acredito que seja só fazer isso:  `$(function(){ //aqui seu codigo... });`
Comment: E no caso do jsfiddle que vc colocou: precisa de `ondomreadOnly`
Comment: @IvanFerrer não entendi o que você propôs, com o `ondomreadOnly`. Mas funcionou colocando o script no fim do `HTML`.
Comment: Não propus nada, só comentei que no jsfiddle que você publicou a opção "ondomreadOnly" está habilitada. O script não funcionará enquanto o seu body não estiver carregado. Por isso não funciona no começo.
Answer: Coloca o teu script no final da página. Do jeito que está o browser vai rodar o script antes de renderizar os elementos. Veja:

 <!DOCTYPE html>

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

    <form action="testeste.html" method="post">
        <select>
            <option value="trechoorigem">Trecho Origem</option>
            <option value="trechodestino">Trecho Destino</option>
            <option value="dataprocessamento">Data Processamento</option>
            <option value="statusintegracao">Status Integração</option>
            <option value="tipoproduto">Tipo Produto</option>
            <option value="datasaida">Data Saida</option>
            <option value="dataconclusaovenda">Conclusão Venda</option>
            <option value="idpostoatendimento">ID P.Atendimento</option>
            <option value="tipointegracao">Tipo Integração</option>
            <option value="confirmacao">Confirmação</option>
            <option value="idintegracao">ID Integração</option>
            <option value="dataemissaovenda">Data Emissao Venda</option>
            <option value="fornecedor">Fornecedor</option>
            <option value="idproduto">ID Produto</option>
            <option value="nomepassageiro">Nome Passageiro</option>
            <option value="idsolicitacao">ID Solicitação</option>
            <option value="datacriacaovenda">Data Criação Venda</option>
            <option value="datachegada">Data Chegada</option>
            <option value="localizadorgds">Localizador GDS</option>
            <option value="postoatendimento">Posto de Atendimento</option>

        </select>
        <input type="text" type="button"/>
        <button onclick="executa()">Pesquisar</button>
        </form>

Comment: É apenas parte do problema. De considerar também as alterações que ele fez no script original ao copiá-lo para o arquivo html.
Outro ponto é que ao se colocar um  sem um [type] definido dentro de um , o browser o trata como [type=submit], fazendo  postback toda vez que o botão for clicado.
Logo o button deve ter seu tipo especificado
Comment: @Moykn Deu certinho, valeu!!

Valeu ai também ai Emir!
Comment: Eu percebi que quando clico no botão ele executa normalmente o filtro, mas quando pressiono enter ele recarrega a página, sabe o motivo disso?
Comment: tem que ver em qual elemento o foco está posicionado


There exists $x \in \mathbb{R}$ such that the number $f(x)=x^2 +5x +4$ is prime."

Question: There exists $x \in \mathbb{R}$ such that the number $f(x)=x^2 +5x +4$ is prime.
I can't understand where to start.
This is what I have so far:
Let P(x) be the statement "$x^2 + 5x +4$ is prime".
Then we have $\exists x \in \mathbb{R}, P(x)$.
I built a table and I suspect that this is not true. Hence, I'm attempting to disprove this statement. Apart from doing a direct proof, I can try a contrapositive proof but I don't know how to start.
Appreciate all inputs.
Comment: When $x=0$ its 4 and when $x=1$ its 10. By continuity ...
Comment: $f(-2) = -2$ is a prime.
Comment: Note that $x^2 +5x +4=(x + 4) (x + 1)$ and so it is almost never a prime for $x \in \mathbb Z$. Only when one of the two factors is $\pm 1$; the only integer solutions are $x=-3,-2$, found by @achillehui.
Answer: $f$ is continuous, and since $f(-1)=0$ and $$\lim_{x\to\infty} f(x)=\infty,$$ you can show that for every $p>0$, there exists some $x\in\mathbb R$ such that $f(x)=p$. You don't even have to restrict yourself to primes, the function reaches every positive number!
Answer: The function goes to infinity as x goes to infinity. It is also continuous. Thus it assumes all sufficiently large real numbers. In particular it assumes all sufficiently large prime numbers.
Answer: You could solve the equation
$$
x^2 + 5x + 4 = 3
$$


When is the filter value available to a context filter in a view?

Question: There is very odd negative grammer for setting up Context filters in views.
I set a context filter to take a value from the URL (perhaps context filters are primarily for something else?)
However when I go to set it up I need to put my details into the field labelled
WHEN THE FILTER VALUE IS NOT AVAILABLE

This seems very odd to me, could someone explain to me When the filter is available?
I may not be making any sense but then again neither does that page!
Comment: When you talk about "that page", it would be nice to provide a link. Now we don't know what steps you followed, so we can't know what's wrong and where your problems came from. Alternatively, write step by step what you did, what you expected and what you got, without any references to external site. That would be preferable, actually.
Comment: Hi Molot, Thank you for your comment.  I'm just adding a context filter to a plain view on the core view creation page.  My question has been answered below.
Answer: At the very top of the contextual filter configuration window you have:

This display does not have a source for contextual filters, so no
  contextual filter value will be available unless you select 'Provide
  default'.

The answer to your question When the filter is available? is short:
The filter is available only if has been provided.
Let say, you want to show a block with the content that depend on node id. Obviously you don't want to provide the node id by yourself on each node to see what the block content is. You don't need to provide it, because the node id is in the URL, so it's available. Of course the node id is not always in the URL, for example if you're viewing a user profile or a list of recently added articles. That's why this fieldset has been labeled:
WHEN THE FILTER VALUE IS NOT AVAILABLE
In this fieldset you can decide what to do when the filter hasn't been provided (display all results? provide default? .. many options there..)
Comment: Thanks.  I see I was assuming that the source in the first instance is the URL but I see it is not.  Now it makes more sense.   Thank you.
Answer: Good one Toby,
As I understand it;
A contextual filter source can be anything; like if i have to embed a views from my code to output the result; I'd feed the contextual parameters as last param in views_embed_view();
Hence, The views page makes a little sense with the sentence 'WHEN THE FILTER VALUE IS NOT AVAILABLE', where you supply the secondary source of a contextual param.


How OpenMP divide a loop into threads?

Question: Say I have a loop
for(int i = 0; i < 1000; i++){
    sum += i;
}

And if I use OpenMP to speed up it, how is this for loop mapped to 4 different cores?
I know it uses fork and join, I mean is it like i=0 for core 0, i=1 for core 1 and etc or i=0 for core 0, i=249 for core 1, i = 499 for core 2 etc.
Thanks,
Bob
Comment: @Gangadhar Cool thanks I think that answered my question.
Comment: just check the wiki http://en.wikipedia.org/wiki/OpenMP it uses a fork join model
Comment: @pyCthon I know it use fork and join, I mean is it like i=0 for core 0, i=1 for core 1 and etc or i=0 for core 1, i=249 for core 2, i = 499 for core 3 etc.
Comment: @dorafmon see [OpenMP divide for loop over cores](http://stackoverflow.com/questions/8312563/openmp-divide-for-loop-over-cores)
Comment: It's such a trivial loop that it cannot sensibly mapped to multiple cores.  Even on the same box, the run time of such a loop is less than the inter-thread comms overhead in queueing it to a pool.
Comment: @MartinJames It is just an example, its not really what I am trying to optimise, instead I am working on a fair complex loop that involve some array index so I am asking this question to see if OpenMP is messing up with cache.
Answer: According to this presentation  it depends on the compiler implementation rather than the OpenMP spec, but the compiler would probably use i=0 for core 0, i=249 for core 1, etc.

Also make sure you are a reduction variable for sum, otherwise you have a race condition in your example.

How OpenMP divide a loop into threads?


Inequalities with single sided absolute values versus double sided absolute values

Question: I am trying to understand how the behavior between the absolute value(s) and the inequality sign differ between equations of the form:
\begin{equation}
|x| < a
\tag{1}
\label{1}
\end{equation}
for some $a \in \mathbb{R}$ and
\begin{equation}
|f(x)| < |g(x)|
\tag{2}
\label{2}
\end{equation}
for $f : D_1 \subseteq\mathbb{R} \to \mathbb{R}$ and $g : D_2 \subseteq\mathbb{R}\to\mathbb{R}$.
Specifically, I know that when one solves an equation like eq. $\ref{1}$, you do the following:

Solve $x < a$.
Solve $x > -a$.
Solve eq. $\ref{1}$ by taking the intersection of the solution found in steps 1. and 2.

I think of step 2. as first writing $-x < a$ (to make the LHS positive for the case when $x < 0$), and then multiplying both sides by $-1$, thereby flipping the inequality sign to get $x > -a$.
To solve eq. $\ref{2}$, you take each case separately, as shown in, for example, this question. However, in each of these cases, as far as I know, you do not switch the inequality sign like in step 2. for solving eq. $\ref{1}$.
Therefore, my question is why, conceptually, is this done for solving eq. $\ref{1}$, but not done in each case (i.e. when the argument of one of the absolute values is negative) when solving eq. $\ref{2}$.
Thanks in advance. I have been avoiding absolute values + inequalities for most of my career in mathematics; it's time I face them.
Answer: Note that the absolute value of a number equals its distance from $0$ which is always a non-negative number.
So the statement that $\vert x\vert<a$ tells us that $a$ is a positive number and that $x$ is closer to $0$ than $a$ is. From this we conclude that $x$ lies somewhere between $-a$ and $a$. In terms of inequalities
$$ -a<x\text{ and }x<a$$
A pair of inequalities connected by the word "and" [but not the word "or"] can be united in a combined inequality provided both inequalities are in the same direction. So the pair of inequalities above can be written in combined form as
$$-a<x<a$$
which is read as "negative $a$ is less than $x$ and $x$ is less than $a$" or more simply $x$ is between negative $a$ and positive $a$.
Now for the case where $|f(x)|<|g(x)|$.
Note that for non-negative numbers, the function $y=x^2$ is increasing. So it follows that  $0\le a<b$ if and only if $a^2<b^2$. Therefore
$$ |f(x)|<|g(x)|\text{ iff }f^2(x)<g^2(x) $$
which is equivalent to
$$ g^2(x)-f^2(x)>0 $$
which is equivalent to
$$ [g(x)-f(x)]\cdot[g(x)+f(x)]>0 $$
which is true if and only if $g(x)-f(x)$ and $g(x)+f(x)$ are both the same sign--both positive or both negative.
Ultimately, it means that $f(x)$ must always lie between $g(x)$ and $-g(x)$. That is
Either

$-g(x)<f(x)<g(x)$ or
$g(x)<f(x)<-g(x)$.

So to find the solution set of $|f(x)|<|g(x)|$ you would find the solution of both 1 and 2 and take their union since the two inequalities are connected by the word "or."
Comment: Thank you. Fixed.
Comment: I added a bit about the $|f(x)|<|g(x)$ case.
Comment: You meant to write $|f(x)\color{red}{|} < |g(x)|~\text{iff}~f^2(x) < g^2(x)$.
Comment: @N.F.Taussig Thanks


Generate an Average in SQLite

Question: In my app I have 4 activities, each activity is associated to a table in my SQLite database.

Leagues = League
Table Bowlers = Bowler Table
Series = Series Table
Games = Game Table

I am trying to figure out what would be the best way to generate an average score for each Series.  The Game id's  are not generated until a new game is added to the series.
By the time a bowler enters in his/her scores the id's might look something  like this;

League id = 1
Bowler id = 3
Series id = 6
Game id's = 9,10,11

What would be the best solution for generating the average for Series id 6.  I was thinking that the average should be generated each time a score is entered and written to an average field in the Series table.  Any ideas?
Method that lists games for a bowler:
public List<Game> getAllGames(String leagueId, String bowlerId, String seriesId) {
        List<Game> games = new ArrayList<>();

        //Select All Query
        String selectQuery = "SELECT  * FROM " + Game.TABLE_NAME + " WHERE " + Game.COLUMN_LEAGUE_ID + " = '" + leagueId + "'" + " AND " + Game.COLUMN_BOWLER_ID + " = '" + bowlerId + "'" + " AND " + Game.COLUMN_SERIES_ID + " = '" + seriesId + "'" + " ORDER BY " +
                Game.COLUMN_TIMESTAMP + " DESC";

        try (SQLiteDatabase db = this.getWritableDatabase()) {
            @SuppressLint("Recycle") Cursor cursor = db.rawQuery( selectQuery, null );

            //Looping Through All Rows And Adding To The List
            if (cursor.moveToFirst()) {
                do {
                    Game game1 = new Game();
                    game1.setId(cursor.getInt(cursor.getColumnIndex(Game.COLUMN_ID ) ) );
                    game1.setLeagueId(cursor.getString(cursor.getColumnIndex(Game.COLUMN_LEAGUE_ID)));
                    game1.setBowlerId(cursor.getString(cursor.getColumnIndex(Game.COLUMN_BOWLER_ID)));
                    game1.setSeriesId(cursor.getString(cursor.getColumnIndex(Game.COLUMN_SERIES_ID)));
                    game1.setScore(cursor.getString(cursor.getColumnIndex(Game.COLUMN_SCORE)));
                    game1.setStrikes(cursor.getString(cursor.getColumnIndex(Game.COLUMN_STRIKES)));
                    game1.setSpares(cursor.getString(cursor.getColumnIndex(Game.COLUMN_SPARES)));
                    game1.setSplits(cursor.getString(cursor.getColumnIndex(Game.COLUMN_SPLITS)));
                    game1.setSplitConversions(cursor.getString(cursor.getColumnIndex(Game.COLUMN_SPLIT_CONVERSIONS)));
                    game1.setOpenFrames(cursor.getString(cursor.getColumnIndex(Game.COLUMN_OPEN_FRAMES)));
                    game1.setTimestamp(cursor.getString(cursor.getColumnIndex(Game.COLUMN_TIMESTAMP)));
                    games.add( game1 );
                } while (cursor.moveToNext());
            }

            //Close Database Connection
            db.close();
        }

        //Return Game List
        return games;
    }

I was thinking that since I am list all the games for a bowler using the above code, I could just add up the scores as I load them into the listview.  How would I go about accomplishing something like this?
DatabaseHelper
public class DatabaseHelper extends SQLiteOpenHelper {

    //Database Version
    private static final int DATABASE_VERSION = 1;

    //Database Name
    private static final String DATABASE_NAME = "tpc_database";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    //Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL(League.CREATE_TABLE);
        db.execSQL(Bowler.CREATE_TABLE);
        db.execSQL(Series.CREATE_TABLE);
        db.execSQL(Game.CREATE_TABLE);

    }

    //Upgrade Database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        //Drop Older Table If It Existed
        db.execSQL("DROP TABLE IF EXISTS " + League.TABLE_NAME);
        db.execSQL("DROP TABLE IF EXISTS " + Bowler.TABLE_NAME);
        db.execSQL("DROP TABLE IF EXISTS " + Series.TABLE_NAME);
        db.execSQL("DROP TABLE IF EXISTS " + Game.TABLE_NAME);

        //Create Tables Again
        onCreate( db );
    }

    //************************                ************************
    //************************ League Methods ************************
    //************************                ************************

    public long insertLeague(String leagueName) {
        //Get Writable Database That We Want To Write Data Too
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();

        //`id` and `timestamp` Will Be Inserted Aromatically
        values.put(League.COLUMN_NAME, leagueName);

        //Insert Row
        long id = db.insert(League.TABLE_NAME, null, values);

        //Close Database Connection
        db.close();

        //Return Newly Inserted Row Id
        return id;
    }

    public League getLeague(long id) {
        //Get Readable Database If We Are Not Inserting Anything
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(League.TABLE_NAME,
                new String[]{League.COLUMN_ID, League.COLUMN_NAME, League.COLUMN_TIMESTAMP},
                League.COLUMN_ID + "=?",
                new String[]{String.valueOf(id)}, null, null, null, null);

        if (cursor.moveToFirst()) {

            //Prepare League Object
            League league = new League(
                    cursor.getInt(cursor.getColumnIndex(League.COLUMN_ID)),
                    cursor.getString(cursor.getColumnIndex(League.COLUMN_NAME)),
                    cursor.getString(cursor.getColumnIndex(League.COLUMN_TIMESTAMP)));

            //Close Database Connection
            cursor.close();
            return league;
        } else {
            return null;
        }
    }

    public List<League> getAllLeagues() {
        List<League> leagues = new ArrayList<>();

        //Select All Query
        String selectQuery = "SELECT  * FROM " + League.TABLE_NAME + " ORDER BY " +
                League.COLUMN_TIMESTAMP + " DESC";

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        //Looping Through All Rows And Adding To The List
        if (cursor.moveToFirst()) {
            do {
                League league = new League();
                league.setId(cursor.getInt(cursor.getColumnIndex(League.COLUMN_ID)));
                league.setName(cursor.getString(cursor.getColumnIndex(League.COLUMN_NAME)));
                league.setTimestamp(cursor.getString(cursor.getColumnIndex(League.COLUMN_TIMESTAMP)));

                leagues.add(league);
            } while (cursor.moveToNext());
        }
        cursor.close();
        //Close Database Connection
        db.close();

        //Return League List
        return leagues;
    }

    public int getLeaguesCount() {
        String countQuery = "SELECT  * FROM " + League.TABLE_NAME;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);

        int count = cursor.getCount();
        cursor.close();

        //Return The Count
        return count;
    }

    public int updateLeague(League league) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put( League.COLUMN_NAME, league.getName() );

        //Updating Row
        return db.update(League.TABLE_NAME, values, League.COLUMN_ID + " = ?",
                new String[]{String.valueOf(league.getId())});
    }

    public void deleteLeague(League league) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(League.TABLE_NAME, League.COLUMN_ID + " = ?",
                new String[]{String.valueOf( league.getId())});
        db.close();
    }

    //************************                ************************
    //************************ Bowler Methods ************************
    //************************                ************************

    public long insertBowler(String leagueId, String bowlerName) {
        //Get Writable Database That We Want To Write Data Too
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();

        //`id` and `timestamp` Will Be Inserted Automatically
        values.put(Bowler.COLUMN_LEAGUE_ID, leagueId);
        values.put(Bowler.COLUMN_NAME, bowlerName);

        //Insert Row
        //long id = db.insert(Bowler.TABLE_NAME, null, values);
        long id = db.insertOrThrow( Bowler.TABLE_NAME, null, values );
        Log.d("INSERTBOWLER","Number of bowlers in db = " + String.valueOf( DatabaseUtils.queryNumEntries(db,Bowler.TABLE_NAME)));
        //Close Database Connection
        db.close();

        //Return Newly Inserted Row Id
        return id;
    }

    public Bowler getBowler(String leagueId) {
        //Get Readable Database If We Are Not Inserting Anything
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query( Bowler.TABLE_NAME,
                new String[]{Bowler.COLUMN_ID, Bowler.COLUMN_LEAGUE_ID, Bowler.COLUMN_NAME, Bowler.COLUMN_TIMESTAMP},
                Bowler.COLUMN_LEAGUE_ID + "=?",
                new String[]{String.valueOf(leagueId)}, null, null, null, null);

        Bowler bowler = null;
        if (cursor.moveToFirst()) {

            //Prepare Bowler Object
            bowler = new Bowler(
                    cursor.getInt(cursor.getColumnIndex(Bowler.COLUMN_ID)),
                    cursor.getString(cursor.getColumnIndex(Bowler.COLUMN_LEAGUE_ID)),
                    cursor.getString(cursor.getColumnIndex(Bowler.COLUMN_NAME)),
                    cursor.getString(cursor.getColumnIndex(Bowler.COLUMN_TIMESTAMP)));

            //Close Database Connection
            cursor.close();
            return bowler;
        } else {
            return bowler;
        }
    }
    public List<Bowler> getAllBowlers(String leagueId) {
        List<Bowler> bowlers = new ArrayList<>();

        //Select All Query
        String selectQuery = "SELECT  * FROM " + Bowler.TABLE_NAME + " WHERE " + Bowler.COLUMN_LEAGUE_ID + " = '" + leagueId + "'" + " ORDER BY " +
                Bowler.COLUMN_TIMESTAMP + " DESC";

        Log.d("GETALLBOWLERS-SQL","SQL used = >>>>" +selectQuery + "<<<<");

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        Log.d("GETALLBOWLERS-CNT","Number of rows retrieved = " + String.valueOf(cursor.getCount()));

        //Looping Through All Rows And Adding To The List
        if (cursor.moveToFirst()) {
            do {
                Bowler bowler = new Bowler();
                bowler.setId(cursor.getInt(cursor.getColumnIndex(Bowler.COLUMN_ID)));
                bowler.setLeagueId(cursor.getString(cursor.getColumnIndex(Bowler.COLUMN_LEAGUE_ID)));
                bowler.setName(cursor.getString(cursor.getColumnIndex(Bowler.COLUMN_NAME)));
                bowler.setTimestamp(cursor.getString(cursor.getColumnIndex(Bowler.COLUMN_TIMESTAMP)));
                bowlers.add(bowler);
            } while (cursor.moveToNext());
        }
        cursor.close();
        //Close Database Connection
        db.close();
        Log.d("GETALLBOWLERS-CNT","Number of elements in bowlerslist = " + String.valueOf(bowlers.size()));

        //Return Bowlers List
        return bowlers;
    }

    public int getBowlersCount() {
        String countQuery = "SELECT  * FROM " + Bowler.TABLE_NAME;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);

        int count = cursor.getCount();
        cursor.close();

        //Return The Count
        return count;
    }

    public int updateBowler(Bowler bowler) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(Bowler.COLUMN_LEAGUE_ID, bowler.getLeagueId());
        values.put(Bowler.COLUMN_NAME, bowler.getName());

        //Updating Row
        return db.update(Bowler.TABLE_NAME, values, Bowler.COLUMN_ID + " = ?",
                new String[]{String.valueOf(bowler.getId())});
    }

    public void deleteBowler(Bowler bowler) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete( Bowler.TABLE_NAME, Bowler.COLUMN_ID + " = ?",
                new String[]{String.valueOf( bowler.getId())});
        db.close();
    }

    //************************                ************************
    //************************ Series Methods ************************
    //************************                ************************

    public long insertSeries(String leagueId, String bowlerId, String seriesName) {

        //Get Writable Database That We Want To Write Data Too
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        //`id` and `timestamp` Will Be Inserted Automatically
        values.put(Series.COLUMN_LEAGUE_ID, leagueId);
        values.put(Series.COLUMN_BOWLER_ID, bowlerId);
        values.put(Series.COLUMN_NAME, seriesName);

        //Insert Row
        //long id = db.insert( Series.TABLE_NAME, null, values );
        long id = db.insertOrThrow( Series.TABLE_NAME, null, values );
        Log.d("INSERT SERIES","Number of series in db = " + String.valueOf( DatabaseUtils.queryNumEntries(db,Series.TABLE_NAME)));

        //Close Database Connection
        db.close();

        //Return Newly Inserted Row Id
        return id;
    }

    public Series getSeries(String leagueId, String bowlerId) {
        //Get Readable Database If We Are Not Inserting Anything
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query( Series.TABLE_NAME,
                new String[]{Series.COLUMN_ID, Series.COLUMN_LEAGUE_ID, Series.COLUMN_BOWLER_ID,
                        Series.COLUMN_NAME, Series.COLUMN_SERIES_AVERAGE, Series.COLUMN_TIMESTAMP},
                Series.COLUMN_LEAGUE_ID + "=?" + " AND " +  Series.COLUMN_BOWLER_ID + "=?",
                new String[]{String.valueOf(leagueId), String.valueOf(bowlerId)}, null, null, null, null);

        if (cursor.moveToFirst()) {

            //Prepare Series Object
            Series series = new Series(
                    cursor.getInt(cursor.getColumnIndex(Series.COLUMN_ID)),
                    cursor.getString(cursor.getColumnIndex(Series.COLUMN_LEAGUE_ID)),
                    cursor.getString(cursor.getColumnIndex(Series.COLUMN_BOWLER_ID)),
                    cursor.getString(cursor.getColumnIndex(Series.COLUMN_NAME)),
                    cursor.getString(cursor.getColumnIndex(Series.COLUMN_SERIES_AVERAGE)),
                    cursor.getString(cursor.getColumnIndex(Series.COLUMN_TIMESTAMP)));

            //Close Database Connection
            cursor.close();
            return series;
        } else {
            return null;
        }
    }

    public List<Series> getAllSeries(String leagueId, String bowlerId) {
        List<Series> series = new ArrayList<>();

        //Select All Query
        String selectQuery = "SELECT * FROM " + Series.TABLE_NAME + " WHERE " + Series.COLUMN_LEAGUE_ID + " = '" + leagueId + "'" + " AND " + Series.COLUMN_BOWLER_ID + " = '" + bowlerId + "'"+ " ORDER BY " +
                Series.COLUMN_TIMESTAMP + " DESC";

        Log.d("GET ALL SERIES-SQL","SQL used = >>>>" +selectQuery + "<<<<");

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        Log.d("GET ALL SERIESS-CNT","Number of rows retrieved = " + String.valueOf(cursor.getCount()));

        //Looping Through All Rows And Adding To The List
        if (cursor.moveToFirst()) {
            do {
                Series series1 = new Series();
                series1.setId(cursor.getInt(cursor.getColumnIndex(Series.COLUMN_ID)));
                series1.setLeagueId(cursor.getString(cursor.getColumnIndex(Series.COLUMN_LEAGUE_ID)));
                series1.setBowlerId(cursor.getString(cursor.getColumnIndex(Series.COLUMN_BOWLER_ID)));
                series1.setName(cursor.getString(cursor.getColumnIndex(Series.COLUMN_NAME)));
                series1.setAverage(cursor.getString(cursor.getColumnIndex(Series.COLUMN_SERIES_AVERAGE)));
                series1.setTimestamp(cursor.getString(cursor.getColumnIndex(Series.COLUMN_TIMESTAMP)));
                series.add(series1);
            } while (cursor.moveToNext());
        }
        cursor.close();
        //Close Database Connection
        db.close();
        Log.d("GETALLSERIES-CNT","Number of elements in serieslist = " + String.valueOf(series.size()));
        //Return Series List
        return series;
    }

    public int getSeriesCount() {
        String countQuery = "SELECT  * FROM " + Series.TABLE_NAME;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery( countQuery, null );

        int count = cursor.getCount();
        cursor.close();

        //Return The Count
        return count;
    }

    public int updateSeries(Series series) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(Series.COLUMN_LEAGUE_ID, series.getLeagueId());
        values.put(Series.COLUMN_BOWLER_ID, series.getBowlerId());
        values.put(Series.COLUMN_NAME, series.getName());
        values.put(Series.COLUMN_SERIES_AVERAGE,series.getAverage());

        //Updating Row
        return db.update( Series.TABLE_NAME, values, Series.COLUMN_ID + " = ?",
                new String[]{String.valueOf( series.getId() )} );

    }

    public void deleteSeries(Series series) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete( Series.TABLE_NAME, Series.COLUMN_ID + " = ?",
                new String[]{String.valueOf( series.getId() )} );
        db.close();
    }

    //************************                ************************
    //************************  Game Methods  ************************
    //************************                ************************

    public long insertGame(String leagueId, String bowlerId, String seriesId, String score, String strikes, String spares, String splits, String splitConversions, String openFrames) {

        //Get Writable Database That We Want To Write Data Too
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        //`id` and `timestamp` Will Be Inserted Automatically
        values.put(Game.COLUMN_LEAGUE_ID, leagueId);
        values.put(Game.COLUMN_BOWLER_ID, bowlerId);
        values.put(Game.COLUMN_SERIES_ID, seriesId);
        values.put(Game.COLUMN_SCORE, score);
        values.put(Game.COLUMN_STRIKES, strikes);
        values.put(Game.COLUMN_SPARES, spares);
        values.put(Game.COLUMN_SPLITS, splits);
        values.put(Game.COLUMN_SPLIT_CONVERSIONS, splitConversions);
        values.put(Game.COLUMN_OPEN_FRAMES, openFrames);

        //Insert Row
        long id = db.insert( Game.TABLE_NAME, null, values );

        //Close Database Connection
        db.close();

        //Return Newly Inserted Row Id
        return id;
    }

    public Game getGame(String leagueId, String bowlerId, String seriesId) {
        //Get Readable Database If We Are Not Inserting Anything
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query( Game.TABLE_NAME,
                new String[]{Game.COLUMN_ID, Game.COLUMN_LEAGUE_ID, Game.COLUMN_BOWLER_ID,
                        Game.COLUMN_SERIES_ID, Game.COLUMN_SCORE, Game.COLUMN_STRIKES, Game.COLUMN_SPARES, Game.COLUMN_SPLITS, Game.COLUMN_SPLIT_CONVERSIONS, Game.COLUMN_OPEN_FRAMES, Game.COLUMN_TIMESTAMP},
                Game.COLUMN_LEAGUE_ID + "=?" + " AND " + Game.COLUMN_BOWLER_ID + "=?" + " AND " + Game.COLUMN_SERIES_ID + "=?",
                new String[]{String.valueOf( leagueId ), String.valueOf( bowlerId ), String.valueOf( seriesId )}, null, null, null, null );

        if (cursor.moveToFirst()) {

            //Prepare Game Object
            Game game = new Game(
                    cursor.getInt( cursor.getColumnIndex(Game.COLUMN_ID)),
                    cursor.getString( cursor.getColumnIndex(Game.COLUMN_LEAGUE_ID)),
                    cursor.getString( cursor.getColumnIndex(Game.COLUMN_BOWLER_ID)),
                    cursor.getString( cursor.getColumnIndex(Game.COLUMN_SERIES_ID)),
                    cursor.getString( cursor.getColumnIndex(Game.COLUMN_SCORE)),
                    cursor.getString( cursor.getColumnIndex(Game.COLUMN_STRIKES)),
                    cursor.getString( cursor.getColumnIndex(Game.COLUMN_SPARES)),
                    cursor.getString( cursor.getColumnIndex(Game.COLUMN_SPLITS)),
                    cursor.getString( cursor.getColumnIndex(Game.COLUMN_SPLIT_CONVERSIONS)),
                    cursor.getString( cursor.getColumnIndex(Game.COLUMN_OPEN_FRAMES)),
                    cursor.getString( cursor.getColumnIndex(Game.COLUMN_TIMESTAMP)));

            //Close Database Connection
            cursor.close();
            return game;
        } else {
            return null;
        }
    }

    public List<Game> getAllGames(String leagueId, String bowlerId, String seriesId) {
        List<Game> games = new ArrayList<>();

        //Select All Query
        String selectQuery = "SELECT  * FROM " + Game.TABLE_NAME + " WHERE " + Game.COLUMN_LEAGUE_ID + " = '" + leagueId + "'" + " AND " + Game.COLUMN_BOWLER_ID + " = '" + bowlerId + "'" + " AND " + Game.COLUMN_SERIES_ID + " = '" + seriesId + "'" + " ORDER BY " +
                Game.COLUMN_TIMESTAMP + " DESC";

        try (SQLiteDatabase db = this.getWritableDatabase()) {
            @SuppressLint("Recycle") Cursor cursor = db.rawQuery( selectQuery, null );

            //Looping Through All Rows And Adding To The List
            if (cursor.moveToFirst()) {
                do {
                    Game game1 = new Game();
                    game1.setId(cursor.getInt(cursor.getColumnIndex(Game.COLUMN_ID ) ) );
                    game1.setLeagueId(cursor.getString(cursor.getColumnIndex(Game.COLUMN_LEAGUE_ID)));
                    game1.setBowlerId(cursor.getString(cursor.getColumnIndex(Game.COLUMN_BOWLER_ID)));
                    game1.setSeriesId(cursor.getString(cursor.getColumnIndex(Game.COLUMN_SERIES_ID)));
                    game1.setScore(cursor.getString(cursor.getColumnIndex(Game.COLUMN_SCORE)));
                    game1.setStrikes(cursor.getString(cursor.getColumnIndex(Game.COLUMN_STRIKES)));
                    game1.setSpares(cursor.getString(cursor.getColumnIndex(Game.COLUMN_SPARES)));
                    game1.setSplits(cursor.getString(cursor.getColumnIndex(Game.COLUMN_SPLITS)));
                    game1.setSplitConversions(cursor.getString(cursor.getColumnIndex(Game.COLUMN_SPLIT_CONVERSIONS)));
                    game1.setOpenFrames(cursor.getString(cursor.getColumnIndex(Game.COLUMN_OPEN_FRAMES)));
                    game1.setTimestamp(cursor.getString(cursor.getColumnIndex(Game.COLUMN_TIMESTAMP)));
                    games.add( game1 );
                } while (cursor.moveToNext());
            }

            //Close Database Connection
            db.close();
        }

        //Return Game List
        return games;
    }

    public int getGameCount() {
        String countQuery = "SELECT  * FROM " + Game.TABLE_NAME;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery( countQuery, null );

        int count = cursor.getCount();
        cursor.close();

        //Return The Count
        return count;
    }

    public int updateGame(Game game) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(Game.COLUMN_LEAGUE_ID, game.getLeagueId());
        values.put(Game.COLUMN_BOWLER_ID, game.getBowlerId());
        values.put(Game.COLUMN_SERIES_ID, game.getSeriesId());
        values.put(Game.COLUMN_SCORE, game.getScore());
        values.put(Game.COLUMN_STRIKES, game.getStrikes());
        values.put(Game.COLUMN_SPARES, game.getSpares());
        values.put(Game.COLUMN_SPLITS, game.getSplits());
        values.put(Game.COLUMN_SPLIT_CONVERSIONS, game.getSplitConversions());
        values.put(Game.COLUMN_OPEN_FRAMES, game.getOpenFrames());

        //Updating Row
        return db.update( Game.TABLE_NAME, values, Game.COLUMN_ID + " = ?",
                new String[]{String.valueOf( game.getId() )} );

    }

    public void deleteGame(Game game) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(Game.TABLE_NAME, Game.COLUMN_ID + " = ?",
                new String[]{String.valueOf( game.getId() )} );
        db.close();
    }
}

Answer: sqlite> create table test (a int);
sqlite> insert into test values (1);
sqlite> insert into test values (2);
sqlite> insert into test values (3);
sqlite> insert into test values (4);
sqlite> select avg(a) as average, count(a) as count, sum(a) as sum from test;
average     count       sum
----------  ----------  ----------
2.5         4           10
sqlite> select avg(a) as average, count(a) as count, sum(a) as sum from test
  where a > 2;
average     count       sum
----------  ----------  ----------
3.5         2           7

Comment: Yes- there are a number of [core math functions](https://sqlite.org/lang_corefunc.html).
Comment: I tried to follow the link above but I am getting the following "Document Not Found
The document /lang_corefunc.html_ is not available on this server"
Comment: How can I assign the results of avg(col) to a variable.
Comment: Remove the underscore from the end of the URL.  You would assign the results of a query to a variable the same way you're doing it in your posting- it's just a column value like anything else.
Comment: If the results for avg(col) is just another column in the table, is it safe to assume that the column name is avg or average?
Comment: by default, it will be `avg(col)`, where `col` is the name of the column.  I suggest using `AS` to rename the column to something sensible.
Comment: Just so I am clear on what your saying.  If my column name is COLUMN_SCORE and use avg(COLUMN_SCORE), the column name with be avg(COLUMN_SCORE), so by use avg(COLUMN_SCORE) AS AVERAGE_SCORE, my column name will be AVERAGE_SCORE.  Do I access it by using [TABLE_NAME].AVERAGE_SCORE?
Comment: the math functions are all aggregate functions- that is, you can't directly have them in a table.  You can, however, create views: `create view average as select avg(a) from test;`
Answer: I can't really understand what you want, but if you want to get the average of all colums in a table than do the following:
1 Add all Series id's. (For adding: Put all values in an Array and use array_sum())
2 Use mysqli_num_rows() and count all rows from your table

How to get the average:
Add up all the numbers, then divide by how many numbers there are. In other words it is the sum divided by the count.

3 Divide the Array sum by the number of all your rows.
Comment: I am trying to get the average score of all the games in the Game table that correspond to a series of id's then write the average score to the Series table to be displayed with the particular Series that matches the games.
Comment: question was specifically about SQLite.

Generate an Average in SQLite


Spring Java Login without Spring Security

Question: I moved to creating my proper login without security, and would like to know how to test if the result of an Hibernate query got a result or not cause now my managedbean login method always returns a SUCCESS result, wether the login is correct or not :
Managed Bean :
public String login (){
        try {
            getUsermanagerService().logUser(username, password);

            return SUCCESS;
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        return ERROR;
    }

DAOImpl :
public UserData logUser(String username, String password) {

List<UserData> userList = new ArrayList<UserData>();
Query query = openSession().createQuery("from UserData u where u.username = :Username and u.password = :Password");
query.setParameter("Username", username);
query.setParameter("Password", password);
userList = query.list();
if (userList.size() > 0)
    return userList.get(0);
else
    return null;}

ServiceImpl :
public UserData logUser(String username, String password) {
    return getUsermanagerDAO().logUser(username, password);

}

Answer: Your logic has error.
 try {
        getUsermanagerService().logUser(username, password);

        return SUCCESS;
    } catch (DataAccessException e) {
        e.printStackTrace();
    }

When user aren't in DB, query will be empty and you will not have any exception. May be, you must check
if (getUsermanagerService().logUser(username, password) != null) return SUCCESS; else ERROR;

And if you want use information about
authorized user, you must return User class and use it? But this is another story.


Chebyshev polynomials and trace of $A \in SL_2(\mathbb{C})$

Question:
Defining $C_n(z) = \frac{z^m + z^{-m}}{2}$, the Chebyshev polynomials are defined by
$$T_n(C_1(z)) = C_n(z)$$
  and are given by $T_1(z) = z, T_2(z) = 2z^2-1, T_3(z) = 4z^3-3z$, etc. Since for $z=e^{i\theta}$ we have $C_1(z) = \cos\theta$, they also satisfy
$$T_n(\cos\theta) = \cos(n\theta)$$
thereby generalizing the double angle trig identity.

The notes I'm reading also claim $$T_n(\text{tr } A/2) = \text{tr } (A^n/2)$$ for $A \in SL_2(\mathbb{C})$. Why does this follow?
Attempt: if $A= \begin{pmatrix} a&b \\ c &d \end{pmatrix}$ then choosing $z=\frac12(\sqrt{(a+d)^2-4}- (a+d))$ implies $C_1(z) = \text{tr }A/2$, but then $T_n(C_1(z)) = \frac{z^n+z^{-n}}{2}$ does not simplify as far as I see to $\text{tr} A^n/2$.
Comment: Note that the trace of $A$ is the sum of its eigenvalues and the product of its eigenvalues is by definition $1$.
Comment: @WimC thanks, that resolves it
Answer: I found several sources with a proof, e.g., the paper by Francis Bonahon, Lemma $8$ on page $9$, using Cayley-Hamilton. Another interesting reference is the paper by Traina on trace polynomials for $SL_2(\Bbb{C})$.