Não consigo encontrar este (error expected declaration or statement at end of input)

Question: Sou novo nessa ramo de programação, estou fazendo um projeto, assistindo um curso e tentando inserir o que aprendo no meu programa, o principal erro que está dando agora é "error expected declaration or statement at end of input", sei que é um erro simples, mas realmente não consegui encontrar, por falta de tempo, também tentei empregar um sistema de buscas no case 2 que vi em outro código, não sei se fiz certo, sei que há muitos erros neste código, caso possam me ajudar, estou bem dispostO a aprender, segue o código abaixo:
#include <stdio.h>//Biblioteca padrão
#include <stdlib.h> //Necessário para system("pause");

int numero; //Variavel global

int main(void) { //função principal do programa
//Inicio da função main

char op; // para usar o do while

do {   //retornar caso a opção desejada não seja valida

    //Criando uma Struct
    struct professores_cursinho //professores_cursinho passa a ser um tipo de dados

    {
        //Abrindo e inserindo coleção de variaveis a struct
        char Nome[40], Disciplina[30];
        int Idade, Carga_Horaria;
        float Salario;
    }; //Final da definição da struct

    struct professores_cursinho Professor[20];// "Professor" agora é uma variável do tipo professores_cursinho, ele possui todas as variáveis que contem na struct

    printf("\n ---------- Escolha uma opcao: --------- \n");
    printf("1 - Cadastrar Professor\n");
    printf("2 - Buscar Professor\n");
    printf("3 - Sair do Programa\n\n");
    printf("Digite sua opcao: ");
    scanf("%d", &numero); //Mandar para variavel global "numero"

    switch(numero) {
        case 1:

            printf("\n---------- Cadastro de Professor ----------\n\n\n");

            printf("Nome do Professor: ");
            fflush(stdin);//Para limpar o buffer do teclado

            /* Usaremos o comando fgets() para ler string, no caso do nome
            do professor e a disciplina
            fgets(variavel, tamanho da string, entrada)
            como estamos lendo com o teclado a entrada é stdin(entrada padrão)
            porém, em outro caso, a entrada também pode ser arquivo*/

            fgets(Professor[20].Nome, 40, stdin);

            printf("Nome da Disciplina: ");
            fflush(stdin);//Para limpar o buffer do teclado
            fgets(Professor[20].Disciplina, 30, stdin);

            printf("Informe a Idade: ");
            scanf("%d", &Professor[20].Idade);

            printf("Informe a Carga Horaria: ");
            scanf("%d", &Professor[20].Carga_Horaria);

            printf("Informe o Salario: ");
            scanf("%f", &Professor[20].Salario);

            printf("\n\n---------- Lendo os dados da struct ----------\n\n");
            printf("Nome: %s", Professor[20].Nome);
            printf("Disciplina: %s ", Professor[20].Disciplina);
            printf("Idade: %d ", Professor[20].Idade);
            printf("Carga Horaria: %d\n ", Professor[20].Carga_Horaria);
            printf("Salario: %.2f\n ", Professor[20].Salario);

            system("cls"); //para limpar a tela e retornar ao menu principal
            break;

        case 2:
            //Inserir aqui o sistema de busca
            printf("\nDigite o nome do professor: ");
            int posicao = 5;
            char auxiliar[20];
            scanf("%s", auxiliar);

            int i;
            for (i = 0; i < Professor; i++) {
                if (strcmp(auxiliar, Professor[20].Nome[i]) == 0) {
                    posicao = i;
                    break;
                }
            }
            if (posicao != 5) {

                printf("NOME: %s\n", Professor[20].Nome);
                printf("DISCIPLINA: %s\n", Professor[20].Disciplina);
                printf("IDADE: %d\n", Professor[20].Idade);
                printf("CARGA HORARIA: %d\n", Professor[20].Carga_Horaria);
                printf("SALARIO: %f\n", Professor[20].Salario);

            } else {

                printf("\n----- PROFESSOR NAO ENCONTRADO! -----\n\n");
            }

            system("pause");
            system("cls");
            break;

        case 3:
            printf("\n---------- OBRIGADO POR UTILIZAR O PROGRAMA :) ----------\n\n");
            break;
        default:
            printf("DIGITE UMA OPCAO VALIDA");
            break;

    }
    while (op != 3);

    return 0;
}

Comment: Você esqueceu de adicionar um `}` para fechar o `switch` (ou o `do` dependendo da perspectiva). Então, antes da linha `while (op != 3);` adicione uma chave e o seu programa vai compilar.
Comment: poderia formatar o código para melhor exibição? É possível editar a pergunta para fazer as correções.
Comment: Estou tendo dificuldades em inserir o código, mas formatei, cortou a parte até int main(void)
Comment: Sim, basta endentar corretamente, existe um botão na interface para facilitar a formatação. O nome do botão é `code`.
Comment: Certo, consegui.
Comment: A parte isso, o seu programa  tem alguns erros que vão impedir ele de  funcionar. Por exemplo, você declara o array `Professor` para conter 20 elementos, e durante todo o programa a única posição do array que você acessa é a 21ª com `Professor[20]`, isso não apenas corrompe a memória como faz com que o seu sistema de cadastro não funcione.  Usar `fflush(stdin);` é simplesmente um erro. `i < Professor` está errado já que `Professor` não é um inteiro. Sugestão: não é incomum a primeira versão de um código ter erros, então, use essa oportunidade para aprender a debugar um programa.
Answer: Você esta tendo problema de sintaxe. Deve estar esquecendo um ; ou } em algum lugar de seu programa, recomendo que o leia com paciência e se atenha a endentação. Por exemplo
int main(){
    do{
        switch(numero){
            case 1:
            break;
        }
    }while(op != 3);
    return 0;
}

recomendo usar o visual studio code com puglins de C/C++.


Cardinality of a set of Continuous and Real Functions in the interval $[0,1]$

Question: my question reads as:

Let $\mathcal R[0,1]$ denote the set of all real-valued functions from $[0,1]$ to $\mathbb R$ and let $\mathcal C[0,1]$ denote the set of continuous functions on $[0,1]$.
  i) Prove that $|\mathcal C[0,1]|=|\mathbb R$|.
  ii) Prove that $|\mathcal R[0,1]|>|\mathbb R$|.

I've been fairly confident in my work with cardinality, but with a set containing functions, I am finding it hard to get a lead.
Thank you in advanced for your help.
Comment: I am sure you can find these questions answered on this site several times (maybe in some equivalent form). For example: http://math.stackexchange.com/questions/477/cardinality-of-set-of-real-continuous-functions and http://math.stackexchange.com/questions/17914/cardinality-of-the-set-of-all-real-functions-of-real-variable or http://math.stackexchange.com/questions/478294/the-set-of-all-real-functions-defined-on-0-1-has-cardinal-number-2c (Some of them were listed among related questions on the right.)
Answer: I would give you some hints here.
For the first one, you can use the fact that if $f, g\in C [0,1]$ satisfies $f(x) = g(x)$ for all $x\in \mathscr D$, where $\mathscr D$ is a dense subset of $[0,1]$, then $f\equiv g$. Here you can choose $\mathscr D$ to be countable. Then think of $|\{ f:\mathscr D \to \mathbb R\}|$. (The set of all real-valued function from $\mathscr D$).
For the second one, try to construct an injection $P([0,1]) \to R[0,1]$ where $P([0,1])$ is the power set of $[0,1]$. Then use (or prove) $|[0,1]|=|\mathbb R|$.
Comment: To construct the injection for the second one you can generalise the proof I gave in http://math.stackexchange.com/questions/707705/what-is-the-cardinality-of-the-set-of-all-infinite-sequences/710825#710825
Comment: For the first one you can choose D as the rationals and use a simple $\epsilon, \delta$ proof to show that continuous functions from R -> R are equivalent to functions from Q -> R. But I'd like to see how they are then equivalent to functions from Q -> Q (which I believe is the answer).
Comment: @TomCollinge: There's an injection from $\{f:\mathscr D \to \mathbb R\}$ to $P(\mathscr D) \times \mathbb R$.


Infinitely many primes in the ring of integers for any quadratic field

Question: Let $d$ be an integer, not a perfect square, and $\mathcal{O}_K$ the ring of integers in $K = \mathbb Q(\sqrt d)$.  I want to prove that there are infinitely many primes in $\mathcal{O}_K$.
How do we show that this is true? Thank you.
Comment: @Qiaochu: I'm not so sure, because if $\mathcal{O}_K$ is not a UFD, you don't necessarily have that every nonunit is a multiple of a prime *element*. For example, in $\mathbb{Z}[\sqrt{-5}]$, $3$ is not a prime and not unit, but there is no prime element that divides $3$ (since there is no element of norm $3$). So how do you guarantee that $p_1\cdots p_n + 1$ is divisible by *some* prime element? It works to show that there are infinitely many **irreducible** elements, but I don't see the prime element case.
Comment: @user9636: If you don't know about ideals or prime ideals, could you please edit the question and say what tools you **do** have available? What, if anything, have you proven about $\mathcal{O}_K$?
Comment: Euclid's proof works without modification in this setting.
Comment: @Qia Even for irreducibles that doesn't generally work since the Eulerian constructed candidate may be a unit.
Comment: @Bill: point. This isn't an issue when $d$ is negative but when $d$ is positive you need to do some fiddling to ensure that the number you construct doesn't have norm $\pm 1$.
Comment: @Arturo:I believe it's prime element.. our professor didn't talk about ideal, prime ideal..
Comment: You should probably just learn about prime ideals! It's very simple.
Comment: @Arturo: thanks for the correction. I was indeed thinking about irreducible elements.
Answer: I suspect you may have mistyped the question, or your professor may not have thought through his or her question carefully enough! Perhaps you are meant to be dealing with prime ideals, not elements?
That said, the result is true, and can be proved at a pretty elementary level, although I think that would be pretty hard for a homework problem. Here are some hints towards the most elementary proof I can think of, followed by some more thoughts.

(1) Let $R$ be a commutative ring and $p$ an element of $R$ such that $R/pR$ is an integral domain. Show that $p$ is prime. (I'm not sure what definition of a prime element you are working with, but this one should be equivalent to it.)
(2) Let $p$ be an odd prime such that $d$ is not square in $\mathbb{Z}/p \mathbb{Z}$. Show that $\mathcal{O}_K/(p \mathcal{O}_K)$ is isomorphic to the field with $p^2$ elements. In particular, $p$ is prime in $\mathcal{O}_K$.
We have now reduced to showing that there are infinitely many primes $p$ such that $d$ is not square modulo $p$.
(3) Show that there is an element $r$ in $\mathbb{Z}/(4d)\mathbb{Z}$, relatively prime to $4d$ such that, if $p \equiv r \mod 4d$ then $d$ is not a square modulo $p$.
Now, I don't know whether or not you are allowed to quote Dirichlet's theorem in your course. If you are, you are done. If not, I do know an elementary proof that there are infinitely many primes $p$ of $\mathbb{Z}$ such that $d$ is not a square modulo $p$, but I'd rather not write it out until I know you need it.

I worry that what I have written above may give you the wrong impression, that prime elements of $\mathcal{O}_K$ come from primes $p \in \mathbb{Z}$ for which $d$ is not square. That is only half the truth.
To make my life simple, let $p$ be relatively prime to $2d$.
If $d$ is not a square modulo $p$, then $\mathcal{O}_K/p \mathcal{O}_K$ is isomorphic to $\mathbb{F}_{p^2}$, as I discussed already. If $d$ is a square modulo $p$, then $\mathcal{O}_K/p \mathcal{O}_K \cong \mathbb{F}_p \oplus \mathbb{F}_p$. So $p$ is not prime.
The ideal $(p)$ factors as $\pi_1 \pi_2$, where $\pi_1$ and $\pi_2$ are prime ideals. It may or may not happen that $\pi_i$ is a principal ideal; if $\pi_i$ is principal, then its generator is a prime element of $\mathcal{O}_K$. What happens is that there is a finite group $H_K$, called the ideal class group, and $\pi$ represents an element of this group. The ideal $\pi$ is principal if and only if the corresponding element of $H_K$ is trivial.
It is in fact true that every element of $H_K$ is represented by $\pi$ for infinitely prime ideals $\pi$ of $\mathcal{O}_K$, and this is still true when we are dealing with "split primes", which in this case means prime ideals $\pi$ coming from a prime $p$ for which $d$ is square.
I worked out the particular case of $\mathbb{Q}(\sqrt{-23})$ in an earlier answer. But I don't know a general proof that every ideal class is represented by infinitely many prime ideals without going through class field theory.
Comment: Or perhaps he is meant to be dealing with *irreducible* elements, for which Euclid's argument works.
Answer: Remember that an element $\pi\in\mathcal{O}_K$ is a prime element if and only if for every $\alpha,\beta\in\mathcal{O}_K$, if $\pi$ divides $\alpha\beta$, then it divides either $\alpha$ or $\beta$.
Question. Are there any rational primes $p$ that are also primes in $\mathcal{O}_K$? If so, what are they? How many are there?
If the question has an affirmative answer and there are infinitely many such primes, then you'll be done. So let's consider what happens to a rational prime in $\mathcal{O}_K$.
We may assume that $d$ is not merely not a perfect square, but in fact squarefree, because if $d=r^2s$, then $\mathbb{Q}(\sqrt{d}) = \mathbb{Q}(\sqrt{s})$.
Consider the "norm map" $N\colon K\to\mathbb{Q}$ given by
$$N(r+s\sqrt{d}) = (r+s\sqrt{d})(r-s\sqrt{d}) = r^2 - ds^2,\quad r,s\in\mathbb{Q}.$$
This map is multiplicative: if $\alpha,\beta\in\mathbb{K}$, then $N(\alpha\beta)=N(\alpha)N(\beta)$. Also, since $r+s\sqrt{d}$ satisfies the polynomial
$$\Bigl( x - (r+s\sqrt{d})\Bigr)\Bigl(x - (r - s\sqrt{d})\Bigr) = x^2 - 2rx + (r^2-ds^2),$$
then $r+s\sqrt{d}\in\mathcal{O}_K$ if and only if $2r$ and $r^2 - ds^2\in\mathbb{Z}$.
This means that $r$ is either an integer or a half integer; if $r$ is an integer, then $ds^2$ must be an integer, hence $s$ must be an integer (since $d$ is squarefree). If $r$ is a half integer, $r = \frac{a}{2}$ with $a$ odd, then it is not hard to show that you must have $d\equiv 1 \pmod{4}$, and $s$ must also be a half integer.
It also means that we can translate statement about divisibility in $\mathcal{O}_K$ into statements about divisiblity in $\mathbb{Z}$, through the use of the map $N$. If $\alpha$ divides $\beta$ in $\mathcal{O}_K$, then $N(\alpha)$ has to divide $N(\beta)$ in $\mathbb{Z}$.
Now, suppose $p$ is a rational prime, and that $p$ divides a product
$$\left( a + b\sqrt{d}\right)\left(x+y\sqrt{d}\right).$$
We want to know under what conditions we can conclude that $p$ divides either $a+b\sqrt{d}$ or $x+y\sqrt{d}$.
Since $p$ divides the product, that
means that $N(p)= p^2$ divides the norm of the product, that is, $p^2$ divides
$$N\left(\left(a+b\sqrt{d}\right)\left(x+y\sqrt{d}\right)\right) = N\left(a+b\sqrt{d}\right)N\left(x+y\sqrt{d}\right) = (a^2-db^2)(x^2-dy^2).$$
Since each of $a^2-db^2$ and $x^2-dy^2$ are integers, and $p^2$ divides the product, then $p$ must divide one of the factors. Without loss of generality, say that $p|a^2-db^2$.
Say $a$ and $b$ are both integers (think about the case where they are both half integers on your own later). Consider some possibilities:

If $p$ divides $b$, then it must divide $a$, and that means that $p$ divides $a+b\sqrt{d}$ and we are done.
If $p$ divides $a$, then it must also divide $db^2$, so it either divides $d$ or it divides $b$.

If $p$ does not divide $d$, then it must divide $b$, and again we are done, since it divides both $a$ and $b$, hence it divides $a+b\sqrt{d}$.

If $p$ does not divide any of $a$, $b$, or $d$, then $a^2\equiv db^2\pmod{p}$, and since all of the factors are relative prime to $p$, that means that $d$ is a quadratic residue modulo $p$.

In summary: either $p$ divides $d$; or else $d$ is a quadratic residue modulo $p$; or else $p$ has to divide one of $a+b\sqrt{d}$ or $x+y\sqrt{d}$.
That is: if $p$ does not divide $d$, and $d$ is not a quadratic residue modulo $p$, then $p$ is a prime element of $\mathcal{O}_K$.
(This was under the assumption that $a$ and $b$ were integers; if they are both half integers, you'll get a similar conclusion).
So,  the question now becomes:
Question (modified): Are there any rational primes $p$ for which $d$ is not a quadratic residue modulo $p$? How many?
Show there's infinitely many such primes for any given $d$. This (together with the completed argument given above) will show that there are infinitely many primes in $\mathcal{O}_K$, namely, at least as many as there are rational primes for which $d$ is not a quadratic residue.
Note that these are not all the prime elements in $\mathcal{O}_K$, though; for some primes $p$ that do not divide $d$ and for which $d$ is a quadratic residue, you get two prime elements of $\mathcal{O}_K$ that are not rational primes, for instance (infinitely many primes for sure, sometimes all such primes).
Comment: Nice exposition. You hit most of the same points I did, but I think you did it more clearly.
Comment: @David: You are invoking some ring theory, I'm doing some congruences. I think both approaches have  merit at this level (and I would have just used ideals if the OP had enough machinery at hand).
Answer: Niven, Zuckerman, and Montgomery outline a topological proof that there exist infinitely many rational primes in Problem 52, Section 1.3, An Introduction to the Theory of Numbers, 5th ed., Wiley (New York), 1991.  I have adapted the proof to the ring of quadratic integers.
Topologize $\mathcal O_K$ as follows: A set $\mathcal N$ of integers is open if for every $\nu \in \mathcal N$, there is an arithmetic progression $\mathcal A$ such that $\nu \in \mathcal A \subseteq \mathcal N$.  Here, we define an arithmetic progression as a set $\{\rho + \kappa \delta\}$ of integers  where $\delta \neq 0$ and $\rho$ are fixed integers, and $\kappa$ runs through all integers in $\mathcal O_K$.
Next, we prove that arbitrary unions of open sets are open and that finite intersections of open sets are open, which will show that these open sets define a topology in the usual sense:  Let $\bigcup_i \mathcal N_i$ be an arbitrary union  of open sets $\mathcal N_i$.  For every $\nu \in \bigcup_i \mathcal N_i$, there is an arithmetic progression $\mathcal A$ such that $\nu \in \mathcal A$, namely the arithmetic progression in the particular $\mathcal N_i$ of which $\nu$ is an element.  Hence, $\bigcup_i \mathcal N_i$ is open.  Next, let $\mathcal N_i, i = 1, 2, \ldots, n$, be a finite number $n$ of open sets.  If $\bigcap _{i=1}^n \mathcal N_i = \varnothing$, then $\bigcap _{i=1}^n \mathcal N_i$ is open trivially.  Otherwise, let $\rho \in \bigcap _{i=1}^n \mathcal N_i$ so that $\rho$ is an element of each of the $n$ sets $\mathcal N_i$, and there is an arithmetic progression $\{\rho_i + \kappa \delta_i\}$ in each $\mathcal N_i$ of which $\rho$ is an element, so there is a particular $\kappa'$ such that $\rho = \rho_i + \kappa' \delta_i$.  Then $\{\rho_i + \kappa \delta_i\} = \{\rho - \kappa' \delta_i + \kappa \delta_i\} = \{\rho + (\kappa - \kappa') \delta_i\} = \{\rho + \kappa \delta_i\}$.  We can then make an arithmetic progression $\mathcal A = \{\rho + \kappa \delta_1 \delta_2 \delta_3 \dots \delta_n\}$  to claim that for every $\nu \in \bigcap _{i=1}^n \mathcal N_i$, there is the arithmetic progression $\mathcal A$ such that $\nu \in \mathcal A \subseteq \bigcap _{i=1}^n \mathcal N_i$.  Hence, $\bigcap _{i=1}^n \mathcal N_i$ is open.
The next step is to prove that the complement of an arithmetic progression $\mathcal A = \{\rho + \kappa \delta\}$ is a union of arithmetic progressions:  Let $\rho_1$ be any element in the complement of $\mathcal A$, in symbols, $\rho_1 \in \mathcal O_K \setminus \mathcal A$.  If there is no such element, then the assertion is true vacuously.  Otherwise, we first show that the arithmetic progression $\{\rho_1 + \kappa \delta\} \subset \mathcal O_K \setminus \mathcal A$.  For suppose, to get a contradiction, that there is an integer of $\{\rho_1 + \kappa \delta\}$ in $\mathcal A$.  Then there exist integers $\kappa_1, \kappa_2$ such that
\begin{align}
\rho_1 + \kappa_1 \delta & = \rho + \kappa_2 \delta\\
\rho_1 & = \rho + (\kappa_2 -\kappa_1) \delta\\
\rho_1 & \in \mathcal A
\end{align}
because $\kappa_2 -\kappa_1$ is one of the integers through which $\kappa$ runs to generate the elements of $\mathcal A$.  But $\rho_1 \in \mathcal A$ contradicts $\rho_1 \in \mathcal O_K \setminus \mathcal A$.  Hence, $\{\rho_1 + \kappa \delta\} \subset \mathcal O_K \setminus \mathcal A$.  Next, make sets $\{\rho_i + \kappa \delta\}$ of arithmetic progressions for each of the elements $\rho_i$ in $\mathcal O_K \setminus \mathcal A$, and form their union $\bigcup_i \{\rho_i + \kappa \delta\}$.  No element of the union will be in $\mathcal A$ as we just showed, and every element of $\mathcal O_K \setminus \mathcal A$ will be in the union, so $\mathcal O_K \setminus \mathcal A$ is a union of arithmetic progressions.
Because arithmetic progressions are open sets, and unions of open sets are open, it follows that the complement of an arithmetic progression is an open set.
Next, let $\mathcal U$ denote the union over all prime numbers $\pi$ of the arithmetic progressions $\{\kappa \pi\}$, and let $\mathcal V$ denote the complement of $\mathcal U$.  In symbols, $\mathcal U = \bigcup_\pi \pi \mathcal O_K$, and $\mathcal V = \mathcal O_K \setminus \mathcal U$.
We now show that $\mathcal V$ is the set of units of $\mathcal O_K$ and therefore not open:  Zero is not in $\mathcal V$ because $\kappa$ takes on the value $0$ as $\kappa$ runs through all the integers of $\mathcal O_K$.  The other integers besides units are (not necessarily unique) products of primes, so those integers are not in $\mathcal V$.  The units are in $\mathcal V$ because no unit has a prime factor.  Based on our definition of an arithmetic progression, in particular that $\delta \neq 0$, $\mathcal V$ cannot contain an arithmetic progression and so is not open.
Finally, we show, to get a contradiction, that if there were only finitely many primes, $\mathcal V$ would be open.  Now
\begin{align}
\mathcal V & = \mathcal O_K \setminus \mathcal U\\
& = \mathcal O_K \setminus \bigcup_\pi \pi \mathcal O_K\\
& = \bigcap_\pi \mathcal O_K \setminus \pi \mathcal O_K &&\text{(De Morgan's law)}\\
\end{align}
The complement of of each $\pi \mathcal O_K$ is open as previously shown, and the intersection of a finite number of open sets is open as previously shown.  Hence, $\mathcal V$ is open.  But that contradicts that $\mathcal V$ is not open.  Thus, there are infinitely many primes in $\mathcal O_K$.


HTML5 page 100% height Issue

Question: I am trying to create a App page which will auto fit to the height. following in the HTML code used in the page

Home

Back

The CSS used
html {
  height:100%!important;
  width:100%;
  padding:0;
  margin:0;
}

body {
  margin:0;
  padding:0;
  width:100%;
  height:100%!important;
}

#main {
  height:100%;
  margin:100%;
  margin:0 auto;
  padding:0;
  background:#fff;
}

.header {
  height:145px;
  width:100%;
  background:url(../images/header-repbg-320.png) left top repeat-x;
  display:block;
  display:inline-block;
}

.allContent {
  width:100%;
  border:0 solid green;
  height:100%;
  min-height:100%;
  vertical-align:middle;
  display:block;
  display:inline-block;
}

#footer {
  background:url(../images/footer-repbg-320.png) bottom left repeat-x;
  height:90px;
  width:100%;
  display:block;
  display:inline-block;
}

My problem is, the whole page is only consuming half of the height of the page leaving a awkward space below footer,
Question: How to make the contents auto fit itself to the height of the page?
Comment: Look at this link: http://www.tutwow.com/htmlcss/quick-tip-css-100-height/
Comment: I couldn't replicate the problem using your code. But try this: http://www.w3schools.com/cssref/pr_pos_vertical-align.asp
Comment: Can you use JS ? , Set min-height in pixel with device height, Just that !
Comment: A Webpage is virtually infinite, so how can you have 100% of infinity? Rather, use an absolute height in pixels, or use one of the creative methods below.
Answer: Click for Demo
Set Html and body tag height:100%; and  you can give maring:0; and
padding :0; to body tag also
just give wrapper div  height:100%;
HTML

    header

    content

    footer

Css
html{
    height: 100%;

}
body{
 margin: 0;
    padding: 0;

    height: 100%;
}
#Wrapper{
        text-align:center;
        margin: auto;
     height:100%;

    border-left: 1px solid #aaa;
    border-right: 1px solid #aaa;
    background-color:orange;

}
#header{
    height:10%;
   background-color:yellow;
}
#content{
    height:80%;
   background-color:#4072b4;
}
#footer{
    height:10%;
   background-color:green;
}

With out setting padding to body and html tag background image will not work
Not working example and Working Example
Your question's fiddle

And its output, It works fine on browser resizing
Comment: @l2aelba now with header and footer
Comment: What about header and footer ?
Answer: You almost had it. I simply revised the CSS of the first three selectors as follows:
html {
    height: 100%;
}
body {
    margin: 0;
    padding: 0;
    height: 100%;
}

#main {
    margin: auto;
    min-height: 100%;
    background: #ccc;
    width: 960px;
    border-left: 1px solid #aaa;
    border-right: 1px solid #aaa;
}

I only added the background, width and borders to the #main selector to show it working. It will work without those properties however the margin and min-height are necessary. You will also notice how the !important value is unnecessary and as a best practice should be used mainly for troubleshooting conflicts with inheritance.
I hope this helps.
Answer: #main {

    height:100%;
    width:100%;
    margin:0 auto;
    padding:0;
    background:#fff;
    position:relative;

}

.header {

    position: absolute;
    top:0px;
    left:0px;
    right:0px;
    height:145px;
    width:100%;
    background:url(../images/header-repbg-320.png) left top repeat-x;
    display:block;
    display:inline-block;

}

.allContent {

    position: absolute;
    top:145px;
    left:0px;
    right:0px;
    bottom:90px;
    width:100%;
    border:0 solid green;
    display:block;
    display:inline-block;
    overflow:auto;

}

#footer {

    position: absolute;
    bottom:0px;
    left:0px;
    right:0px;
    background:url(../images/footer-repbg-320.png) bottom left repeat-x;
    height:90px;
    width:100%;
    display:block;
    display:inline-block;

}

HTML5 page 100% height Issue


Cannot use libraries in sub-theme

Question: I'm experiencing a weird problem. I'm making a sub-theme of the Bootstrap theme that's available for Drupal 8. However, after trying all the possible ways of how to attach a library to a page in my theme, no one seems to work. Am I doin'g something wrong?
Here's my libraries.yml file
countdown-timer:
version: VERSION
js:
  js/jquery.countdown.min.js: {}
  js/auction-timer.js: {}

Here's how I am trying to attach it to all pages in .info.yml
libraries:
  - numisvet/countdown-timer

I have already tried the approach of adding '#attached' to the render array or using {{ attach_library('numisvet/countdown-timer') }} in a twig file.
No one of these seems to work, only libraries defined by the Bootstrap theme are getting loaded.
Am I doing something wrong?
Thanks a lot for all replies.
Comment: Make sure the yml spacing/indentation is correct. Also, after attaching, clear the cache.
Answer: Simply add your library here in your's my libraries.yml file
 bootstrap-scripts:
 js:
bootstrap/js/affix.js: {}
bootstrap/js/alert.js: {}
bootstrap/js/button.js: {}
bootstrap/js/carousel.js: {}
bootstrap/js/collapse.js: {}
bootstrap/js/dropdown.js: {}
bootstrap/js/modal.js: {}
bootstrap/js/tooltip.js: {}
bootstrap/js/popover.js: {}
bootstrap/js/scrollspy.js: {}
bootstrap/js/tab.js: {}
bootstrap/js/transition.js: {}
bootstrap/js/transition.js: {}

Your-sub-theme/js/jquery.countdown.min.js: {}

Your-sub-theme/js/auction-timer.js: {}

**No need to define it separately also place your js file at correct folder path should be eg:Your-sub-theme/js/jquery.countdown.min.js then clear cache **.

Cannot use libraries in sub-theme


nginx keeps answering with the 'default nginx site' despite it being removed from config

Question: I was hoping someone could help me with this strange problem.  On a 'clean' server install, I have the following "website.com" and nginx configs, yet if you try to go to the http version of www.website.com, it renders the default nginx page, instead of forwarding over to the https version like it's configured to do.  The site is using the AWS Linux ami, and is behind an elb (hence the directive for elb-check).
In my /sites-available (and ln -s'd to /sites-enabled), all I have (even when doing a # ls -lah) is:
default_server  website.com  elb-check
The configs (as well as the nginx.conf are below).
Thank you in advance!  Please let me know if there's additional info/configs you need.
website.com:
# Send http www. to https www.
    server {
    listen 80;
    server_name www.website.com;
    return 301 $scheme://www.website.com$request_uri;
    server_tokens off;

    }

# Send http non www. to https www.
    server {
    listen 80;
    server_name website.com;
    return 301 $scheme://www.website.com$request_uri;
    server_tokens off;

    }

# Send https non www. to https www.
    server {
    listen 443 ssl;
    server_name website.com;
    return 301 $scheme://www.website.com$request_uri;
    server_tokens off;

        ssl_certificate "/path.to.crt";
        ssl_certificate_key "/path.to.key";
        ssl_dhparam "/etc/pki/nginx/dhparams.pem";
        ssl_session_cache shared:SSL:1m;
        ssl_session_timeout  10m;
        ssl_protocols TLSv1.2;
        ssl_ciphers ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA:!RC4:HIGH:!MD5:!aNULL:!EDH;
        ssl_prefer_server_ciphers on;

    }

# Answer https and www. requests

    server {
        listen  443 ssl;
        server_name www.website.com;
        index   index.html index.php;
        root    /home/website/html;
        access_log  /var/log/website/access.log;
        error_log   /var/log/website/error.log;
    server_tokens off;

        ssl_certificate "/path.to.crt";
        ssl_certificate_key "/path.to.key";
        ssl_dhparam "/etc/pki/nginx/dhparams.pem";
        ssl_session_cache shared:SSL:1m;
        ssl_session_timeout  10m;
        ssl_protocols TLSv1.2;
        ssl_ciphers ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA:!RC4:HIGH:!MD5:!aNULL:!EDH;
        ssl_prefer_server_ciphers on;

    location / {
        root    /home/website/html;
        try_files $uri $uri/ /index.php?$uri&$args;
        }

    location ~ /private\.php$ {
        auth_basic "Restricted Area";
        auth_basic_user_file /home/website/.htpasswd;
                fastcgi_pass   127.0.0.1:9000;
                fastcgi_index  index.php;
                fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
                include fastcgi_params;
        }

    location ~ \.php$ {
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include fastcgi_params;
        }

    }

nginx.conf:
# nginx config
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /var/run/nginx.pid;

events {
    worker_connections 1024;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;

    # Load Virtual Sites
    include /etc/nginx/sites-enabled/*;
    include /etc/nginx/sites-available/*;

    index   index.php index.html index.htm;
    server_tokens off;
}

default_server:
# To black-hole all other subdomain requests
server {
    listen 80;
    server_name _;
    return 444;
}

elb-check:
# So the ELB sees the instance as still being alive
server {
    location /home/elb-check {
    access_log off;
    return 200;
    add_header Content-Type text/plain;
    }
}

Comment: Run `nginx -t` and check the output carefully.
Comment: this is what I do all the time @Mic
Answer: Nginx will choose the first server in the config if no default server is specifically defined. Install a dummy default server.
# This just prevents Nginx picking a random default server if it doesn't know which
# server block to send a request to
server {
  listen      80 default_server;
  server_name _;
  return 444;
  access_log off; log_not_found off;
}

You may want to define a default https server as well, though it will probably generate certificate warnings if it's not on a specific domain. I don't bother.
Comment: Probably because it's a default built into nginx, and your higher up sites don't define a root.
Comment: Why is mine routing to the _default_ nginx page though?  There's nothing directing traffic to that location (`/usr/share/nginx/html`).
Comment: How Nginx knows what is the "first server in the config" ? Good one...
Comment: @prosti that's the point. The order of servers is undefined (at least to me) so you use the default_server directive to tell Nginx what to do, rather than effectively letting it choose randomly. I'm sure there is an order that files are included, perhaps alphabetic, but I don't know it and it's not important enough to look up.
Comment: first of all to get the idea of "first server in the config" you would need to check the algo fo the nginx. I sure this is based on the `include` directives order you specify in nginx.conf, else if you have a wild char it may be even based on OS call. Like you set ls *.conf, but not important as you said. nothing big, just that sintagma of yours brought my attention.
Answer: I think another issue is/was with the nginx.conf, at the bottom where you are including the sites-enabled/*. You are including both available and enabled configurations. You are loading your configuration twice, so nginx, not finding a working config, will always default to a basic config.
# Load Virtual Sites
    include /etc/nginx/sites-enabled/*;
    include /etc/nginx/sites-available/*; <-- do not need this too.


Use $routeParams in service

Question: I'm trying to append a query parameter to all API calls which I fetch from the URL.
factory('Post', function ($resource, $routeParams) {
    return $resource('api/posts', {customer_id: $routeParams.customerId});
})

This works the first time the Post service is used but the second time it's injected it has already been initialized and is using the first customer ID even though the URL has changed.
How do I make this work as intended?
Answer: Because services are singletons.
That's why you get that behavior.
I recommend that do not inject $routeParams as the init params of a service.
Instead, inject it in controllers, then call service's functions using the values in $routeParams as params.
The code may like this:
factory('Post', function ($resource) {
    return {
        doPost: function(customerId) {
            $resource('api/posts', {customer_id: customerId});
        }
    };
});

//...
//in some controller
Post.doPost($routeParams.customerId)

Use $routeParams in service


What is the name of a plot of - log 10 of p values in multiple testing?

Question: Under the null, the p-value is uniformly distributed between 0 and 1. Taking the negative of the log base 10 of many such p-values should follow an exponential distribution. You can show quantiles of their distribution under the null, but more importantly, logging them makes large differences very compelling. I can't remember the name of such a plot though:

## example R code
x <- replicate(100, rnorm(10), simplify=FALSE)
y <- replicate(100, rnorm(10), simplify=FALSE)

lm.sig <- function(x, y) {
  coef(summary(lm(y ~ x)))[2, 4]
}

sigs <- mapply(lm.sig, x, y)

plot(-log(sigs, base=10), type='h', xlab='Comparison Index', ylab='-log p value')
abline(h=-log(0.05, base=10), lty=2)
legend('topleft', lty=2, 'Nominal 0.05 error rate')

Comment: I'm not sure if we misunderstand each other or it's just my own lack of comprehension of part of your response. I have no problem with the use of a log-scale, merely the value labels on the axis. I find it much easier to interpret "0.005" than "-2.3". I'm merely suggesting the use of tick marks and labels for $p$ rather than $\log_{10}p$\*, or at least the use of two axes. $\quad\quad$\*(while keeping the plot essentially unchanged -- well, I would also plot points rather than lines; what does the length of the line-segment mean on the plot?)
Comment: I don't know of a specific name of such a plot (though I'd bet it has probably been called by a couple of names before). I'd be inclined to put actual probabilities on the plot (or at the least, include them on the right side).
Comment: Agreed. That would be my mistake. The y-axis could be better labeled to represent the log-scale. The problem with presenting untransformed p-values is that 0.05 doesn't look much different from 0.01, nor 0.01 from 0.0001. Complementary log transformations allow such values to "pop".
Answer: Geneticists call this a "Manhattan plot". Usually the bars are thicker, with no gap in between, so it looks (sort of kind of) like the New York skyline.
Comment: That's right! I kept thinking "Metropolis" plot, as I knew there was some relationship to a city and the shape of the figure.
Answer: A plot of vertical lines is often called a "Needle Plot". See Graphics with R (section 3.7.3) or SAS doc.
Normally there is a shared baseline for the needles, making it conceptually like a bar chart. Your code suggests a baseline of 0 segments(seq(sigs), 0, seq(sigs), -log(sigs, base=10)), but your image looks more like lines centered at 0, segments(seq(sigs), log(sigs, base=10), seq(sigs), -log(sigs, base=10)).
Comment: Thanks for the introduction to `type='h'` for generating verticle line (e.g. needle plots). However, Manhattan, as Harvey indicated, is the term for multiple testing and p-value context specifically.


Ícone na parte superior de uma janela

Question: Preciso altera o ícone no canto esquerdo de uma janela que criei, o código que tenho como exemplo é o seguinte, mas não funciona:
objeto.tk.call("icone.ico");

Como posso fazer?
Answer: Você deve utilizar o método iconbitmap
import Tkinter

window = Tkinter.Tk()
window.iconbitmap('CAMINHO_COMPLETO_PARA_O_ICON/ICON.ICO')
window.mainloop()

Referência

Tkinter.Tk.iconbitmap

Ícone na parte superior de uma janela


Suppose that $n$ indistinguishable balls are arranged in N distinguishable boxes

Question: Suppose that $n$ indistinguishable balls are to be arranged in N distinguishable boxes so that each distinguishable arrangement is equally likely. If n is greater than or equal to N, what is that probability that no box will be empty?
Answer: The first question has $\left(\!{N\choose n}\!\right)$ arrangements.  If we insist that each box is nonempty, we first put one ball in each, and there are $\left(\!{N\choose n-N}\!\right)$ arrangements of the remainder. The ratio is your desired answer.
Edit: This notation denotes counting multisets, i.e. $\left(\!{a\choose b}\!\right)={a+b-1\choose b}$


Cognito postConfirmation function not triggered

Question: I'm signing up users to my application using serverless and AWS Lambda/Cognito, and I'd like to send a confirmation email after the users sign up. To do this, I created a postConfirmation function definition in my serverless.yml to be triggered after the postConfirmation Cognito event fires, but that function doesn't seem to get called at all. What could be the issue?
serverless.yml
...
  postConfirmation:
    description: Cognito handler for when a user is confirmed, here it is used for storing the data to database and sending a confirmation email
    name: "${self:service}-users-post-confirmation-cognito-trigger-${self:provider.stage}"
    handler: src/service/users/postConfirmationTrigger.handler
    dependsOn:
      - CognitoUserPoolMyUserPool
    events:
      - cognitoUserPool:
          pool: ${self:service}-user-pool-${self:provider.stage}
          trigger: PostConfirmation
          existing: true

I'm trying to see if the postConfirmation handler is called at all:
exports.handler =  (event, context, callback)  => {
    console.log(`this function fires!`)
    console.log(event)
}

but I don't see anything in the logs. Not sure how to trigger the handler
Answer: Looks like a classic Lambda callback issue. Your Lambda is finishing before a callback is completed. Try this:
exports.handler =  (event, context, callback)  => {
    console.log(`this function fires!`)
    console.log(event)
    context.done(null, event);
}

or this
exports.handler =  (event, context, callback)  => {
    console.log(`this function fires!`)
    console.log(event)
    callback(null, event);
}

Also make sure your Lambda configuration is setup so that it doesn't timeout. The default is 3s which is often too short.
Answer: PostConfirmation Lambda is triggered when the user is confirmed not only signup,
so make sure that the user verifies his email or phone number after signup by setting autoVerify email using console:

Or using serverless:
Resources:
  CognitoUserPool:
    Type: AWS::Cognito::UserPool
    Properties:
      UserPoolName: user-pool
      # Set email as an alias
      UsernameAttributes:
        - email
      AutoVerifiedAttributes:
        - email  <--- HERE


puppeteer nodejs instagram problem after 4-5 times

Question: I have some problems with puppeteer.
I call the site instagram with a username. It works. But after 5-6 times instagram says to login.
So how I handle this ? I log to instagram then I go to the userpage and crawl the description text.
Now its like this: it works but only 4-5 times then I have to login:
<code>const puppeteer = require("puppeteer");

const verification = async username => {
    try {
        const browser = await puppeteer.launch({headless: false, ignoreHTTPSErrors: true});
        const page = await browser.newPage();
        page.setUserAgent("Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36");

        await page.goto(`https://www.instagram.de/${username}`, {waitUntil: 'networkidle2', timeout: 0, ignoreHTTPSErrors: true});
        const d = await page.waitForSelector(".-vDIg > span"); // get Desc
        const value = await d.evaluate(el => el.textContent);

        await browser.close();
        console.log(value);
        console.log("-- bingo --");

    } catch (e) {
        console.log("our error", e);
    }
};

module.exports = verification;

</code>
Anyone has a solution for this problem ? I need your help
Comment: You can save your credentials and detect the login screen puppeteer also can save the cookies and the session.
Comment: What I usually do instead is to use puppeteer core and use connect to attach to the current chrome that way you can use your save credentials from the actual browser you are using or setup profile with shortcut to be used.
Comment: @RicardoSilva I thank you for your answers. But I have no idea how I setup the profile with a shortcut. Do you have any examples maybe for me ?
Answer: Sorry it took so long to reply.
I don't know how much you know from puppeteer core.
But the code below will grab the tab that matches the url you put in, hence preserving any session/cookie/auth you have manually done.
<code>/* eslint-disable import/extensions */ /* eslint-disable no-underscore-dangle */
/* eslint-disable-next-line import/no-extraneous-dependencies */
import puppeteer from 'puppeteer-core';
/* eslint-disable-next-line import/no-extraneous-dependencies */
import fetch from 'node-fetch';

const browserRemoteDebuggerUrl = 'you name it';

const pup = (async () => {
  const debugJson = await (await fetch(new URL(browserRemoteDebuggerUrl))).json();
  const browser = await puppeteer.connect({
    browserWSEndpoint: debugJson.webSocketDebuggerUrl,
    defaultViewport: null,
  });
  const _pages = await browser.pages(); let page = {};
  try {
    // eslint-disable-next-line prefer-destructuring
    page = _pages.filter(x => x.url())[0];
    return {
      page,
      browser,
    };
  } catch (e) {
    browser.disconnect(); return console.log('page not found?');
  }
})();

export async function evaluate() {
  const puppeteer_ = await pup;
  try {
    await puppeteer_.page.evaluate(stuff);
    await puppeteer_.browser.disconnect();
  } catch (error) {
    // eslint-disable-next-line
    console.error('page not found?\n', error);
    await puppeteer_.browser.disconnect();
  }
}

export default pup;
</code>
you can still use the same logic to spawn a new browser from a local path, meaning that you can pass the profile you want to open as argument to the chrome executable. I used to that but I do not have that code anymore.
EDIT: you need remote debugging on in chrome, also you don't want to have devtools console opened before you reach the "page.evaluate" part this usually causes bugs for me. What I usually do is place a break point on that line, then open the devtools, then resume on node.


AngularJS smart-table global config implementation

Question: table. For displaying buttons I am using this part of code,with a template

This link for template st-tamplate="/App...." is repeating on all pages. How can I make global configuration ?
Answer: You can configure it at application level
  angular.module('myModule', []).
    config(function(stConfig) {
      stConfig.pagination.template = 'my-custom-pagination-tmpl.html';
    });


Por que utilizar Class.forName ao conectar com o banco de dados?

Question: Para a conexão com banco de dados, além da inclusão do driver JDBC, a maioria dos artigos e exemplos utilizam o método estático Class.forName(String).
Veja o exemplo com o MySQL:
Class.forName("com.mysql.jdbc.Driver");

ou até
Class.forName("com.mysql.jdbc.Driver").newInstance();

Algumas citações:

"Criando uma conexão Java + MySQL Server" em DevMedia
"MySQL and Java JDBC" em Voegella

O que faz o Class.forName(String) e o newInstance()? Não é possível importar o pacote com.mysql.jdbc e instanciar um objeto Driver para a conexão, por exemplo?
Comment: Isso não é mais necessário desde o java 1.6. Anteriormente era necessário
 para que o java encontrasse o driver correto. Mas após a versão citada, o proprio compilador já procura o driver mais adequado e se não encontra, lança exceção.
Comment: Relacionada: [java.lang.RuntimeException: java.lang.ClassNotFoundException: org.postgresql.Driver](https://pt.stackoverflow.com/q/113508/28595)
Comment: @Articuno Quase. Não é o compilador que faz isso. É a classe `DriverManager` que faz em tempo de execução. O compilador mesmo, não quer nem saber se a classe necessária existe ou não.
Answer: TL;DR

Não é necssário usar-se Class.forName(String) a partir do Java 6, mas fazê-lo mesmo assim pode fazer o seu programa recusar-se a ser inicializado caso o driver não estiver no classpath.
Não existe e nem nunca existiu necessidade em utilizar-se o newInstance() nesse caso. Isso não serve para absolutamente nada.
Você pode importar e instanciar o driver diretamente se quiser sem problemas.

Seguem as explicações detalhadas:
O Class.forName(String) é realmente necessário?
Vou copiar um trecho desta minha outra resposta:

O processo de inicialização do driver, usando o Class.forName não é mais necessário nas versões mais recentes do Java. Entretanto, ao fazê-lo assim mesmo, você denuncia logo de cara a presença de eventuais erros de classpath. Além disso, ele só precisa ser feito uma vez, durante o carregamento do programa, e se falhar, o programa está irremediavelmente quebrado. Assim sendo, esse processo pode ser mantido em um bloco de inicialização estático.

Esse mecanismo era responsável por garantir que a classe do driver fosse carregada. Uma vez carregada, a classe efetua o seu próprio registro como um driver SQL, passando a ser reconhecido pela classe DriverManager como tal. A partir do Java 6, você não precisa mais usá-lo.
Um pouco de reflection
Para todas as classes carregadas na JVM, existe um objeto da classe java.lang.Class correspondente. Para obter-se uma classe a partir de seu nome, você pode usar o método Class.forName(String).
O newInstance(), é o método responsável por chamar o construtor sem parâmetros de uma dada classe a partir do objeto Class correspondente. Uma vez que ele invoca o construtor, ele naturalmente retorna a instância criada. Com isso, é possível criar-se instâncias de classes a partir do objeto Class.
Note que a partir do Java 9, esse método foi tornado obsoleto porque ele não se comporta bem no caso do construtor lançar uma exceção. A alternativa é trocar newInstance() por getDeclaredConstructor().newInstance().
A classe ServiceLoader
Com o advento do ServiceLoader no Java 6, o uso explícito do Class.forName(String) para esse caso tornou-se desnecessário, pois o ServiceLoader é o mecanismo que permite enumerar-se automaticamente serviços dentro de JARs que implemente uma determinada interface e é esse mecanismo que os drivers usam para enumerar-se a si mesmos sem que o programador precise se preocupar com isso.
Por exemplo, se você abrir o seu mysql-connector-java-5.1.36.jar como se fosse um arquivo ZIP, você encontrará um arquivo chamado java.sql.Driver dentro de uma pasta chamada META-INF/services. Eis o conteúdo desse arquivo:
com.mysql.jdbc.Driver
com.mysql.fabric.jdbc.FabricMySQLDriver

Quando o ServiceLoader for procurar por implementações da interface java.sql.Driver, ele vai procurar pelo arquivo META-INF/services/java.sql.Driver dentro de cada JAR, e em cada JAR onde esse arquivo for encontrado, será dele lida uma lista com o nome das implementações. Em seguida, o ServiceLoader vai carregar cada uma dessas classes e então, a medida que for carregando elas,
 chamar o método newInstance(), mantendo as instâncias produzidas em um Map.
No entanto, como o ServiceLoader é utilizado internamente pela classe DriverManager, você não precisa interagir diretamente com ele (nem precisa saber que existe) e nem precisa mais efetuar o Class.forName(String) manualmente. A única coisa que você precisa fazer é usar o DriverManager diretamente:
Connection con = DriverManager.getConnection(url, usuario, senha);

O que a classe do Driver faz afinal?
Vamos dar uma olhada no código-fonte da classe com.mysql.jdbc.Driver:
package com.mysql.jdbc;

import java.sql.SQLException;

/**
 * The Java SQL framework allows for multiple database drivers. Each driver should supply a class that implements the Driver interface
 *
 *

 * The DriverManager will try to load as many drivers as it can find and then for any given connection request, it will ask each driver in turn to try to
 * connect to the target URL.
 *
 *

 * It is strongly recommended that each Driver class should be small and standalone so that the Driver class can be loaded and queried without bringing in vast
 * quantities of supporting code.
 *
 *

 * When a Driver class is loaded, it should create an instance of itself and register it with the DriverManager. This means that a user can load and register a
 * driver by doing Class.forName("foo.bah.Driver")
 */
public class Driver extends NonRegisteringDriver implements java.sql.Driver {
    //
    // Register ourselves with the DriverManager
    //
    static {
        try {
            java.sql.DriverManager.registerDriver(new Driver());
        } catch (SQLException E) {
            throw new RuntimeException("Can't register driver!");
        }
    }

    /**
     * Construct a new driver and register it with DriverManager
     *
     * @throws SQLException
     *             if a database error occurs.
     */
    public Driver() throws SQLException {
        // Required for Class.forName().newInstance()
    }
}

Observe que há um bloco de inicialização estática que instancia a classe e a registra no DriverManager. Dessa forma, quando a classe é carregada, a instância necessária do driver já é criada. Ou seja, quando um Class.forName(String) for executado (seja por você ou seja indiretamente pelo ServiceLoader), ela já vai ser instanciada.
Posso chamar o newInstance() mesmo assim?
Se você quiser usar o Class.forName(String) mesmo assim, ao chamar o newInstance(), você vai criar uma outra instância que não estará registrada no DriverManager e ao não atribuir ela a lugar nenhum, será logo descartada pelo coletor de lixo. Ou seja, a chamada explícita a newInstance() é totalmente inútil e desnecessária.
Entretanto, ter várias instâncias do driver não é nocivo. De fato, uma é registrada no DriverManager pelo inicializador estático e uma segunda instância é criada pelo ServiceLoader. Se você usar o newInstance(), vai criar uma terceira instância também (ainda mais se você atribuí-la a alguma variável e utilizá-la posteriormente).
Seria de se esperar que o fato de existir mais do que uma instância do driver pudesse acarretar problemas, mas não acarreta devido a forma como ele é implementado. Se você olhar no código-fonte da superclasse de com.mysql.jdbc.Driver, que é a classe com.mysql.jdbc.NonRegisteringDriver, você verá que todos os campos são estáticos e compartilhados por quaisquer instâncias que venham a existir. Logo, se todas as instâncias compartilham o mesmo estado e não mantêm nenhum estado em si próprias, todas têm o mesmo comportamento e operam sobre os mesmos dados.
E se eu importar o driver diretamente?
Ao importar o driver diretamente, se você puder garantir que o seu código irá carregá-la, o inicializador estático dela vai ser executado e ela vai se registrar no DriverManager.
Usar uma com.mysql.jdbc.Driver.class no meio do código não é o suficiente para garantir o carregamento da classe. Mas, se você usar uma dessas coisas, aí funciona:
Class<?> x = com.mysql.jdbc.Driver.class;

Ou então:
new com.mysql.jdbc.Driver();

Ou seja, desde que você lembre-se de que pode haver várias instâncias equivalentes do driver por aí, você pode fazer isso sim e não haverá nenhum problema.


Puppet container wont start automatically

Question: So I have created a puppet container for a certificate authority.  It works, but does not start correctly.  Here is my Dockerfile:
FROM centos:6
RUN yum update -y
RUN rpm -ivh http://yum.puppetlabs.com/puppetlabs-release-el-6.noarch.rpm
RUN yum install -y ruby puppet-server
ADD puppet.conf /etc/puppet/puppet.conf

VOLUME ["/var/lib/puppet/ssl/"]
EXPOSE 9140

#NOTHING BELOW THIS COMMENT RUNS
RUN puppet master --verbose

CMD service puppetmaster start
CMD chkconfig puppetmaster on
CMD []

I can then start the container with the following run(note that I named the image ca-puppet):
docker run -d -p 9140:9140 -it --name ca-puppet \
-v /puppet-host/ssl:/var/lib/puppet/ssl \
ca-puppet bash

The issue is that I need to docker exec into the container and run the following commands to get it started and create the ca certificates in its ssl directory:
puppet master --verbose
service puppetmaster start
chkconfig puppetmaster on

I have a feeling I should be using some other Docker file commands to run the last 3 commands.  What should that be?
Answer:
There can only be one CMD instruction in a Dockerfile. If you list
  more than one CMD then only the last CMD will take effect.

also

If the user specifies arguments to docker run then they will override
  the default specified in CMD.

However, using the default process manager (e.g., SysV, systemd, etc) in Docker for most mainstream distros can cause problems (without making a lot of modifications). You generally don't need it, however -- particularly if you're only running one application (as is often considered best practice). In a Docker container, you generally want your primary application to be the first process (PID 1).
You can do this by not daemonizing puppet and start it as the default container command via something like:
CMD puppet master --verbose --no-daemonize
And use the Docker host to manage it (via restart policy, etc.).


Dynamically loading content (ajax) other than using page methods

Question: I'm working on a site at the moment that loads all of its browser popups by using page methods. This approach works but it's starting to get messy. I also view page methods as ways to perform small tasks, username availability comes to mind.
What other options are there besides page methods and the update panel?
Answer: PageMethods sounding fine to me (which are essentially Webservices).
You could pull more data per request and use cache more. You could build a better JavaScript wrapper which satisfies the need for more tidiness.
You could choose another library: How to call a web service from jQuery
Answer: You should look at the JQuery ajax functionality. http://api.jquery.com/category/ajax/
You can point the url of the AJAX request to an aspx page or an html page or pretty much any web resource that you like, as long as the request is handled on the server by some kind of HttpHandler. And as long as your callback handler is able to handle and display the returned resource


If $Ker(T^r)=Ker(T^{r+n})$ does that imply $Im(T^r)=Im(T^{r+n})$

Question: Here T is a linear transformation and an n dimensional vector space V, $T:V\rightarrow V$. And $r$ is such that $Ker(T^r)=Ker(T^{r+j})\ \forall j\geq1$
Also, how can I show that $W=T^r(V)$ is T- invariant?
Thanks for your help.
Comment: Hint: dimension formula (or whatever else name you know for the fact that $\dim\left(\operatorname*{Ker} f\right) + \dim\left(\operatorname*{Im} f\right) = \dim V$ for any linear map $f: V \to W$).
Answer: You have always $\mathrm{ker}T^{r} \subset \mathrm{ker}T^{r+j}$, since if $T^{r}v=0$, then $T^{r+j}v= T^{j}\left(T^{r}v\right)=T^{j}0=0$. Similarly, you have $\mathrm{im}T^{r+j} \subset \mathrm{im}T^{r}$, since $T^{r+j}v=T^{r}\left(T^{j}v\right)$. Since for a generic endomorphism $F$ you have that the sums of the dimension of ker and im are equal to n, if $\mathrm{ker}T^{r}=\mathrm{ker}T^{r+j}$ then the dimensions of $\mathrm{im}T^{r}$ and of $\mathrm{im}T^{r+j}$ are equal. But $\mathrm{im}T^{r+j} \subset \mathrm{im}T^{r}$, so they must coincide.
Now we are done also for the second question, since $T\left(T^{r}V\right)=\mathrm{im}T^{r+1} = \mathrm{im}T^{r}= T^{r} V$.


Diferença entre horas sem levar em consideração a data

Question: Boa noite,
Tenho o seguinte código:
WITH
CONSULTA AS (
 SELECT
    V.CHAPA,
    V.DATA,
    MAX(V.BATIDA) AS MAXBATIDA,
    MIN(V.BATIDA) AS MINBATIDA
      FROM
            ARELBATIDATRANSITOVIEW  AS V
        WHERE
          V.CODCOLIGADA = 1
           AND  BATIDA IS NOT NULL
           AND  YEAR ( V.DATA ) = 2016
             GROUP BY V.CHAPA,
                       V.DATA
),
CONSULTASEQ AS (
SELECT *, SEQ= ROW_NUMBER() OVERPARTITION BY CHAPA ORDER BY DATA)
  FROM CONSULTA
)
SELECT
        C1.CHAPA,
        C1.MAXBATIDA,
        C2.MINBATIDA,
        DATEDIFF(HOUR, C1.MAXBATIDA, C2.MINBATIDA) AS HORAS,
        'TESTE DE HORAS' AS DESCRICAO
  FROM CONSULTASEQAS C1
       LEFT JOIN CONSULTASEQ AS C2 ON C1.CHAPA = C2.CHAPA AND C1.SEQ = C2.SEQ -1
             WHERE DATEDIFF(HOUR,  C1.MAXBATIDA, C2.MINBATIDA) < 11
                         ORDER BY C1.MAXBATIDA ASC

Ele me retorna:
8636;2016-06-04 22:31:00.000;2016-06-06 12:59:00.000;38;TESTE DE HORAS
9042;2016-06-04 22:31:00.000;2016-06-06 12:28:00.000;38;TESTE DE HORAS
9035;2016-06-04 22:32:00.000;2016-06-06 13:31:00.000;39;TESTE DE HORAS

No campo horas ele esta calculando a diferença entre a máxima de uma hora com a minima de outra, mais preciso que em campos como esse:
8636;2016-06-04 22:31:00.000;2016-06-06 12:59:00.000;38;TESTE DE HORAS
9042;2016-06-04 22:31:00.000;2016-06-06 12:28:00.000;38;TESTE DE HORAS

Eu preciso que retorne a diferença das horas sem considerar a data, exemplo:
 DIFF ENTRE 22:31:00  E  12:59:00 SEJA:

22:31
23:31
00:31
01:31
02:31
03:31
04:31
05:31
06:31
07:31
08:31
09:31
10:31
11:31
12:31
12:56

Ou seja, sem comparar as datas, isso seria possivel ?
SQL SERVER 2008
Comment: Sugestão: marcar também como sql-server
Answer: Uma forma bem simples é assim:
select CAST((C1.MAXBATIDA-C2.MINBATIDA) as time(0)) Horas

Veja esse exemplo:
declare @d1 datetime, @d2 datetime
set @d1='20161024 21:18:41.330'
set @d2='20161024 23:28:41.330'
select CAST((@d2-@d1) as time(0)) Horas

Comment: Perfeito,Obrigado.


Standard error for proportion with small sample size

Question: Standard error for a proportion, when n > 5 and np > 5 is calculated as $$SE = \sqrt{ \frac{p(1-p)}{n}}$$ where p is the proportion and n is sample size.
However, for even smaller samples, we were given an equation $$SE=\frac{1-e^{\frac{log(0.05)}{n}}}{1.96}$$
Is the second formula a valid way to calculate standard error of a proportion for very small samples? What is the rationale behind it?
Comment: Somebody is confused.  This appears related to constructing a confidence interval for a proportion when no successes are observed in $n$ independent iid Bernoulli observations.  The standard error formula $\sqrt{p(1-p)/n}$ is correct for any $p$ and $n$.  When $p$ is unknown (as it usually is), one substitutes an estimate for $p$ in this formula--and the result is *still* called the standard error.  It makes a poor input to a confidence limit calculation even when $np \approx 5$: don't use Normal-theory formulas until $np$ and $n(1-p)$ are much larger than that.
Comment: From where is the second formula? It doesn't depend on $p$ and already contains some quantiles (i.e. 1.96). So I wonder how it can be called a standard error at all?
Comment: @COOLSerdash We were asked to calculate this by a reviewer, without a reference. That's why I hope someone might be able to figure out what this means.
Comment: @whuber Thank you. Would you turn this into an answer so that you could get credit for it?
Comment: Here's an online calculator for the interval estimate methods noted above:
http://epitools.ausvet.com.au/content.php?page=CIProportion It covers: 1. Asymptotic (Wald) method based on a normal approximation 2. Binomial (Clopper-Pearson) 'exact' method based on the beta distribution 3. 'Wilson' Score interval, 4. 'Agresti-Coull' (adjusted Wald) interval and 'Jeffreys' interval.
Answer: No.
The standard error of the mean (SEM or standard error) is a value representing how close the 'true' population mean is likely to be to the sample mean. It is related to the standard deviation (SD) - it is the SD divided by the square root of sample size - and it can be used along with the sample mean to derive a 95% confidence interval for the population mean (the 95% confidence interval for the population mean is the sample mean +/- 1.96*SEM).
For 'large' samples (two rules of thumb in common use are when np and n(1-p) are both greater than 5 or when they are both greater than 10) we can use a normal approximation. However, for small samples or extreme proportions, where the rule of thumb is not true, the interval within which the population mean is likely to be found is not symmetrical about the sample proportion. This means that the SD and the SEM cannot be usefully defined. The best alternative is to calculate and report a confidence interval for the population mean; this page includes a calculator for this using the Clopper-Pearson method.
See also the 2001 paper by Brown, Cai and DasGupta, "Interval Estimation for a Binomial Proportion". Statistical Science. 16 (2): 101–133 which is a fairly accessible overview of the problem and some approaches to fixing it.
(It is worth noting that the above paper actually recommends either the Wilson interval, the Agresti interval or the Jeffries interval, but I couldn't find an online calculator for those; there are many in software packages. For example, in Matlab <code>[p, ci] = binofit([positives], [sample size]</code>) gives you a confidence interval via the Agresti method).
Comment: See also the 1998 paper by Agresti & Coull, "Approximate Is Better than 'Exact' for Interval Estimation of Binomial Proportions". The American Statistician
Vol. 52, No. 2 (May, 1998), pp. 119-126 for a clever but straightforward adjustment to improve Wald performance when p is small.


using constroptim in R on equals constraint on variables

Question: The problem is simple.
I am using the constrOptim function wherein the constraints/parameters a,b,c satisfy the condition a+b+c = 1 and a>0,b>0,c>0
Can I have an example on this?
So far, I could code up something like this :
optim(c(0.1,0.1,0.1,0.1,0.1,0.1),
   optimize_ranks,data=data,
   lower=c(0.2,0.2,0.2,0.1,0.1,0.2),
   method="L-BFGS-B",
   upper=c(1,1,1,1,1,1))

All I want is, that these 6 params x1,x2,x3,x4,x5,x6 must add up to 1.
Comment: Does this answer satisfies your question this time?
Answer: If you need to set these constraints (sum equals 1) on the 6 parameters a, b, c , d, e,f in constrOptim:
ui = rbind(
   c(1,1,1,1,1,1),
   c(-1,-1,-1,-1,-1,-1)
 )
ci = c(0.999, -1.001)

func = function(x) x[1]-x[2]*x[1]+x[3]**3-x[4]*x[5]

init = c(1,0,0,0,0,0)

#> constrOptim(init, func, grad=NULL, ui=ui, ci=ci)
#$par
#[1]  -5744.485   4392.275 -27681.276  14950.497   5945.962   8138.027

#$value
#[1] -2.121093e+13

Think about your vector of 6 parameters x such that ui*x>ci (the inequality is strict, explaining the error margin of 0.001 in ci). It is exactly how it is described in constrOptim documentation.
Comment: so,if i have a,b,c,d,e,f and a+b+c+d+e+f = 1, i set ui = rbind(
       c(1,1,1),
       c(-1,-1,-1),
       c(1,0,0),
       c(0,1,0),
       c(0,0,1)
     ) and ci = c(1, -1, 0.00001, 0.00001, 0.00001) ? how about ci, i got the ui part though
Comment: Hey, could you suggest for the initial values for these 6 variables to start with? It says "initial value is not in the interior of the feasible region", when i start with c(1,0,0,0,0,0).
Comment: parameters <- constrOptim(c(0.00001,0.00001,0.00001,0.00001,0.00001,0.00001),optimize_ranks,data=data,lower=c(0.2,0.2,0.2,0.1,0.1,0.2),method="L-BFGS-B",ui = rbind(
    c(1,1,1,1,1,1),
    c(-1,-1,-1,-1,-1,-1),
    c(1,0,0,0,0,0),
    c(0,1,0,0,0,0),
    c(0,0,1,0,0,0),
    c(0,0,0,1,0,0),
    c(0,0,0,0,1,0),
    c(0,0,0,0,0,1)
  ),
  ci = c(1, -1, rep(0.00001,6)))
Comment: It fails for the above call.
Comment: c(0.1, 0.1, 0.1, 0.1, 0.1, 0.5) . even this doesnt work. how do i know the feasible region?
Comment: c(0.088, 0.088, 0.088, 0.088, 0.088, 0.333) ..now this must, must lie in the feasible region. still it gives the same error.
Comment: I know how to find the feasible region, but when i put some values out of it, it fails again, giving the same error - "initial values not inside the feasible region".
Comment: I cannot accept this as the right answer yet. Could you please help me with the initial parameters?
Comment: I edited my post, but please do not spam. Put your request in your question (which is badly formulated by the way since you speak about two problems and do not give the function to optimize).
Comment: I am still looking at it, I am reading the code now, for constrOptim, it at times says par empty, anyways I have found a work around to it, now have some other problem. thanks
Comment: Can you tell me how to pass a data frame in the f function to be minimized?that is the only thing aching me now.
Comment: Hum for this I need the detail of your function, the prototype at least. YOu can open a new question since it is very different to this one!
Comment: http://stackoverflow.com/questions/28295794/pass-parametersdata-frame-in-controptim-in-r. I have asked this.


Simple Differential Equation

Question:
We have
  $$\frac{dx}{dt}=x-y-1$$
  $$\frac{dy}{dt}=x-y+1$$
Express $y$ in terms of only $x$ (i.e. no $t$ term).

My professor gave me the hint "use $\frac{d}{dt}(x-y)$", but I don't know how this is supposed to help me.
Comment: $\frac{d}{dt}(x-y) = \frac{dx}{dt} - \frac{dy}{dt} = -2$, so solve for $x-y$ by integrating and then go back to the original differential equations
Comment: @copper.hat read carefully: dx/dt ends with $-1$ and dy/dt ends with $+1$.
Answer: Use both $x-y$ and $x+y$.  I get
$$\frac{d}{dt}(y-x) = 2 \implies y-x=2 t+C$$
$$\frac{d}{dt}(y+x) = 2 (x-y) = -4 t \implies y+x=-2 t^2 +C'$$
Do some algebra to find that
$$t^2+t+x=0 \implies t=-\frac12 \pm \frac12 \sqrt{1-4 x}$$
Then
$$y=t-t^2+C = x-1\pm\sqrt{1-4 x}+C$$
Comment: No problem, I very much enjoy reading your answers!
Comment: @Amzoti: that's very kind of you.  Thanks.
Answer: We can also do the problem with a long way. However, @Ron's approach is a shortcut concrete one, I 'd like to bring up additional points. They are useful to know. :)
The system is equal to the following system if we set $x'=Dx, y'=Dy$:
$$ \left\{
        \begin{array}{ll}
            (D-1)x+y=-1 \\
            -x+(D+1)y=1
        \end{array}
    \right.
$$ Now, let's try to solve it as it is solved in pre-calculus. We have:
$$ \left\{
        \begin{array}{ll}
            \color{green}{(+1)}(D-1)x+\color{green}{(+1)}y=\color{green}{(+1)}\times-1 \\
            \color{green}{(D-1)}(-x)+\color{green}{(D-1)}(D+1)y=\color{green}{(D-1)}\times1
        \end{array}
    \right.
$$ So; $$[(D^2-1)+1]y=-2\Longleftrightarrow D^2y=-2\Longleftrightarrow y=-t^2+C_1t+C_2$$ wherein $C_1$ and $C_2$ are constants. Doing the same way for $x$ you can find it with respect to $t$ also.
Comment: Also very nice + 1. Hope all is well my friend!
Comment: $+ 1 \land$ missing you!

Simple Differential Equation


How to know which Implementation of Interface is being used?

Question: I've below code snippet.
public int appendLoopOnAppenders(LoggingEvent event) {

    int size = 0;

    if (this.appenderList != null) {
        size = this.appenderList.size();
        for (int i = 0; i < size; i++) {
            Appender appender = (Appender) this.appenderList.elementAt(i);
            appender.doAppend(event);
        }
    }

    return size;
}

Here Appender is a Interface but when I check the Appender's official documentation, It is being implemented by so many classes.
I want to know, In such cases, How would I know which class's Implementation out of all classes who implements Appender Interface is getting used ?
For example in above code, How would I know doAppend is which class's implementation ?
Comment: This seems to be an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Why do you need to know the implementation? The benefit of interfaces is to decouple their delcaration from the (concrete) implementation. As an aside: `Appender appender = (Appender) this.appenderList.elementAt(i);` why do you need to cast here? Maybe you want to take another look at the definition of this list (especially its generic parameter).
Comment: *Why* do you want to do that? `interfaces` are there to hide the implementation and just expose official "api"
Answer: You can use appender.getClass() to see which actual type your appender has. You can also use the instanceof operator to test the type of an object.


Prove the identity $ \sum_{i=0}^n {n \choose i} i = n2^{n-1} $ using combinatorial proof.

Question:
Prove the identity $ \sum_{i=0}^n {n \choose i} i = n2^{n-1} $ using combinatorial proof.
Comment: Have you checked [this question](http://math.stackexchange.com/questions/7757/how-to-prove-this-binomial-identity-sum-r-0n-r-n-choose-r-n2n-1) and the [questions which are linked there](http://math.stackexchange.com/questions/linked/7757)? For example, [this one](http://math.stackexchange.com/questions/67068). And [this questions](http://math.stackexchange.com/questions/388587/combinatorial-proof-of-sumn-i-1-binomnii-n2n-1) looks like direct duplicate. (And again, looking [at the linked questions](http://math.stackexchange.com/questions/linked/388587) might be useful, too.)
Comment: You are trying to explain this by  counting a given set in  two different ways, like one of the previous questions you posted  about $\binom{52}{13}$ and I answered?
Comment: That was a different question. I know it may seem the same, but that was actually asking to prove it with another identity; this question is asking for a proof which is using combinatorial methods.
Comment: You are not searching for popular questions (regarding these binomial identities) which have been adequately answered. If you have any specific query then post it, but your 3 questions on these identities are really duplicates.
Comment: I have looked at the other solutions posted to the same question. The reason why I posted this was to actually understand what 'counting arguments' means because none of the other questions explicitly said this.
Answer: Hint. Consider the following  counting problem:
How many ways do you have of choosing a non-empty subset of $S_n:=\{1,2,\dots,n\}$ and then an element of this subset?
You can choose a subset of $i$ elements in $\binom{n}{i}$ ways (note that $\sum_{i=0}^n \binom{n}{i}$ gives you all the subsets of $S_n$ that is $2^n$) then you pick one of the $i$ element of this subset in $i$ ways. Hence the total number is
$$\sum_{i=1}^n {n \choose i} i,$$
that is the left-hand side of your identity.
What about the right-hand side?
Another approach: note that
$$\sum_{i=1}^n {n \choose i} i=\sum_{i=1}^n \frac{n}{i}\cdot {n-1 \choose i-1} i=n\cdot\sum_{i=1}^n  {n-1 \choose i-1}=n\sum_{j=0}^{n-1} \cdot {n-1 \choose j}=n2^{n-1}.$$.
Answer: $\binom ni$ is the number of ways to pick $i$ items out of $n$, and in your sum there is an extra factor $i$. So we can count all the ways to draw $i$ items and paint one of them red. This is the same as painting one item red and picking $i-1$ white ones in all possible ways.
Comment: Would this be considered 'counting arguments'?
Comment: I don't see a better way to describe it than as a "counting argument". Unless you would prefer "paint shop" ?


how to add selected values in sequence multi select2

Question: if you want to show your select2 selected value in sequence which one sequence select, and drop down not close until you click outside
[![Show like this][1]][1]
[1]: https://i.stack.imgur.com/hZvVS.png

 $("select").select2({
  tags: true
});

$("select").on("select2:select", function (evt) {
  var element = evt.params.data.element;
  var $element = $(element);

  $element.detach();
  $(this).append($element);
  $(this).trigger("change");
});
<select style="width: 500px;" multiple="multiple">
    <option>two</option>
    <option>four</option>
    <option>six</option>
  </select>
Answer:

$("select").select2({
  tags: true
});

$("select").on("select2:select", function (evt) {
  var element = evt.params.data.element;
  var $element = $(element);

  $element.detach();
  $(this).append($element);
  $(this).trigger("change");
});
//drop down always visibile until you click outside
var thing = $("select").select2({
  closeOnSelect: false
}).on("change", function(e){
  // thing.select2("close");
  // try this line if your code not working
  // thing.select2("open");
});
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>JS Bin</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0-rc.1/css/select2.min.css" />

  <select style="width: 500px;" multiple="multiple">
    <option>two</option>
    <option>four</option>
    <option>six</option>
    <option>Seven</option>
    <option>Eight</option>
    <option>Nine</option>
  </select>


How to pass ostream operator<< as a function in C++?

Question: Is there any way I can pass an std::ostream operator<< as an argument in other function call? For example:

#include <iostream>

template <typename Visitor>
void print(Visitor v, int value)
{
    v(value);
}

int main(void)
{

    std::cout.operator<<(5); // This works

    std::cout << 5; // This works

    print(std::cout.operator<<, 5); // Error happens

    return 0;
}

The error is:
$ g++ -g main.cpp -o main
main.cpp: In function 'int main()':
main.cpp:17:12: error: no matching function for call to 'print(<unresolved overloaded function type>, int)'
           5);
            ^
main.cpp:4:6: note: candidate: template<class Visitor> void print(Visitor, int)
 void print(Visitor v, int value)
      ^~~~~
main.cpp:4:6: note:   template argument deduction/substitution failed:
main.cpp:17:12: note:   could not deduce template parameter "Visitor"

I know in C++ we can do operator overloadings like std::ostream& operator<<(std::ostream& out, something); but that's not what I aim to. Let's say I want to work with other printing functions or operators (like std::fout or printf), so I want my print function to be generic as much as possible.
Comment: As long as your function accepts `std::ostream&` as a parameter, it'll work just fine. https://ideone.com/AZZnr5
Comment: This particular `operator<<` is not an [addressable function](https://en.cppreference.com/w/cpp/language/extending_std#Addressable_functions) and so cannot be passed as an argument to another function in this manner. Depending on what exactly you're trying to do and why you believe you need to structure your `print` function this way, a different approach may be feasible.
Comment: There are few circumstances in which is is appropriate to pass an `operator<<()` as an argument of a function. It will also be problematic for streams, as some `operator<<()` are member functions of classes in the standard library (`std::basic_ostream`, etc) and some are non-member functions.  So it is more usual to pass the stream and the object, and connect them using an expression like `astream << an_object` - the compiler will then sort out calling an appropriate `operator<<()` (or diagnosing an error) - whether that function is a member of the stream or a non-member - as needed.
Comment: You need to pass a pointer or reference to the function, the object the function is a member of, and the value to pass to this function. Or use lambdas if you only want to pass a function.
Comment: I haven't tried your answers yet but @songyuanyao answer works for me!
Answer: You can pass a lambda instead.
print([](int value) { std::cout << value; }, 5);

Comment: @AndreasHadjigeorgiou Like [this](https://wandbox.org/permlink/w5whYnKaCRZq2mPZ)?
Comment: I swear I had tried lambda before, i guess I had messed up somewhere! This answer works for me! Thank you!
Comment: can you demonstrate the complete example please!


What football stadium is at the highest altitude in the world?

Question: After Brazil's goalless draw against Bolivia during 2018 World Cup Qualifiers, which was played on Estadio Hernando Siles Stadium, La Paz, the Brazilian players needed some oxygen refreshment after their game at such a high altitude.
According to the Wikipedia article about this stadium,

The stadium is located at an altitude of 3,637 metres (11,932 feet) above sea level, making it one of the highest professional stadiums in the world.

Is this stadium the one at highest altitude? If not, which professional football stadium is the highest located stadium in the world?
Answer: Estadio Hernando Siles is not the highest stadium in the world. Estadio Víctor Agustín Ugarte, another stadium in Bolivia, is even higher with an altitude of 3,960 meters (12,992 ft).
However, the highest stadium in the world is Estadio Daniel Alcides Carrión located in Peru with an altitude of 4,380 meters (13,973 ft) above sea level. This stadium is used by football team Unión Minas.


Applying Bayes's Theorem When Evidence is Uncertain

Question: My limited understanding of  Bayes's theorem,
$$P(H|E)=\frac{P(E|H)P(H)}{P(E)}$$
is that—even though one of it's terms is $P(E)$—it's applied when $E$ is definitely known to be true. (You went to the doctor and definitely got a positive test result.)
How can I apply the theorem when $E$ might be true with some known probability?

More detail: I have a machine-learning model that, evaluating $H$ and $E$ individually, estimates how probable each is. $H$ and $E$ may be are related, though, so I'd like to adjust these probabilities based on what the model said about the other. ($H$ could be true even if $E$ is not true—but $E$ being true makes it more likely $H$ is true.)

A concrete example adapted from Wikipedia's:

Suppose that a test for using a particular drug is 99% sensitive and 99% specific. That is, the test will produce 99% true positive results for drug users and 99% true negative results for non-drug users. Suppose that 0.5% of people are users of the drug.

What is the probability that a randomly selected individual for whom it is 70% certain (somehow) that he got a positive result is a user of the drug? (This does not mean that's there's a 30% chance he got a negative result, but a 30% chance that he got no result.)
Comment: Interesting question. I don't have the answer, but this seems relevant https://pdfs.semanticscholar.org/13f5/795c9d4075d4468131fe9405bae5ec3e3857.pdf
Comment: How can you adjust the probabilities if you don't even know if $H$ and $E$ are related in the first place?
Comment: @jbowman poor wording. They are related. (Edit: on second, thought, I haven't completely worked on the conditional probability, but is it true that Bayes's theorem require that they be definitely related?)
Comment: I'm not entirely sure what you mean - in general $P(E) = \int P(E|H)p(H)\mathrm{d}H$ and you use this to update the probability distribution of $H$. So you are effectively averaging over the uncertainty of the value of $H$. Can you give a concrete example of a situation where this arises? That might make it easier to help.
Comment: @MauritsM Does that equation have a name? Please see the example I added.
Answer: Let $E$ be an event that occurs with probability $0 \leqslant \phi \leqslant 1$.  Assuming that $H \perp \phi | E$ (which just means that your probability $\phi$ has no further effect on the calculations), you have:
$$\begin{equation} \begin{aligned}
\mathbb{P}(H|\phi)
&= \mathbb{P}(H,E|\phi) + \mathbb{P}(H,\bar{E}|\phi) \\[6pt]
&= \mathbb{P}(H|E,\phi) \mathbb{P}(E|\phi) + \mathbb{P}(H|\bar{E},\phi) \mathbb{P}(\bar{E}|\phi)  \\[6pt]
&= \phi \cdot \mathbb{P}(H|E) + (1-\phi) \cdot \mathbb{P}(H|\bar{E}) \\[6pt]
&= \phi \cdot \frac{\mathbb{P}(E|H) \mathbb{P}(H)}{\mathbb{P}(E)} + (1-\phi) \cdot \frac{\mathbb{P}(\bar{E}|H) \mathbb{P}(H)}{\mathbb{P}(\bar{E})}  \\[6pt]
&= \phi \cdot \frac{\mathbb{P}(E|H) \mathbb{P}(H)}{\mathbb{P}(E)} + (1-\phi) \cdot \frac{(1-\mathbb{P}(E|H)) \mathbb{P}(H)}{1-\mathbb{P}(E)}. \\[6pt]
\end{aligned} \end{equation}$$
This gives you an extended version of Bayes' rule for dealing with an uncertain event $E$.  As you can see, this rule merely says that the conditional probability of $H$ given $\phi$ can be considered as a weighted average of the Bayes' rule expressions for the two possible outcomes of $E$, weighted by their probabilities.
Comment: What does $\bar{E}$ mean here?
Comment: That means not-$E$ (i.e., the event $E$ does not occur).  I have added an additional line to the equation to show the result just in terms of $E$.
Comment: Thanks for clarifying. I'm wondering, though, does this assume $P(\bar{E}|\phi) = (1 - \phi)$? In that $(1 - \phi)$ portion of outcomes, we don't necessarily have $\bar{E}$—we just don't know whether we have $E$ or $\bar{E}$.
Comment: We have assumed that $\mathbb{P}(E|\phi) = \phi$, so we must also have $\mathbb{P}(\bar{E}|\phi) = 1-\mathbb{P}(E|\phi) = 1-\phi$.  That is not an assumption; it is a consequence of our specification of the probability that $E$ occurs.
Answer: Well, first of all, "evidence" is generally taken to be, by definition, that which you are certain of. If your doctor comes to you and says "We got your results mixed up with five other people's, and got five positive results", then you apply Bayes' theorem to P(E|H), where H = you have the disease and E = "We got your results mixed up with five other people's, and got five positive results". If you don't know enough about E to calculate P(E|H), then you can't apply Bayes' Theorem.
With your example, consider 1 000 000 people. 5 000 are drug users. Of those, 995 will test positive, and 5 negative. There are 995 000 non-drug users, of which 9950 will test positive and 985050 will test negative. So, out of those who test positive, 9.09% are drug users. But we don't have that the person in question tested positive, we have that they "are 70% certain to have tested positive". So now we have to find out what that population is made up of. One issue is presumably, 70% of people who are 70% certain to have tested positive tested positive. But what of the other 30%? Did the test negative? Or weren't tested at all? Let's say they tested negative. We have that 9.09% of positive are drug users, and they make up 70%. So this gives 6.36% drug users. We also have that those a negligible percentage that tested negative drug users. We add those numbers together and get that 6.36% of this set are drug users.
So to recap:
percentage positive * P(drug user|positive) + percentage negative * P(drug user|negative)
which is
.70(true positive/(true positive + false positive))+.30(false negative/(false negative + true negative))
However, this is based on certain independence assumptions. Let's call these people that are 70% certain "reported". My calculation assumes that false positives are just as likely to be reported as true positives. But it is very likely that that will not be true.


#1064 Syntax Error : In "Update Query"

Question: When I use this mysql code
update catalog_product_entity_decimal
  set value = "6.0000"
  where attribute_id = 75 and
        entity_in ( SELECT
        product_id
        from `catalog_category_product`
        WHERE category_id =37 );

i'm getting this error
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT product_id from `catalog_category_product` ' at line 4

I couldn't figure out what's wrong with my query. Can someone tell me what's wrong?
Thank you
Answer: You are missing the IN clause after entity_in. Use this:
update catalog_product_entity_decimal
  set value = "6.0000"
  where attribute_id = 75 and
        entity_id IN ( SELECT
        product_id
        from `catalog_category_product`
        WHERE category_id =37 );

Comment: Or it should be `entity in`.
Comment: Thankyou. Your code fixed my issue. But its `entity_id IN` instead of `entity_in IN`
Comment: @Giri thats because I did not know your column names. Anyways, I will fix it in the answer
Answer: I think catalog_category_product will not contain the ' symbol.
Try the query without using the ' symbol
Answer: You missed = OR in in the query

#1064 Syntax Error : In "Update Query"


Convergence of indicator function

Question: Let $\{x_k\}_{k\in\mathbb{N}}\subset\mathbb{R}^n$ and $x\in\mathbb{R}^n$ such that: $x_k\to x$, $k\to+\infty$. Is true that:
$\chi_{B_R(x_k)}\to\chi_{B_R(x)}$, $k\to+\infty$, pointwise on $\mathbb{R}^n$? In this case can you give me a rigorous proof of this fact?
Comment: is $B_R$ the open ball of radius $R$?
Comment: Yes, $B_R(y)$ is the open ball of radius R and centre $y$.
Answer: On $\mathbb R,$ does $\chi_{B(1/k,1)} \to \chi_{B(0,1)}$ everywhere? No because $\chi_{B(0,1)}(1)=0,$ while $\chi_{B(1/k,1)}(1)=1$ for all $k.$

Added later: The OP asks if we have $\chi_{B(x_k,R)} \to \chi_{B(x,R)}$ a.e. The answer is yes. First fix $y\in B(x,R).$ Then $|y-x|=R-\epsilon.$ For large $k$ we will have $|x-x_k|<\epsilon/2.$ For such $k,$
$$|y-x_k|\le |y-x|  + |x-x_k| <R-\epsilon+\epsilon/2 = R-\epsilon/2.$$
Thus for large $k,$ $y\in B(x_k,R),$ which implies $1= \chi_{B(x_k,R)}(y)=\chi_{B(x,R)}(y).$ So for any fixed $y \in B(x,R),$ we get pointwise convergence.
A similar argument shows that if $|y-x|>R,$ then we have pointwise convergence at $y$ (to $0$).
Letting $C$ be the set where pointwise convergence holds, we see $ B(x,R)\subset C\subset \{|y|>R\}.$ So the only set where we don't have pointwise convergence is a subset of $\partial B(x,R),$ a set of measure $0.$
Comment: But is true that $\chi_{B_R(x_k)}\to\chi_{B_R(x)}$ a.e. on $\mathbb{R}^n$? In this case can you give a me rigorous proof of this fact please ?
Comment: Done. $\,\,\,\,$
Comment: Ok, very clear. Now i want prove that $\chi_{B_R(x_k)}\leq\chi_{B_{2R}(x)}$ a.e. on $\mathbb{R}^n$, for $k$ large. I have tried to use the same idea but it seems to me doesn't work. Can you help me?
Comment: In fact, $\chi_{B(x_k,R)}\le \chi_{B(x,2R)}$ everywhere for $k$ large. Proof: Suppose $|x_k -x| <R.$ Let $y\in B(x_k,R).$ Then

$$|y-x|\le |y-x_k|+|x_k-x|<R + R=2R.$$

So for such $k,$ $y\in B(x,2R).$ For these $k$ we therefore have $\chi_{B(x_k,R)}\le \chi_{B(x,2R)}$ everywhere.

Convergence of indicator function


Raphael- Detect overlapped elements when drag and drop

Question: I'm trying to get element by drag and drop another element.
I have for example 2 circles: c1 and c2.
What i want to do is :  if i drop c2 above c1 hence they are overlapped(not entirely necessary), i can get circle c1 (ex:id, title... etc).
http://jsfiddle.net/Tomen/LYjnV/1/
Is there a way to do it?
Comment: [Element.onDragOver](http://raphaeljs.com/reference.html#Element.onDragOver) might be useful, if all you need to do is perform some action based on the dragged over element.
Comment: It's the other way, onDragOver(f) can only run function on my current element when it was dropped on other element. But what i want is that under element.
Answer: I'm not sure if you want the moving element that collides, or the static one that is collided with - so I'll give both. (it sounds like you want the static one, but it is this one which Element.onDragOver gives, as suggested in Oli's comment)
Here is a rudimentary jsfiddle which accesses both elements:

For the static element that is collided with, it uses Raphael's Element.onDragOver
For the moving element that is being dragged, it uses some basic code based loosely on how jQuery UI's Draggable and Droppable libraries do this, as described here - by placing the dragged object in the global namespace while it is being dragged, and then accessing it from there.

It's possible Raphael already has a feature like this for accessing the dragged element, but if it does I haven't managed to find it looking in the docs, code or DOM.
My implementation of the second point is an extremely basic demonstration which would need improvement. For something more complete, I'd recommend reading and taking inspiration from the code used by the heavily tested and refined jQuery UI to do the same thing


mutex.try_lock() lets multiple threads hold the lock simultaneously

Question: After hours tearing my hair out, it appears I've been savagely mauled by unexpected behaviour from c++11's unique_lock.  I must have horribly misunderstood something :
#include <iostream>
#include <vector>
#include <thread>
#include <mutex>

#define N_THREADS 4
#define N_ITERATIONS 10000
#define N_LOOPS 1000000

class ThingMaJigger
{
public:
    void fight()    {
        if(m.try_lock()) {
            // more then one thread ends up here??!?!?
            printf("I'm the winner!\n" );
            m.unlock();
        } else {
            printf("Sleeping \n" );
        }
    }
private:
    std::mutex m;
};

void worker(ThingMaJigger* ar,int tIdx)
{
    ar->fight();
}

int main(int argc, char const *argv[])
{
    for (int _loop = 0; _loop < N_LOOPS; ++_loop) {
        std::vector<std::thread> ts;
        ThingMaJigger t;
        for (int i = 0; i < N_THREADS; ++i)
        {
            ts.emplace_back(worker,&t,i);
        }

        for (int i = 0; i < N_THREADS; ++i)
        {
            ts[i].join();
        }

        printf("\n");

    }
        return 0;
}

Compile with clang++ -std=c++11 -O2 -lpthread ./unique_lock.cpp
clang 3.7.0, g++ 5.1.1, both behave in the same way.
Example output:
I'm the winner!
Sleeping
Sleeping
I'm the winner!

I'm the winner!
Sleeping
I'm the winner!
Sleeping

I'm the winner!
I'm the winner!
Sleeping
Sleeping

Kinda looks like multiple workers holding the same lock
at the same time, don't it?
http://en.cppreference.com/w/cpp/thread/mutex/try_lock says:

Return value
true if the lock was acquired successfully, otherwise false.

Note: try_lock is allowed to return false even if no one else
has the lock. That's not what this is about.
Comment: You appear to have a question that is one of pure code (and (self) answered with pure code).  Such questions would be better asked on Stack Overflow instead.  There doesn't seem to be any question of software design or architecture in the question or information about design or architecture in the answer.
Answer: This is working as intended.
Immediately after printing "I'm the winner," you're unlocking the lock.  This gives the other threads a chance to acquire it as well.
If you want only one thread to "win," you should also have a variable indicating whether someone has won yet.  Set it to false before creating the threads.  Any thread which acquires the lock sucessfully checks that variable to see if anyone else has won.
bool somebodyWon = false; // make sure this is set to false before
                          // threads get created

    if(m.try_lock()) {
        if (somebodyWon) {
            printf("Darn, someone beat me to it!\n");
        } else {
            printf("I'm the winner!\n");
            somebodyWon = true;
        }
        m.unlock();
    } else {
        printf("I didn't even get a chance! \n" );
    }

The other approach, which is also legal, is to change from using a mutex to a semaphore so that one thread can lock the object, but let the parent thread release it after all threads have joined.
Comment: I answered my own question minutes after I posted, but thanks anyway.
Answer: Conccurency is confusing. Let's go shopping!
#include <iostream>
#include <vector>
#include <thread>
#include <mutex>
#include <unistd.h>

#define N_THREADS 4
#define N_ITERATIONS 10000
#define N_LOOPS 1000000

class ThingMaJigger
{
public:
    void fight()    {
        if(m.try_lock()) {
            // more then one thread ends up here??!?!?
            printf("I'm the winner!\n");
            usleep(1000000); // <<<< this.
                             // or can unlock() before other's try_lock()
            m.unlock();
        } else {
            printf("Sleeping \n" );
        }
    }
private:
    std::mutex m;
};

void worker(ThingMaJigger* ar,int tIdx)
{
    ar->fight();
}

int main(int argc, char const *argv[])
{
    for (int _loop = 0; _loop < N_LOOPS; ++_loop) {
        std::vector<std::thread> ts;
        ThingMaJigger t;
        for (int i = 0; i < N_THREADS; ++i)
        {
            ts.emplace_back(worker,&t,i);
        }

        for (int i = 0; i < N_THREADS; ++i)
        {
            ts[i].join();
        }

        printf("\n");

    }
        return 0;
}


Not able to find total and averages for the given number - Correct Code

Question: I want to create a loop that adds the 4 charges together and then average the charges so the customer knows their average item charge. Even I want to create a statement to find the average. Display the average with a label and format number with dollar sign and two decimal places.
When I run this code I in the total variable only last value from the myCharges is displayed. I want the total and the average.
For the average i need help to print with 2 decimal places.
double[] myCharges = {12,13,14,15.55} ;
 double total = 0;
 for (int i = 0; i < myCharges.Length; i++)
 {
     total += myCharges[i];
 }
  Console.WriteLine("Total of MyCharges are {0:C}", total);
  Console.WriteLine("Average of MyCharges are {0:C}", myCharges.Average().ToString("0.00));
  Console.ReadKey();

Answer: You are looking for Enumerable.Sum():
Console.WriteLine("Total of MyCharges are {0:C}", myCharges.Sum());

Your current code does store only last value of array because of the total = myCharges[i]; assignment that forgets previous value. You can fix it by using +=:
for (int i = 0; i < myCharges.Length; i++)
{
     total += myCharges[i];
}

Comment: This works as well, and is harder to mess up than the for loop in the OPs code.
Answer: Your 6th line should read
total += myCharges[i];

Using just = does assignment when you want it to sum. Just for clarity, += is the same as saying total = total + myCharges[i].
As far as 2 decimal places go, the C (currency) formatting string should take care of it for you. If you don't want the average formatted as currency, try the F2 format string, or one of the others on: MSDN
Answer: You're overwriting the value of total every loop.  You'll want to do this (note the + sign):
total += myCharges[i];

Alternatively you can skip the loop and use:
myCharges.Sum();

To get 2 decimal places you can do this:
myCharges.Average().ToString("0.00");

Comment: The currency string he is using also will do 2 decimal places, as would using "F2" for a non-currency format string.
Comment: Ahh, Ok. I don't usually format my strings that way :)
Comment: I believe F2 is the equivalant of "0.00" (perhaps without the leading 0 if the number is less than 0), try putting "F2" instead of "0.00" and see what happens. The format strings are also more "normal" when doing String.Format (which, incidentally, is what Console.Writeline actually calls).
Comment: I have to use for loop and total is suppose to be calculated inside the loop. Total += myCharges[i] is working perfectly fine
Comment: myCharges.Averges().ToString("0.00")) is working perfectly fine
Answer: Alexei's answer is a better way to calculate Sum. However, to point out where you're going wrong for educational purposes you can see the line in your code:
total = myCharges[i];

only holds the current value. To fix that change it instead to:
total += myCharges[i];

But really, using the built-in functionality is simpler.