Find the highest $n\in \mathbb N$ such that $f^{(n)}$ exists

Question:
Let $f: \mathbb R\rightarrow \mathbb R$ which for $x \in \mathbb R$: $$f(x)=\begin{cases}\frac{e^x-1}{x}, & x\neq 0\\1, & x=0\end{cases}$$ Find $\sup\left\{ n\in \mathbb N: f\text{ is }n\text{-times differentiable}\right\} $.

My try:For starters, let's check if $f$ has $f^{(1)}$:For $x\neq 0$:

$f$ is a composite of elemental differentiable functions so also $f$ is differentiable for $x\neq 0$

For $x=0$:
$$f'(0)=\lim_{x\rightarrow 0}\frac{f(x)-f(0)}{x-0}=\lim_{x\rightarrow 0}\frac{\frac{e^x-1}{x}-1}{x}=\lim_{x\rightarrow 0}\frac{e^x-1-x}{x^2}=\lim_{x\rightarrow 0}\frac{1+x+\frac{x^2}{2}+o(x^2)-1-x}{x^2}=\frac{1}{2}+\frac{o(x^2)}{x^2}=\frac{1}{2}$$However we know that for $x=0$: $f(x)=1$ so $f'(x)=0\neq \frac{1}{2}$That's why in my opinion $f$ hasn't $f'$ so also other derivative not exist.  However I think I can have an error because then this task is really easy.Can you check it?
Comment: "$f$ is differentiable" has nothing to do with $n$. You should write
$$ \sup\{ n \in\mathbb N : f \text{ is } n\text{-times differentiable} \}$$
Comment: Since we are considering natural numbers only, I think the question is to find the highest $n\in\mathbb{Z}_{\geq0}$ such that $f^{(n)}$ exists
Comment: @MP3129 no problem :)
Comment: What role does $n$ play here?
Comment: For example if $f$ is $100-\text{times}$ differentiable then answer is $100$ because then $\sup(n\in \mathbb N: \text{f is differentiable})=100$
Comment: @RMWGNE96 yes, you have right, I used your proposition and edited my topic, thank you
Comment: @CalvinKhor yes, I'm sorry for my mistake, I corrected it
Answer: If we know that $f(x)=1$ for all $x$ in an interval around $0,$ then we can conclude that $f'(0)=0,$ but this is not the case. Let me apply the same argument to $g(x)=x$ to show you the issue.

"Let $\alpha$ be any real number. On the one hand, $$g'(\alpha):=\lim_{x\to \alpha}\frac{g(x)-g(\alpha)}{x-\alpha}=\lim_{x\to \alpha}\frac{x-\alpha}{x-\alpha}=\lim_{x\to \alpha}1=1.$$ But on the other, we know that $g(\alpha)=\alpha,$ so since $\alpha'=0,$ then $g'(\alpha)=0\ne 1.$ Thus, $f$ is nowhere differentiable."

Rather, you have directly calculated $f'(0)=\frac12.$ Thus, $f$ is once differentiable, at least.

It turns out that we can do even better, using the fact that $$e^x=\sum_{n=0}^\infty\frac{x^n}{n!},$$ so that $$e^x-1=\sum_{n=1}^\infty\frac{x^n}{n!}=x\sum_{n=1}^\infty\frac{x^{n-1}}{n!}=x\sum_{n=0}^\infty\frac{x^n}{(n+1)!}.$$
At this point, we can fairly directly prove that $$f(x)=\sum_{n=0}^\infty\frac{x^n}{(n+1)!}$$ for all $x\in\Bbb R.$ Thus, $f$ is differentiable as many times as we like at $0,$ and the $n$th derivative will be $\frac1{n+1}$ for all $n.$ Since $f$ is differentiable as many times as we like everywhere else, too, then $f$ is differentiable as many times as we like everywhere.
Comment: +1 for understanding what mistake OP made
Comment: (Small typo, the $n$th derivative should be multiplied by $n!$)
Comment: @CalvinKhor: Drat! I had it right the first time....
Comment: yeah :) I think the power series of $\exp$ is a good way to remember, since $\exp'=\exp$ we know all the derivatives are 1 at 0, and the power series has $/n!$ in it
Answer: $$\frac{e^x- 1}x = \frac{\sum_{k=0}^\infty \frac{x^{k}}{k!}-1}x = \frac{\sum_{k=1}^\infty \frac{x^{k}}{k!}}x = \sum_{k=1}^\infty \frac{x^{k-1}}{k!}  =\sum_{n=0}^\infty \frac{x^n}{(n+1)!}=1+\frac{x}2+\frac{x^2}{6}+\dots$$
So this function is analytic with convergent everywhere power series $f(x)=\sum_{n=0}^\infty a_n x^n$ given above. The derivatives at $0$ are $$f^{(n)}(0) = n!a_n = \frac{1}{n+1}.$$
I have no idea what you mean by

$\text { However we know that for } x=0 : f(x)=1 \text { so } f^{\prime}(x)=0 \neq \frac{1}{2}$

Graph of $f$, some derivatives and a 5th order Taylor polynomial:

This function actually has a name, it is the  (1,2)-Mittag-Leffler function
$$ f(x) = E_{1,2}(x) = \sum_{n=0}^\infty \frac{x^n}{\Gamma(n+2)}.$$
For similar reasons, $\operatorname{sinc}(x):=\frac{\sin(x)}x$ only has a removable singularity at 0.
Comment: @MP3129 Consider the function $g(x) = 1+x$. Then for $x=0$, $g(x)=1$. So "of course" $$\lim_{x\to 0}g'(0)=0?$$ but $$\frac{g(x)-g(0)}{x-0} =\lim_{x\to 0} \frac{1+x - 1}{x-0} = 1 \neq 0?$$
This reasoning is faulty, $g$ is differentiable infinitely many times.  you cannot use the derivative of the constant function to help you. You should instead trust the limit definition.
Comment: "I have no idea what you mean by" - in my sollution I get that $f'(0)=\frac{1}{2}$ but we know that $f'(0)=0$ so it is contradition and I wrote that $0 \neq \frac{1}{2}$
Comment: @MP3129: Actually, we don't know that $f'(0)=0,$ because it's not true. See my answer.
Comment: How do you know that $f'(0)=0?$ that's not true @MP3129 . 1/2 is correct
Comment: Maybe I have not expressed myself clearly, so I am sorry, I will explain more what I mean:for $x=0$ we know that $f(x)=1$. The derivative of the constant function is equal $0$. So if $ f $ is differentiable for $ x = 0 $ then $f'(0)=0=\lim_{x\rightarrow 0}\frac{f(x)=f(0)}{x-0}$. However if $\lim_{x\rightarrow 0}\frac{f(x)=f(0)}{x-0}=\frac{1}{2}$ then this equality does not occur


finding efficiently the correlation cofactor in probability

Question: would appreciate your help with this question:
a regular die is being thrown 21 times. we define:
$x_1$ - the number of throws we obtained 1 or 2.
$x_2$ - the number of throws we obtained 3,4,5,6.
how can i calculate the correlation cofactor between $x_1$ and $x_2$
my attempt:
so according to the details, i think that in order to find the correlation cofactor, i need to solve: $p(x_1,x_2)=\frac{cov(x_1,x_2)}{\sqrt{var(x_1)var(x_2)}}$, so i get that $p(x_1,x_2)=\frac{E[x_1x_2]-E[x_1]E[x_2]}{\sqrt{((E[x_1^2]-(E[x_1])^2)(E[x_2^2]-(E[x_2])^2)}}$, and it becomes a huge mess. is there a smart or efficient way to solve it using the given data instead of a lot of calculations?
would really appreciate your help and insights.
thank you very much!
Answer: Covariance is bilinear and symmetric.

If $X,Y$ are random variables with $X=aY+b$ where $a,b$ are constants then: $$\mathsf{Var}X=\mathsf{Var}(aY+b)=a^2\mathsf{Var}Y$$
and:$$\mathsf{Cov}(X,Y)=\mathsf{Cov}(aY+b,Y)=a\mathsf{Cov}(Y,Y)=a\mathsf{Var}Y$$
If $a\neq0$ and $Y$ is not degenerated then this leads to:$$\rho(X,Y)=\frac{\mathsf{Cov}(X,Y)}{\sqrt{\mathsf{Var}X}\sqrt{\mathsf{Var}Y}}=\frac{a\mathsf{Var}Y}{\sqrt{a^2\mathsf{Var}Y}\sqrt{\mathsf{Var}Y}}=\frac{a}{|a|}$$
Apply this on $X_1=(-1)X_2+21$.
Comment: wow, thank you very much for this. so much to learn here
Comment: Take your time. Glad to help.
Answer: Before we answer your question: consider the random variable $X$ that follows $Bin(n,p)$ . What we get is that $E(X) = np$ and that $V(X) = np(1-p)$.
In this particular case,$X_1$ follows $Bin(21,1/3)$ and $X_2$ follows $Bin(21,2/3)$. You can easily calculate now $E(X_1),V(X_1),E(X_2),V(X_2)$.All you have to find now is $E(X_1X_2)$,but in this particular case you can notice that $X_2 = 21- X_1$ and replace it above.


Why are pluggable adapters rarely used?

Question: I was reading Design Patterns by GOF and pluggable adapters caught my eye. I read up on this conversation https://coderanch.com/t/98662/engineering/pluggable-adapter and I like this answer Pluggable Adapter as mentioned in the GOF but still had a few questions:

Why are pluggable adapters not used more often? They provide more flexibility but according to GOF an interface adaptation would have been built into the Target so I guess the Target is forgotten to be designed for possible future adaptations in this aspect?
How is reflection used to implement pluggable adapters? And how is this not applying the Object style of the Adapter pattern?
Answer:
Pluggable Adapters are more work. They require planning for the future, rather than just planning for the present. You could argue that Pluggable Adapters violate YAGNI.
Reflection is an implementation detail. It is not a requirement for any GoF pattern. The book never mentions reflection, which makes sense, because that would limit the patterns to languages supporting reflection. Of course, you could implement an Adapter using reflection if you wanted to (you could implement anything using reflection if you wanted to). It likely would not be a Pluggable Adapter, because if the target had already gone to the trouble of making itself Pluggable, an Adapter should be simple enough without reflection.

Why are pluggable adapters rarely used?


Como ativar contador com um determinado scroll

Question: Tenho o seguinte problema, preciso ativar um contador quando o usuário rolar o scroll até a div onde se encontra os números, porém no meu código o contador funciona e depois parece que ativa novamente a função, tentei usar um preventDefault() dentro do complete porém ele me retorna undefined.
Segue abaixo um exemplo do meu código:

function ativaContador(e){
$('.contador').each(function() {
            $(this).prop('Counter', 0).animate({
                Counter: $(this).text()
            }, {
                duration: 4000,
                easing: 'swing',
                step: function(now) {
                    $(this).text(Math.ceil(now)+'%');
                },
              complete: function(){

              },
            });

        });
  }

$(window).scroll(function(e) {
  var alturaBody = $(window).height();
  var distanciaElemento = $('.contador').offset().top;
  var posicaoScroll = $(this).scrollTop();
  var alturaElemento = $('.contador').outerHeight();

  if (posicaoScroll > (distanciaElemento+alturaElemento-alturaBody)){
    ativaContador();
   }
});
.bloco{
  height:2000px;
}

100

Answer: Você está usando uma animação, e a mesma se repete. Para parar a repetição é necessário utilizar o método stop() quando a animação estiver completa.
O primeiro parâmetro diz para limpar o Queue da animação, o segundo diz para pular para o fim da animação, que é opcional, sendo que a animação já está no fim.
Veja mais: https://api.jquery.com/stop/

function ativaContador(e){
$('.contador').each(function() {
            $(this).prop('Counter', 0).animate({
                Counter: $(this).text()
            }, {
                duration: 4000,
                easing: 'swing',
                step: function(now) {

                    $(this).text(Math.ceil(now)+'%');
                },
              complete: function(){
            $(this).stop(true,true)
              },
            });

        });
  }

$(window).scroll(function(e) {
  var alturaBody = $(window).height();
  var distanciaElemento = $('.contador').offset().top;
  var posicaoScroll = $(this).scrollTop();
  var alturaElemento = $('.contador').outerHeight();

  if (posicaoScroll > (distanciaElemento+alturaElemento-alturaBody)){
    ativaContador();
   }
});
.bloco{
  height:2000px;
}

100


NFL teams with as many or more thrown interceptions than completions in a game

Question: The Denver Broncos had only a single completion pass while they threw 2 interceptions against the New Orleans Saints in week 12 of the 2020 season. The low completion count was due to all the Broncos quarterbacks being deemed ineligible to play the day before the match, after one of them tested positive for the Covid-19 virus, and the other 3 (including the practice squad QB) being in high contact with him. And due to the NFL protocols regarding the pandemic, the Broncos weren't able to sign a free agent quarterback and have him ready to start in time for the game.
The Broncos ended up starting a wide receiver from the practice squad as their QB, who went 1/9 for passes with 2 interceptions. This made the first NFL match in 20+ years where a team had thrown more interceptions than completions. Since the NFL/AFL merger, what are all the games that had at least one side with as many or more thrown interceptions than completions?
Answer: It happened 15 times in total; mostly in the early days (twelve times in the 1970s, then once in the 1980s and once in the 1990s).  Many early post-merger teams didn't pass much, after all, and so when they tried sometimes it worked out poorly.
A particularly fun case is 1974's Jets @ Bills game, which featured Broadway Joe Namath for the Jets, against a Bills team featuring Joe Ferguson who led the league in attempts and passing yards just three years later.  The line?
<code>Joe Namath:   2 completions (on 18 attempts), 3 INTs
Joe Ferguson: 0 completions (on  2 attempts), 0 INTs
</code>
You can be forgiven for looking at the "@ Bills" part of that and assuming this game was played in a snowstorm; no, it was actually in the mid 60s that day, though perhaps with some wind.
More impressively, some of these teams actually won their games!  See for example the match in that same year, 1974, between John Madden's Raiders and Hank Stram's Chiefs, a real barnburner of a game; the Raiders won, 7-6, on 181 rushing yards, 3 completions (including a TD!) and 3 interceptionss.  The Chiefs on the other hand featured the great Len Dawson, and managed 12 completions for 126 yards and 2 INTs, but unfortunately for them never broke the plane, and George Blanda's kick sailed through the uprights to seal the win for the Raiders.  This game might have been more likely to have been affected by the weather of course, at 23 degrees (wind chill 9!).

Boston Patriots at Kansas City Chiefs - October 11th, 1970
Cleveland Browns at Baltimore Colts - September 26th, 1971
Oakland Raiders at Houston Oilers - October 9th, 1972
Chicago Bears at Philadelphia Eagles - December 10th, 1972
New York Jets at Buffalo Bills - September 29th, 1974
Pittsburgh Steelers at Cleveland Browns - November 17th, 1974
Oakland Raiders at Kansas City Chiefs - December 8th, 1974
Oakland Raiders at Cincinnati Bengals - October 19th, 1975
Atlanta Falcons at Minnesota Vikings - November 9th, 1975
San Diego Chargers at Tampa Bay Buccaneers - September 19th, 1976
Denver Broncos at Chicago Bears - December 12th, 1976
Houston Oilers at Pittsburgh Steelers - October 23rd, 1977
Kansas City Chiefs at San Diego Chargers - November 2nd, 1986
San Diego Chargers at Kansas City Chiefs - September 20th, 1998
New Orleans Saints at Denver Broncos - November 29th, 2020


Graphite: How to make historic whisper data available through web app

Question: I've recently reconfigured my graphite setup from a single carbon-cache instance to several carbon-cache instances. As I needed to cook this up on a new host without bringing down the old graphite server while setting up, I now have a whisper directory with the historic metrics from the old server that I need to make available through the webapp on the new host.
I copied the dir to the new host and added an entry in the webapp local_settings.py:
DATA_DIRS = ['/carbon1/whisper','/carbon2/whisper','/carbon3/whisper','/carbon4/whisper','/whisper-archive']
whisper-archive is the dir I'm talking about. Unfortunately, the data is not showing up. Am I doing something wrong or is there a better way to do this?
running graphite 0.10.0 source install
on freebsd 10.0-RELEASE-p12
Comment: I've tried to run whisper-merge on some of the files, but to no avail.
Comment: whisper-dump both files then whisper-merge them.
Answer: I think it's just going to look in these places and use the data from the first one it finds. If you want to have the old data in the same graphs as the new one, then I think you're going to have to use whisper-dump to dump the data out of both the old and new metrics and whisper-merge to combine them.
Answer: In the end Steve was mostly right.
The problem was I had the archive folder first in the list of data dirs. When a query came through with a timespan that bridged the changeover the webapp got a response from the archive folder and stopped looking further.
The fix, however, was not like Steve explains. Instead I had to whisper-merge the old data into the new whisper files. Since I have 4 carbon cache stores and a replication of 2, this was trickier then usual.
I ended up whipping up a quick bash script to recursively merge the data into it's matching, newer, counterparts.  Here's a snippet in case it can help someone:
<code>for l in $(find /whisper-archive -type f -name '*.wsp'); do

  for c in {1..4}; do
    echo -n "carbon$c: Checking whisper file: $l..."; #debug output

    # I made a tmp file with the list of whisper files in each carbon instance
    # for quick searching and handy list for validation

    grep $l ./carbon$c.files.txt >/dev/null \
         && sudo /usr/local/bin/whisper-merge.py \
                 /whisper-archive/$l /carbon$c/whisper/$l;

    echo 'done'; # debug output
  done;
done;
</code>


Desempilhando pilha dinâmica

Question: Eu tenho um algoritmo de pilha dinâmica. Só que se eu inserir 10 elementos na pilha e for desempilhar sem remover o primeiro elemento ele da falha de segmentação. E se eu remover o primeiro elemento do topo sobrando 9 8 7 6 5 4 3 2 1 e depois desempilhar, ele remove 4 elementos ao invés de remover um só, entao ficando 9 4 3 2 1.

Como eu resolvo isso para que ele remova um só elemento ao desemplihar?
E como faço para inserir 10 elementos na pilha e desempilhar sem dar falha de segmentação?

O código:
#include <iostream>

struct pilha
{
 int num;
 pilha *prox;
};

int main()
{
 pilha *topo = NULL;
 pilha *aux;
 int op;
  do
   {
    std::cout << "\n\n\tPILHA DESEMPLILHA COMO ESTRUTURA DINAMICA"
                 "\n\tMENU DE ESCOLHA DA PILHA"
                 "\n\t1 - INSERIR NA PILHA"
                 "\n\t2 - CONSULTAR TODA PILHA"
                 "\n\t3 - REMOVER DA PILHA"
                 "\n\t4 - DESEMPILHAR A PILIHA"
                 "\n\t5 - ESVAZIAR A PILHA"
                 "\n\t6 - SAIR"
                 "\n\tESCOLHA: ";
    std::cin >> op;

   if(op == 1)
    {
     std::cout << "\n\tINSIRA NUMERO NA PILHA: ";
     pilha *novo = new pilha();
     std::cin >> novo->num;
     novo->prox = topo;
     topo = novo;
     std::cout << "\n\tNUMERO "<<novo->num<<" INSERIDO COM SUCESSO!!!";
    }

   if(op == 2)
    {
     if(topo == NULL)std::cout << "\n\tPILHA VAZIA!!!";
     else
      {
       std::cout << "\n\tPILHA COMPLETA: ";
       aux = topo;
       while(aux != NULL)
       {
        std::cout << aux->num << " ";
        aux = aux->prox;
       }
      }
    }

   if(op == 3)
    {
     if(topo == NULL)std::cout << "\n\tPILHA VAZIA!!!";
     else
      {
       aux = topo;
       std::cout << "\n\tNUMERO: " << topo->num << " REMOVIDO COM SUCESSO!!!";
       topo = topo->prox;
       delete(aux);
      }
    }

   if(op == 4)
    {
     if(topo == NULL)std::cout << "\n\tPILHA VAZIA!!!";
     else
      {
       std::cout<<"\n\tTOPO: "<<topo->num;
       aux = topo->prox;

       while(aux != NULL)
       {
        aux = aux->prox;
        topo->prox--;
       }
      }
    }

   if(op == 5)
    {
     if(topo == NULL)std::cout << "\n\tPILHA VAZIA!!!";
     else
      {
       aux = topo;
       while(aux != NULL)
       {
        topo = topo->prox;
        delete(aux);
        aux = topo;
       }
       std::cout << "\n\tPILHA ESVAZIADA COM SUCESSO!!!!";
      }
    }

   if(op<1 || op>6)std::cout << "\n\tOPCAO INVALIDA!!!";
   else
   if(op == 6)std::cout<<"\n\tGOOD BYE ...!!\n\n";

   }while(op != 6);
 return 0;
}

Answer: Todo o problema está na forma como você está "desempilhando" a pilha:
aux = topo->prox;

 while(aux != NULL)
{
   aux = aux->prox;
   topo->prox--;
}

Aqui há dois pontos a se destacar.

Não parece fazer sentido remover todos os elementos sem libertar a memória.
Você não pode decrementar o ponteiro prox (ou fazer qualquer coisa do tipo), porque neste caso se trata de uma pilha dinânica. Decrementar e incrementar só funciona com vetores, porque no caso dos vetores, a disposição dos elementos na memória é contínua. No caso de pilhas dinânmicas (ou listas) não se sabe ao certo qual a posição do próximo elemento ou do elemento anterior.

Sugestão de código:
aux = NULL;
if(topo->prox){
   if(topo->prox->prox)
      aux = topo->prox->prox;
   std::cout << "Item " << top->prox << "destruido com sucesso.\n";
   delete topo->prox;
   topo->prox = aux;
} else std::cout << "Item não destruido.\n";

Comment: ainda nao deu certo eu fiz isso ele esvazia a pilha.
Comment: mas a intenção é fazer o quê?
Comment: levantar o topo remover o proximo manter o topo e todos os numeros após o proximo. entao se eu tiver  1 2 3 4 5 o topo é o 5 entao teria que levantar o 5 remover o 4 e quando eu digitar o 2 ele me mostraria 1 2 3 5
Comment: Vou fazer a edição
Comment: agora deu certo mas a minha duvida é qual parte ai eu utilizo para mostrar: std::cout<<"NUMERO: "<<4<<" REMOVIDO COM SUCESSO."; ?
Comment: conssegui fazer aqui : pilha *removido = new pilha(); removido = topo->prox; std::cout << "\n\tNUMERO: " << removido->num << " REMOVIDO COM SUCESSO!!!";
Comment: Está bem, mas não entendi o porquê de alocar novamente a memória (removido = new pilha()), se você acaba fazendo o ponteiro apontar para outro lugar. Eu não andei testando, e parece que há um erro no meu código, é std::cout << "Item " << top->prox->num
Comment: capricho meu na hora que escrevi aqui no codigo nao esta assim eu só criei o ponteiro mesmo...

Desempilhando pilha dinâmica


List items of a certain content type in another content type

Question: For college we have to create a website with drupal. This website has to be for a travel agency that does surf vacations. We already have the  basic website up and running but are kinda stuck with the destinations.
I will quickly explain how the website should be set up and our problem.
So bassicly a customer should be able to go to the page called "Destinations" and have a list of the 4 available countries where they could book a vacation. Like for example you have Australia and Costa Rica. However when a user clicks on for example Australia he should get a new list of possible locations within this country where he wants to go surf.
We have tried with many different ways to get this to work the problem however is that both the countries and local destinations should have a picture and a short description. Also the user should be able to select their "level" on the specific location.

What we have tried:
Taxonomy: We have tried using taxonomy but it doesn't allow us to give the right design to the website. It will list the countries but without any description or picture.
Ubercart: I wish this would have worked but somehow you can't create subclasses in ubercart or just only show a list of classes with views.

Thank you for taking your time and we hope to find a solution soon.
Kind regards.
Comment: Dude you want the 'entity reference' module. Nodes within nodes...
Answer: A general out line is given below,

Create a content type for country, add your available
countries with images and description
Create a destination content type, with necessary fields like
image,description etc: (If you want process booking with payment, use
Ubercart and create a product class Destination, modify the required
fields)
Add a country field to destination contenttype of 'fieldtype' - Node Reference, choose widget as select list. This allows choose country on creation of a new destination
Use Views to list the destinations page, by selecting necessary fields,
Use views to create the list of related destinations based on the
country name and save it as a block. So based on the country
selection the destinations can be list in this block
If you are using online payment for booking use ubercart, otherwise
on booking you can send an enquiry to admin.

Hope you got an idea on how to proceed.
UPDATE
To get list of the destinations on clicking the country do the following

In your destination listing view, Add a 'Contextual filters'(
Arguments in D6) and choose the 'country nodereference field'.
In your four country listing view, in fields choose Nid (Nid)  also
and choose 'Exclude from display ' option for that field.
Then in the 'Country name field' - click 'Rewrite results' and choose
'Output this field as a link' checkbox. In link path give path like
below
eg: destinations/[nid]  ie: where destinations is the path of the
your destination page and [nid] is the token for the node id.
Probably you have to just change 'destinations' only with your path.

Thats it, now on clicking the country it will goto destinations page which shows all destinations belongs to the particular country
Comment: Ok, thank you for your information, the node refernce thing is something we haven't used yet because our understanding of Drupal is limited. I will let you know what the result it but it sounds promising.
Comment: Ok so we done what you told us and it seems to go in the right direction. However we have one major issue right now.

When you are on the page that lists all the countries and you click on a country, we get the description of that country and not the list of the destinations within that country. We have looked at views on how to change this but we can't seem to find the solution.
Comment: i updated the answer based on your requirement, see UPDATE  section in answer
Answer: If you want a ajax work it should be done by your own code.
If you don't care about load new pages then you can try with views.
Is this a drupal 6 project?
Oscar?
Comment: We don't know much about ajax and I think it should be done with Drupal. We have used views but I can't see how this could be used to solve our problem.

If you could help us out with views maybe that would be much appreciated.


How to prevent repetition of data display in report?

Question: Sample Report - Design

Sample Report - Preview

XML Code File
<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="report2" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="82a3ce80-bdcd-4d51-8f21-e72b3f438b53">

    <subDataset name="dataset1" uuid="70653a81-8d48-4edd-b72f-20f769f51aea">
        <queryString language="SQL">
            <![CDATA[SELECT
     schooldetails.`ID` AS schooldetails_ID,
     schooldetails.`Name` AS schooldetails_Name,
     schooldetails.`Boardtype` AS schooldetails_Boardtype,
     schooldetails.`Location` AS schooldetails_Location,
     schooldetails.`Phone` AS schooldetails_Phone,
     schooldetails.`Address` AS schooldetails_Address,
     schooldetails.`Additionaldetails` AS schooldetails_Additionaldetails
FROM
     `schooldetails` schooldetails]]>
        </queryString>
        <field name="schooldetails_ID" class="java.lang.Integer"/>
        <field name="schooldetails_Name" class="java.lang.String"/>
        <field name="schooldetails_Boardtype" class="java.lang.String"/>
        <field name="schooldetails_Phone" class="java.lang.String"/>
    </subDataset>
    <queryString>
        <![CDATA[SELECT
     schooldetails.`ID` AS schooldetails_ID,
     schooldetails.`Name` AS schooldetails_Name,
     schooldetails.`Boardtype` AS schooldetails_Boardtype,
     schooldetails.`Location` AS schooldetails_Location,
     schooldetails.`Phone` AS schooldetails_Phone,
     schooldetails.`Address` AS schooldetails_Address,
     schooldetails.`Additionaldetails` AS schooldetails_Additionaldetails
FROM
     `schooldetails` schooldetails]]>
    </queryString>
    <field name="schooldetails_ID" class="java.lang.Integer"/>
    <field name="schooldetails_Name" class="java.lang.String"/>
    <field name="schooldetails_Boardtype" class="java.lang.String"/>
    <field name="schooldetails_Location" class="java.lang.String"/>
    <field name="schooldetails_Phone" class="java.lang.String"/>
    <field name="schooldetails_Address" class="java.lang.String"/>
    <field name="schooldetails_Additionaldetails" class="java.lang.String"/>
    <background>
        <band splitType="Stretch"/>
    </background>
    <title>
        <band height="79" splitType="Stretch">
            <staticText>
                <reportElement uuid="e15d9fdb-5a73-421d-8059-3e6d84742a43" x="0" y="0" width="555" height="79"/>
                <textElement textAlignment="Center" verticalAlignment="Middle">

                </textElement>
                <text><![CDATA[Sample report 2]]></text>
            </staticText>
        </band>
    </title>
    <detail>
        <band height="114">
            <componentElement>
                <reportElement uuid="0752ad71-0544-4a92-bc06-666619eada15" key="table 1" style="table 1" x="0" y="0" width="360" height="50"/>
                <jr:table xmlns:jr="http://jasperreports.sourceforge.net/jasperreports/components" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports/components http://jasperreports.sourceforge.net/xsd/components.xsd">
                    <datasetRun subDataset="dataset1" uuid="46c3a1a8-1e2b-4ea0-b7ac-5b630657c146">
                        <connectionExpression><![CDATA[$P{REPORT_CONNECTION}]]></connectionExpression>
                    </datasetRun>
                    <jr:column width="99" uuid="b4badcbe-8219-4fcf-978c-b5ff6f2057d0">
                        <jr:columnHeader style="table 1_CH" height="30" rowSpan="1">
                            <staticText>
                                <reportElement uuid="09f0cb22-b9b2-499a-9e94-0d9edb96e5f8" x="0" y="0" width="99" height="30"/>
                                <textElement textAlignment="Center" verticalAlignment="Middle">

                                </textElement>
                                <text><![CDATA[School ID]]></text>
                            </staticText>
                        </jr:columnHeader>
                        <jr:detailCell style="table 1_TD" height="20" rowSpan="1">
                            <textField>
                                <reportElement uuid="0be272c3-3345-48fd-b90a-a0d0df3bc909" x="0" y="0" width="99" height="20"/>
                                <textElement textAlignment="Center" verticalAlignment="Middle">

                                </textElement>
                                <textFieldExpression><![CDATA[$F{schooldetails_ID}]]></textFieldExpression>
                            </textField>
                        </jr:detailCell>
                    </jr:column>
                    <jr:column width="160" uuid="1f036ef4-d3e4-4113-9084-5530b1e3e8d2">
                        <jr:columnHeader style="table 1_CH" height="30" rowSpan="1">
                            <staticText>
                                <reportElement uuid="9ef54b86-c6ac-4f0b-8904-ff82ace55d7c" x="0" y="0" width="160" height="30"/>
                                <textElement textAlignment="Center" verticalAlignment="Middle">

                                </textElement>
                                <text><![CDATA[Name]]></text>
                            </staticText>
                        </jr:columnHeader>
                        <jr:detailCell style="table 1_TD" height="20" rowSpan="1">
                            <textField>
                                <reportElement uuid="6c01ebc8-165d-41da-b632-8b19b67770ac" x="0" y="0" width="160" height="20"/>
                                <textElement textAlignment="Center" verticalAlignment="Middle">

                                </textElement>
                                <textFieldExpression><![CDATA[$F{schooldetails_Name}]]></textFieldExpression>
                            </textField>
                        </jr:detailCell>
                    </jr:column>
                    <jr:column width="114" uuid="7561e583-3af8-4799-ac88-2a7e8c164bfa">
                        <jr:columnHeader style="table 1_CH" height="30" rowSpan="1">
                            <staticText>
                                <reportElement uuid="c500ce42-e32d-4704-9832-52d7413926e3" x="0" y="0" width="114" height="30"/>
                                <textElement textAlignment="Center" verticalAlignment="Middle">

                                </textElement>
                                <text><![CDATA[Board]]></text>
                            </staticText>
                        </jr:columnHeader>
                        <jr:detailCell style="table 1_TD" height="20" rowSpan="1">
                            <textField>
                                <reportElement uuid="da078d0e-c6fb-4a3d-a0ed-ea12265cf729" x="0" y="0" width="114" height="20"/>
                                <textElement textAlignment="Center" verticalAlignment="Middle">

                                </textElement>
                                <textFieldExpression><![CDATA[$F{schooldetails_Boardtype}]]></textFieldExpression>
                            </textField>
                        </jr:detailCell>
                    </jr:column>
                    <jr:column width="131" uuid="7842fd3f-e097-4acd-a1ab-a09c0361c23b">
                        <jr:columnHeader style="table 1_CH" height="30" rowSpan="1">
                            <staticText>
                                <reportElement uuid="c0519344-d25a-4ed9-8970-1acf9e4857ed" x="0" y="0" width="131" height="30"/>
                                <textElement textAlignment="Center" verticalAlignment="Middle">

                                </textElement>
                                <text><![CDATA[Phone]]></text>
                            </staticText>
                        </jr:columnHeader>
                        <jr:detailCell style="table 1_TD" height="20" rowSpan="1">
                            <textField>
                                <reportElement uuid="560916c9-e02a-40c9-a7af-a63d285b900a" x="0" y="0" width="131" height="20"/>
                                <textElement textAlignment="Center" verticalAlignment="Middle">

                                </textElement>
                                <textFieldExpression><![CDATA[$F{schooldetails_Phone}]]></textFieldExpression>
                            </textField>
                        </jr:detailCell>
                    </jr:column>
                </jr:table>
            </componentElement>
        </band>
    </detail>
</jasperReport>

My Question
How can i avoid repetition of table display twice? I want the data
to be displayed only one time.
As you see in the above screen shots, I don't want the data to be
displayed twice.
Answer: You have put your table component into the detail band. The detail band is repeated for every record in the dataset. You have two records, so your table is repeated twice; If you had more data, you would get many more repetitions.
You could get rid of the table component completely, putting each columnHeader element from the table into a <columnHeader> band, and each detailCell element into a <detail> band. Doing this should preserve the behaviour of the table component without repeating it. See http://community.jaspersoft.com/wiki/designing-report for an example of this.
Alternatively, you could simply move your table component into a different band that doesn't get repeated (e.g. ).
Comment: @Dreamer: If you really need to put it in the detail band, you could try setting the `printWhenExpression` on the table to `$V{REPORT_COUNT} == 1`
Comment: thanks.. i already used this.. but was expecting whether there is a solution for using Table itself in the Detail band.. but since it wont work, i'm now using the summary band.. thanks for your replies.
Answer: Copy the table component in summary band and delete the detail band.
If you want repeated value in table data then edit your table component in Ireport and select the text field and   uncheck the "Print Repeated Values" check box property of a text field.
XML CODE will be like this:-
          </jr:columnHeader>
          <jr:detailCell style="table 1_TD" height="20" rowSpan="1">
             <textField>
                <reportElement uuid="560916c9-e02a-40c9-a7af-a63d285b900a"
          isPrintRepeatedValues="false" x="0" y="0" width="131" height="20"/>
             <textElement textAlignment="Center" verticalAlignment="Middle">

            </textElement>
           <textFieldExpression><![CDATA[$F{schooldetails_Phone}]]>
           </textFieldExpression>
             </textField>
            </jr:detailCell>
          </jr:column>

Comment: sorry.. tried your suggestion.. but still the table is displayed two times.. any other solutions ?
Comment: Use your original report and copy the table component  in summary band and delete the detail band
Answer: If your table shows multiple times within List component, uncheck "Print when Detail Overflow" and try. It works for me.


Cannot set subscriptions_status on migration from csv

Question: Modules used: Simplenews and Migrate.
I have a single newsletter, to which I want to subscribe all users imported from the csv file.
This is my csv file content:
id,email,date_submitted

This is my yml import file
langcode: en
status: true
dependencies: {  }
id: test_subscriber
class: null
field_plugin_method: null
cck_plugin_method: null
migration_tags:
   - CSV
migration_group: test
label: 'Test Subscriber'
source:
  plugin: csv
  path: sites/default/import/subscriber.csv
  delimiter: ','
  enclosure: '"'
  header_row_count: 1
  track_changes: true
  ids:
    - id
process:
  type:
    plugin: default_value
    default_value: simplenews_subscriber
  created: date_submitted
  mail: email
  status:
    plugin: default_value
    default_value: 1
  subscriptions:
    plugin: sub_process
    source: subscriptions
    process:
      target_id:
        plugin: default_value
        default_value: my_newsletter
      status:
        plugin: default_value
        default_value: 1
      timestamp: date_submitted
      source:
        plugin: default_value
        default_value: website
destination:
  plugin: 'entity:simplenews_subscriber'
migration_dependencies:
  required: {  }
  optional: {  }

I can successfully import all the user with email and timestamp but the users are not subscribed to the newsletter (my_newsletter).
In database I have the table "simplenews_subscriber__subscriptions but the columns: "entity_id", "subscription_target_id", "subscription_status", "subscription_timestamp" and "subscriptions_source" doesn't get populated.
If I change the subscription setting in the yml file as follow:
    subscriptions:
      target_id:
        plugin: default_value
        default_value: my_newsletter
      status:
        plugin: default_value
        default_value: 1
      timestamp:
        plugin: default_value
        default_value: date_submitted
      source:
        plugin: default_value
        default_value: website

In database table "simplenews_subscriber__subscriptions, the columns: "entity_id" and "subscription_target_id" get populated but the columns: "subscription_status", "subscription_timestamp" and "subscriptions_source" are filled with null instead of data.
The end result is a list of user unsubscribed to my_newsletter (from subscriber edit page the my_newsletter checkbox is unchecked)
Thanks in advance to anybody willing to give me a tip.
Answer: I finally was able to solve the issue.
Instead of this yml section code
subscriptions:
  target_id:
    plugin: default_value
    default_value: my_newsletter

I changed to this code
subscriptions/target_id:
  plugin: default_value
  default_value: my_newsletter

Here the full code
langcode: en
status: true
dependencies: {  }
id: test_subscriber
class: null
field_plugin_method: null
cck_plugin_method: null
migration_tags:
  - CSV
migration_group: test
label: 'Test Subscriber'
source:
  plugin: csv
  path: sites/default/import/subscriber.csv
  delimiter: ','
  enclosure: '"'
  header_row_count: 1
  track_changes: true
  ids:
    - id
process:
  type:
    plugin: default_value
    default_value: simplenews_subscriber
  created: date_submitted
  mail: email
  status:
    plugin: default_value
    default_value: 1
  subscriptions/target_id:
    plugin: default_value
    default_value: my_newsletter
  subscriptions/status:
    plugin: default_value
    default_value: 1
  subscriptions/timestamp:
    plugin: default_value
    default_value: date_submitted
  subscriptions/source:
    plugin: default_value
    default_value: website
destination:
  plugin: 'entity:simplenews_subscriber'
migration_dependencies:
  required: {  }
  optional: {  }


Laravel - Passar Variável Para View - Página Registro

Question: Estou utilizando Laravel 5.8 e adicionei um campo a mais no cadastro de usuários. Quero inserir um form select nesse campo mas, estou com dificuldade.
O que eu imaginei que daria pra fazer, era isso no arquivo  RegisterController.php (\app\Http\Controllers\Auth):
<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');

        $setores = \App\Setores::all();
        return view('auth.register', compact('setores'));
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
            'setor_id' => ['required'],
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\User
     */
    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
            'setor_id' => $data['setor_id'],
        ]);
    }

}

E isso:
  <select id="setor_id" name="setor_id">
  @if(count($setores)>0)
  @foreach($setores as $set)
   <option value="{{ $set->id }}" selected="selected"> {{ $set->nome }}
   </option>
  @endforeach
  @endif

No arquivo register.blade.php (\resources\views\auth)
Mas, estou recebendo o seguinte erro como retorno:

Facade\Ignition\Exceptions\ViewException
Undefined variable: setores (View: C:\xampp\htdocs..._...\resources\views\auth\register.blade.php)

Alguém sabe como eu poderia passar essa variável para minha View register.blade.php?
Comment: Procure  o método `register()` na classe `RegistersUsers` e sobrescreva esse método na sua classe `RegisterController` adicionando a variável `$setores` à sua view
Comment: Tem certeza que `view('auth.register', compact('setores'))` deveria estar no `__construct()` e não no método relativo ao `register.blade`?
Comment: Então. Eu não encontrei onde é chamada essa view. Vou postar todo o conteúdo do meu RegisterController.
Comment: Achei essa classe RegisterUsers.php e coloquei direto nela essa variável na chamada da View. Muito obrigada, Erlon!!!
Answer: Então cara, a forma que eu conheço pra fazer isso é definir no controller da view as variáveis que você quer passar na view. Eu geralmente faço da seguinte forma:
//Crio uma função INDEX para carregar a tela:

public function index() {

//aqui faço toda a lógica e tratativa, e após isso dou um return:

return view('sua_view.index', [
         'variavel1' => $variavel_definida_na_lógica_acima
        , 'variavel2' => $variavel_definida_na_lógica_acima
        , 'variavel3' => $variavel_definida_na_lógica_acima
        , 'variavel4' => $variavel_definida_na_lógica_acima
        , 'variavel5' => $variavel_definida_na_lógica_acima
    ]);
}

Depois que você ajustar a view e o retorno das variaveis, o erro mencionado (Undefined variable:) desaparece, e você pode chamar as variáveis dentro da view, que no caso seria
{{variavel1}} / {{variavel2}} / {{variavel3}} / {{variavel4}} / {{variavel5}}

Dai pra fazer o foreach funcionar, não esqueça de atribuir obviamente nas variáveis o tipo array, e depois só seguir o que você já estava fazendo.
Comigo funciona perfeitamente assim, e sinceramente acho que fica até mais organizado.
Espero ajudar.
Comment: Assim não dá certo pra mim. Eu coloquei o conteúdo a View Register acima.
Comment: Os Controllers gerados pelo Auth são diferentes. Não são dessa forma.
Answer: O RegisterController implementa a trait RedirectsUsers, nessa trait ela implementa o metodo showRegistrationForm() que é o método que é chamado quando você acessa a rota /register, então basta você sobrescrever o método dentro do RegisterController, ficaria algo assim:
public function showRegistrationForm()
{
    $setores = Setor::all();

    return view('auth.register', compact('setores'));
}


Can tld files be accessed from WEB-INF\lib\{*.jar}\META-INF\resources\WEB-INF directory?

Question: I have a jsp file which include a tag like:
<%@ taglib prefix="abc" uri="/WEB-INF/tlds/xyz.tld" %>

and in my app, the deploy structure is:
WEB-INF
  |-lib
      |-some.jar
          |-META-INF
              |-resources
                  |-WEB-INF
                      |-tlds
                          |-xyz.tld

this works fine in Tomcat 7, but when I deploy my app to JBoss as 7, it can not find the tld file.
so, is it an issue of JBoss(not support Servlet3.0?) or the tld files just can not accessed from META-INF\resources\WEB-INF directory in a jar?
Comment: Can you please post the error stack here ?
Answer: This is not a Servlet 3.0 issue, it's a JSP 2.2 question. (They're different specifications).
The uri portion of the taglib declaration is not a location. It is a key and must correspond to the content of the
<uri>your/tld/uri</uri>

element in the tld file.
If this element is missing then you must declare it in a taglib map in the web.xml, providing the uri there:
<jsp-config>
     <taglib>
         <taglib-uri>/WEB-INF/tlds/xyz.tld</taglib-uri>
         <taglib-location>/WEB-INF/lib/some.jar/META-INF/resources/WEB-INF/tlds/xyz.tld</taglib-location>
     </taglib>
</jsp-config>

Comment: Alternate solution that works too:  in the TLD file declare element your/tld/uri  rather than in the map in web.xml


Last two digits of $2^{11212}(2^{11213}-1)$

Question:
What are the last two digits of the perfect numbers $2^{11212}(2^{11213}-1)$?

I know that if $2^n-1$ is a prime, then $2^{n-1}(2^n-1)$ is a perfect number and that every even perfect number can be written in the form $2^n(2^n-1)$ where $2^n-1$ is prime. I'm not sure how to use this information though.
Answer: We want the remainder when the product is divided by $100$. Th remainder on division by $4$ is $0$, so all we need is the remainder on division by $25$.
Note that $\varphi(25)=20$. So by Euler's Theorem, $2^{20}\equiv 1\pmod{25}$. It is easier to note that $2^{10}\equiv -1\pmod{25}$.
It follows that $2^{11212}\equiv -4\pmod{25}$. The same idea shows that $2^{11213}-1\equiv -9\pmod{25}$. Thus our product is congruent to $36$, or equivalently $11$, modulo $25$.
Now solve $x\equiv 0\pmod{4}$, $x\equiv 11\pmod{25}$. The solution is $36$ modulo $100$.
Answer: A little playing with a calculator or a spreadsheet shows that the the last two digits of $2^n$ follow a pattern that repeats with a cycle length of $20$.  So, for example, $2^5$ ends in $32$;  $2^{25}$ ends in $32$, and $2^{45}$ ends in $32$ and so on.
We need to find the last two digits of $$2^{11212}(2^{11213}-1)=2^{22425}-2^{11212}$$ $22425 \mod 20$ is $5$;$2^5=32$.
$11212\mod 20$ is $12$;$2^{12}=4096$.
So, we need the last two digits of the number you get by subtracting a big number ending in $96$ from a much bigger number ending in $32$.  The answer is $36$
Comment: A curious factoid:  multiplying any power of 2 (except 0) by 76 leaves the last two digits unchanged...
Answer: HINT:
Note that $2^n-1$ is prime implies $n$ is prime.  Consider what that means for the form of $n$ as it applies to $2^n-1$.
Find the value of $2^n-1$ for several small values of $n$, enough to determine whether there is a pattern and if so, what it might be.  Apply the same logic to $2^{n-1}$, and then to the multiplication of the two.
Note that for $n\gt 2$ this implies that $n$ is odd.  So consider $2^{2k+1}-1$ and $2^{2k}$ for several small values of $k$ to see if a pattern develops.
Comment: I don't think your hint about the primality of $n$ is relevant.
Comment: Maybe not if you take the Andre Nicolas route and know the formulas off the top of your head that provide the answer directly.  My point is that $n$ must be odd which limits the value of $2^n-1$ and $2^{n-1}$ in specific ways.


Estimate the variance of Gaussian distribution from noisy sample

Question: I have measured a large data sample from an underlying Gaussian distribution and want to estimate the variance and its error. However, the measured values are noisy with some Gaussian noise with a standard deviation that is approximately known. How can I estimate the error of the sample variance in this case? First I computed the mean squared error $$\frac{2}{n-1} \sigma^4$$
which does not take into account the noise and seems to be too small.
What I also do not understand is, how one can compute the MSE if one does not know the true distribution, thus don't know the true $ \sigma$.
Comment: One aspect that may help, is that you can create a pivotal quantity for this problem.
Comment: @probabilityislogic Can you elaborate on how you would use that or refer me to some helpful material?
Comment: As you've described it the variance of the samples is $\sigma^2+\sigma_\epsilon^2$.  So if you know $\sigma_\epsilon^2$, you can subtract that from the variance of the samples.  (Estimating the precision of that estimate of $\sigma^2$ is another matter.)  If you don't know $\sigma_\epsilon^2$, then you can only estimate the sum of the two variances.  One way that allows you to get separate estimates is to take 2 or more estimates/measurements for each sample.  Then you can use a mixed model to get the separate estimates. If you know $\sigma_\epsilon^2$, why not consider a bootstrap approach?
Comment: @JimB I need some estimate for the error of my variance. By bootstrapping do you mean something like this: $Var[\hat{\theta}] = \frac{\sum_b^B \hat{\theta}_b - \hat{\bar{\theta}}}{B-1}$? How can I use my knowledge of $\sigma_\epsilon$ in this approach?
Answer: I would answer this question through the use of bayesian estimation with a "non-informative" prior.
notation and setup
Data model... $(y_i|\mu,\sigma^2)\sim N(\mu,\sigma^2+\sigma_e^2) $ for $i=1,\dots,n $
Prior... $p (\mu,\sigma^2)\propto(\sigma^2+\sigma_e^2)^{-2} $
The prior is not favouring one source. We have $\frac {\sigma^2}{\sigma^2+\sigma_e^2}\sim U (0,1) $ - the variance proportion is uniformly distributed in the prior. Now all this leads to a marginal posterior for $\sigma^2$ of
$$p (\sigma^2|DI)\propto(\sigma^2+\sigma_e^2)^{-(n+1)/2-1}\exp\left(-\frac {(n-1)s^2}{2(\sigma^2+\sigma_e^2)}\right)$$
This is a "truncated" inverse gamma distribution for $(\sigma^2+\sigma_e^2)$ with shape parameter $\frac {n+1}{2} $ and scale parameter $\frac {(n-1)s^2}{2} $ where $s^2=\frac {1}{n-1}\sum_{i=1}^n (y_i-\overline {y})^2$ and $\overline {y}=\frac {1}{n}\sum_{i=1}^n y_i $. The truncation is that $(\sigma^2+\sigma_e^2)>\sigma_e^2$
how to make use of this
First I would check if the truncation matters by calculating the probability that $(\sigma^2+\sigma_e^2)\leq \sigma_e^2$ using the inverse gamma cdf. A quick "eyeball" check can also be that $s^2>>\sigma_e^2$ (i.e. most of the variation in the data does not comes from measurement error).
If the truncation is not important, we can just use the normal inverse gamma. The expected value of the above posterior is $E(\sigma^2|DI)\approx s^2-\sigma_e^2$ and the variance is given as $$var(\sigma^2|DI)=var(\sigma^2+\sigma_e^2|DI)\approx\frac {2}{n-3}\left [E(\sigma^2+\sigma_e^2|DI)\right]^2\approx\frac {2}{n-3}s^4$$. You need to have $n>3$ to apply these formulae.
This is pretty much your expression but with $\sigma^2$ replaced by $s^2$.
If the truncation matters, the you'll need to work in terms of the incomplete gamma function. If you define the function $f (k)=\gamma \left (\frac {n+1}{2}+k, \frac {(n-1)s^2}{2\sigma_e^2}\right)$ then you have....for the expected value...
$$E (\sigma^2|DI)=s^2\frac{n-1}{2}\frac {f(-1)}{f (0)}-\sigma_e^2$$
And the variance is given by
$$var (\sigma^2|DI)=\left [E(\sigma^2+\sigma_e^2|DI)\right]^2\left [\frac{f (-2)f (0)}{f (-1)^2} - 1\right]$$
Comment: Thanks for your effort! I probably need some time to understand that. My statistics background is not that profound. What exactly means the $DI$ and how could $(\sigma^2 + \sigma_e^2) \leq \sigma_e^2$ be violated if the variances are always positive?
Comment: The notation "D" is just shorthand for "the data" and "I" is for "other information"
Comment: The term $\tau=(\sigma^2+\sigma^2_e)$ will assign a non-zero probability to the event $\tau\leq\sigma^2_e $ if we use the inverse gamma distribution *without truncation*. However, the formulas are analytic if we do this as an approximation.
Answer: If (using the notation of the answer from @probabilityislogic) $\sigma_e^2$ is known, then the maximum likelihood estimator of $\sigma^2$ is
$$\hat{\sigma}^2={{n-1}\over{n}}s^2-\sigma_e^2$$
(or rather the maximum of this and zero).  The estimate of the asymptotic variance of $\hat{\sigma}^2$ is given by
$$\frac{2 (n-1)^2 s^4}{n^3}$$
which for large $n$ is very close to
$$\frac{2s^4}{n}$$
And this is very similar to your result although by $\sigma^2$ you must mean $\sigma^2+\sigma_e^2$.  So your formula is consistent with the asymptotic theory.   Maybe you could expand on what you mean by "seems to be too small" and why you think that.


How can i loop through array of objects

Question: Here I wanted to loop through my array consisting elements as Objects. But my problem is that I was unable to pass spritearray[i] =(which should be) Ncardinal into the function text(label = (Ncardinal = {"name": "North", "lat": 0, "lon": 360})).
var sprite, label;
var radius = 1;
function text(label, radius)
{
 this.position.x = label.lat;
 this.position.y = label.lon;
};
var Ncardinal = {"name": "North", "lat": 0, "lon": 360};
var Scardinal = {"name": "South", "lat": 0, "lon": 180};
var Ecardinal = {"name": "East", "lat": 0, "lon": 90};
var spritearray = [Ncardinal, Scardinal, Ecardinal];
for(var i=0; i<spritearray.length; i++)
{
 sprite = new text(spritearray[i], radius);
}

Comment: your code makes no sense, because of the two opened curly brackets and the return inbetween
Comment: `sprite` should be an array `[]` where you `push` items. with your code, you create the `text` object and put it in sprite variable, only keeping the last one.
Comment: my major problem is with why i was unable to pass spritearray[i] = Ncardinal.. into the function and retrieve its elements inside the function like .lat, .lon ? sorry to say i just created a example code to explain my problem in programmatical way.. Nina scholz
Comment: Your parameters are being passed, that's all fine, but you needed to define the `position` property before adding sub-properties to it... see my answer with a working snippet.
Comment: Possible duplicate of [How to loop through an array containing objects and access their properties](http://stackoverflow.com/questions/16626735/how-to-loop-through-an-array-containing-objects-and-access-their-properties)
Answer: You need to define this.position before adding properties to it.

Here's a working version that outputs sprite positions onto the console:

var sprite, label;
var radius = 1;

function text(label, radius) {
  this.position = {};           // <---- this is the key
  this.position.x = label.lat;
  this.position.y = label.lon;

  // or all in one line
  // this.position = {x: label.lat, y: label.lon};
};
var Ncardinal = {
  "name": "North",
  "lat": 0,
  "lon": 360
};
var Scardinal = {
  "name": "South",
  "lat": 0,
  "lon": 180
};
var Ecardinal = {
  "name": "East",
  "lat": 0,
  "lon": 90
};
var spritearray = [Ncardinal, Scardinal, Ecardinal];
for (var i = 0; i < spritearray.length; i++) {
  sprite = new text(spritearray[i], radius);
  console.log(sprite);
}
Comment: it's returning `this`.

How can i loop through array of objects


how to extract data from excel (apache poi) to put it in mysql table using jsp?

Question: I want to extract data from excel sheet to insert it into a mysql table using jsp, so far i've done this and its printing data into the outpout(using apache poi),what should i add to this code ?
Output :
Name      Age        Adress

Mark       35      New york,AA

Elise      22      India,bb

Charlotte  45      France,cc

Readexcel.jsp :
<%@page import="java.sql.Statement"%>
<%@page import="java.util.ArrayList"%>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.Connection"%>
<%@page import="java.util.Date"%>
<%@page import="org.apache.poi.ss.usermodel.Cell"%>
<%@page import="org.apache.poi.ss.usermodel.Row"%>
<%@page import="org.apache.poi.xssf.usermodel.XSSFSheet"%>
<%@page import="org.apache.poi.xssf.usermodel.XSSFWorkbook"%>
<%@page import="java.io.File"%>
<%@page import="org.apache.commons.io.FilenameUtils"%>
<%@page import="org.apache.commons.fileupload.FileItem"%>
<%@page import="java.util.Iterator"%>
<%@page import="java.util.List"%>
<%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@page import="org.apache.commons.fileupload.FileItemFactory"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>PRINT DATA FROM EXCEL FILE</title>

    <%

         try{

        boolean ismultipart=ServletFileUpload.isMultipartContent(request);
        if(!ismultipart){

        }else{
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List items = null;

        try{
          items = upload.parseRequest(request);
        }catch(Exception e){
        }
        Iterator itr = items.iterator();
        while(itr.hasNext()){
            FileItem item = (FileItem)itr.next();
            if(item.isFormField()){

            }else{
                String itemname = item.getName();
                if((itemname==null || itemname.equals(""))){
                    continue;
                }
                String filename = FilenameUtils.getName(itemname);
                File f = checkExist(filename);
                item.write(f);
                try{

        XSSFWorkbook workbook = new XSSFWorkbook(item.getInputStream());
        XSSFSheet sheet = workbook.getSheetAt(0);

        Iterator<Row> rowIterator = sheet.iterator();
        while (rowIterator.hasNext()){
            Row row = rowIterator.next();
            Iterator<Cell> cellIterator = row.cellIterator();

            while (cellIterator.hasNext())
            {
                Cell cell = cellIterator.next();
                switch (cell.getCellType()){
                    case Cell.CELL_TYPE_NUMERIC:
                    out.print(cell.getNumericCellValue() + "t");
                     break;
                    case Cell.CELL_TYPE_STRING:
                    out.print(cell.getStringCellValue() + "t");

                      break;}
            }
            out.println("");

        }

    }catch (Exception e){
        e.printStackTrace();
    }
   }
            }
        }
    }catch(Exception e){
     }
     finally {
           out.close();
        }

            %>
 <%!
 private File checkExist(String fileName){
    String saveFile = "D:/upload/";
    File f = new File(saveFile+"/"+fileName);

    if(f.exists()){
        StringBuffer sb = new StringBuffer(fileName);
        sb.insert(sb.lastIndexOf("."),"-"+new Date().getTime());
        f = new File(saveFile+"/"+sb.toString());
    }
    return f;
   }

        %>

I've created a table in my database named EXCELDATA with the header of the excel sheet :
 ExcelData (Name varchar(50),age int,adress varchar(50));

what should i add to this code to get the data from the excel sheet to the mysql table ??
Comment: although this works its not the best idea to put code like this in a jsp. You cn google to find out why. A servlet migth be better. also if your wondering why the source html made by this jsp has a lot of blank lines its cause of the <%@page tags on top - nothing wrong if you dont mind them ... if you do just move the end tag to the next line ...
Answer: This is my excelimport.jsp file
     try{
         String name,age,address=null;

        Class.forName("com.mysql.jdbc.Driver");
        Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/dbname","username","password");

        con.setAutoCommit(false);
        PreparedStatement pstm = null ;
        FileInputStream input = new FileInputStream("C://yourexcelfile.xls");
        POIFSFileSystem fs = new POIFSFileSystem( input ); //creating a new poi reference to the given excel file
        HSSFWorkbook wb = new HSSFWorkbook(fs);
        HSSFSheet sheet = wb.getSheetAt(0);
        Row row;
         Statement st=con.createStatement();
        for(int i=1; i<=sheet.getLastRowNum(); i++){  //points to the starting of excel i.e excel first row
            row = (Row) sheet.getRow(i);  //sheet number

                   if( row.getCell(0)==null) { name = "0";}  //suppose excel cell is empty then its set to 0 the variable
                   else name = row.getCell(0).toString();   //else copies cell data to name variable

                   if( row.getCell(1)==null) { age = "0"; }
                   else age= row.getCell(1).toString();

                   if( row.getCell(2)==null) { address = "0";   }
                   else  address   = row.getCell(2).toString();

     String sq="INSERT INTO ExcelData(name,age,address) VALUES('"+name+"','"+age+"','"+address+"')";

            pstm = (PreparedStatement) con.prepareStatement(sq);//here we are using prepared statement because we are calling this statement for each row
            pstm.execute();
            System.out.println("Import rows "+i);
        }
        con.commit();
        pstm.close();
        con.close();
        input.close();
        System.out.println("Success import excel to mysql table");

    }catch(ClassNotFoundException e){
        out.println(e);
    }catch(SQLException ex){
       out.println(ex);
    }catch(IOException ioe){
       out.println(ioe);
    }

%>

Comment: Hi dileep , i tried your code after modifying it and this message shows up in my jsp : java.lang.ClassNotFoundException: com.mysql.jdbc.Driver , ichecked my mysql database and the "ExcelData table " is empty ,what should i do
Comment: add MySQL jdbc driver jar file in to your libraries...folder and please find jar file in below url https://code.google.com/p/find-ur-pal/downloads/detail?name=mysql-connector-java-5.1.18-bin.jar&  and let me know....
Comment: it's already done , i added apache poi jars +mysql-connector,but still no data in my table


Category of all categories vs. Set of all sets

Question: In naieve set theory, you quickly run into existence trouble if you try to do meta-things things like take "the set of all sets". For example, does the set of all sets that don't contain themselves contain itself? (see, Russell)
On the other hand, people have no trouble casually talking about the "category of all categories", etc. How do we know there isn't a contradiction lurking somewhere here - especially since many books define categories in terms of sets?
Comment: Perhaps this [wikipedia](http://en.wikipedia.org/wiki/Category_of_small_categories) page and references therein would help a bit?
Answer: If you base your mathematics on Set Theory, then you run into the same foundational issues in Category Theory as you do in Set Theory (since Categories will have to be modeled "with" Set Theory in some sense).
You can go the other way, though: you can base your mathematics with Category Theory, and develop the Category of Sets through it, as Lawvere does here. Then your primitive notions, the bedrock of your theory, is not Set Theory but Categories. There are precise ways in which you can talk about "Category of all categories", analogous to the way in which you can talk about "the class of all sets" if you start with Set Theory instead.
How do we know there are no problems lurking in this viewpoint? Well, we don't, just like we don't know that there are no serious problems lurking in Set Theory (e.g., that it is not consistent).
Comment: Awesome link! Thanks for that alone! +1
Answer: In general there are two ways to make foundations of category theory precise. The first one is to make use of Grothendieck universes, which is just a way to limit the number of sets we are considering. So when we say the category of sets (groups, modules, ...) is implicit that we are restricting ourselves to some universe which is a set in the usual sense. This approach isn't all nice, since we cannot prove in ZFC that every set $S$ belongs to some universe $\mathcal{U}$, so we need to take it as an axiom. However people seems to prefer this one.
The second one is the Neumann–Bernays–Gödel set theory (NBG). It is an axiomatic set theory where class is the primitive concept. Then we say that a class $S$ is a set if there is a class $C$ such that $A \in C$. Thus a set is a particular kind of class and a class that is not a set is called proper class. Using this axiomatic, the collection of all sets is a proper class. So when we say the category of sets (rings, topological spaces, ...) we have a proper class of objects. However we cannot speak of the class of all classes and we introduce the name small category to refer to categories with a set of objects. Then we can speak of the category of all small categories and functors between them.
NBG does not mess the other things we already have in mathematics since it is a  conservative extension  of ZFC. Meaning that all theorems we already know in ZFC are still valid in NBG and if we prove a theorem in NBG using only the language of ZFC then it is a theorem in ZFC.
But you don't need to worry too much with these things. In my opinion they are very technical for a first course and in most cases they are not really important. Just treat your categories in the same naive way almost everyone treats sets and remember that things can be done precisely.
Answer: I'm not sure what Arturo has in mind with his link (which is an axiomatization of set theory, not of category theory), but it's well-known that there is the same issues with the category of all categories that there is with the set of all sets.  It doesn't normally arise because the types of constructions that you would want to do don't lead to contradiction, but the same thing is true of set theory.
The existence of a contradiction seems to be folklore, but this message by Steve Simpson on the Foundation of Mathematics mailing list gives a contradiction in pretty careful detail.  Carsten Butz replies saying that this type of example is well-known.
People seem to be increasingly careful about the issue, and emphasizing that they are taking about a "large" category of "small" categories, where "large" and "small" can be made precise in the two different ways that Nuno discusses.
Comment: Sorry, I don't see how that answers the original question.  How does that help you avoid the Russell paradox?  "Naive category theory" will have the paradox, just as naive set theory will.
Comment: What I had in mind is exactly what I said I had in mind: Lawvere axiomatizes set theory taking Category theory for granted; that is, he bases set theory on categories (rather than the approach in, say, Mac Lane, which bases Category Theory in set theory).
Answer: You can talk about "the category of all categories" with the proviso "in a given universe". "Our universe" is big enough to include the set of natural numbers and all the usual operations you do with sets (union, intersection...) See Mac Lane's "Categories for the working mathematician", first chapter, for the details.
Answer: There's a big distinction between sets and categories. Russell paradox makes sense in sets because of Separation Axiom. Nothing like this is needed in categories. Russell paradox just cannot be formulated, you cannot talk about "the category of such categories that...". So what would be the problem is categories are not based on set theory? None. Set theory is not based on set theory. I believe it's a pretty legit category.
More, nobody doubts that a category Set is a legitimate category, whatever the definition. It does contain "all sets". But it's not a set, so Separation Axiom is not a part of its description.
Comment: P.S. I wonder what caused all these negative reactions to my, I thought, simple explanation.
Comment: It seems to me that we use some analog of the Separation axiom quite often when we construct a category. For ex., when you say "category of groups", you mean the collection of all pairs of sets  (G, *) such that...
Comment: @Mihail this is a very good point, but that's if you define a group as a set. More, if you define a group as a set with an operation, "such that". There's more than one approach. We can define a category of groups in a given, e.g., topos.
Comment: Could you suggest a link where I can read about alternative definition of a category of groups?
Comment: See e.g. https://ncatlab.org/nlab/show/Grp and https://ncatlab.org/nlab/show/group and https://www.andrew.cmu.edu/course/80-413-713/notes/chap04.pdf and any example from model theory taking group theory as a theory and its models in a topos.


How to get rdp client ip in c++?

Question: I want to find client address and PORT in remote desktop connection.
I want to use windows API and c++ programing in windows.
Answer: window has a IP tables that have all connected IP, that is in the IphlpAPI.
this is a link for that:(http://msdn.microsoft.com/en-us/library/ms923578.aspx)

How to get rdp client ip in c++?


Custom configuration variable not available when running locally

Question: I have set my variable with firebase functions:config:set stripe.key="xxxxxxx"
firebase functions:config:get > .runtimeconfig.json exports config correctly to the functions folder.
{
  "stripe": {
    "key": "xxxxxxxxx"
  }
}

However using functions.config().stripe.key returns the error when running firebase serve:
TypeError: Cannot read property 'key' of undefined
at Object. (C:\Users\ash\Documents\GitHub\danceform\functions\index.js:14:38)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at C:\Users\ash\AppData\Roaming\nvm\v6.11.5\node_modules\firebase-tools\lib\triggerParser.js:21:11
at Object. (C:\Users\ash\AppData\Roaming\nvm\v6.11.5\node_modules\firebase-tools\lib\triggerParser.js:75:3)

Windows 10
firebase-admin: ^5.13.1,
firebase-functions: ^2.0.2
firebase-tools: 4.0.0
nodejs: 6.11.5
UPDATE EDIT
Creating the .runtimeconfig.json file manually with VScode resolves the issue. The problem appears to be when creating the file with firebase functions:config:sget > .runtimeconfig.json (powershell)
Even though both files have the same CR/LF line endings and exactly the same text. What could be causing this?
Answer: Resolved by using CMD instead of powershell to do functions:config:get >.runtimeconfig.json


Voice leading confusion

Question: I perfectly understand the theory of voice leading when explained in most theory books about moving voices between chords in the shortest possible manner to give a smooth connection between chords.
But in practice I never can see/understand the voice leading in sheet music because the chords generally are arpeggiated with melodic/motivic figures interspersed and/or chord inversions thrown in between.
Can someone explain in a logical way how voice leading works when there are a large number of notes per chord and many choices.
I do realize that one can make a "reduction" and remove non-harmonic tones but even this tends to be lacking(over simplified) in many real world cases. (specially when there is confusion in exactly which note is non-harmonic)
The way I see it is there is a much more complicated effect going on than the simple rules given in (most) theory books. The same applies to pitch resolution. e.g., most examples are extremely simplified(quarter notes in 4/4) or musical examples are chosen to "prove" the theory(i.e., the picking and choosing fallacy).
Comment: Another good example tends to be on the acoustic guitar. The standard open guitar chords do not allow for proper voice leading yet is extremely common. Many times the chords go from 6 notes(open E, open G) to 4 notes(open D). The loss of notes is due almost entirely to the physical limitation/setup of the instrument and nothing else. (one could argue that the top voice is the most important in voice leading and the other inner melodies can skip around if necessary)
Comment: Could you provide an example passage where you find voice-leading difficult to apply?
Comment: @oliTUTilo Pick just about any passage in any piece of music. As I pointed out, the oversimpled idea of voice leading is "A melody note moves the shortest distance to the next note" but much of music contains many melodies, instruments carrying the melodies, notes that are not important, notes that have delayed resolution, etc...
Comment: If you need to find an example then pick a random bar from some Haydn piano sonata and chances are you will have a good example. (there will be at least one note that doesn't seem to have voice leading, unless one explains it in some complicated manner such as some weird delayed and octave movement or voice transference)
Answer: The rather strict rules of voice-leading as we might first be taught aren't meant to summarize the art. They are to be taken as a spring-board into a greater but harder to define understanding of music. It looks like you've had enough of those beginning exercises in simple 4-part homophonic part-writing.
Those patterns and "rules" of voice leading that we might be taught are supposed to be easier to apply and understand than the broader principles of actual practice.  Composers don't always resolve tendency tones and might use more skips than your instructor would have preferred in an intro to voice leading class.  But tendency tones are called tendency tones for a reason, and skips reduce our ability to hear the integrity of a voice, so they are solid concepts to understand, for example.
Most generally, voice-leading is just the way voices move about in a piece.  Usually, good voice leading means that each voice feels smooth, atleast somewhat independent, at least somewhat interesting, and supportive of the background harmony and feel of the piece.  Besides the standard ways we're first taught to voice-lead, it helps for voices to possess their own melodic or rhythmic aspects.  You can look to contrapuntal devices.  But I'm not aware of any hard-and-fast criteria.
I wouldn't be too stuck on removing "non-harmonic tones", as they are part of the actual progression of the voices (voice leading).
Let's use a phrase from Haydn's Piano Sonata in Eb (Hob XVI:49) to demonstrate some simple examples of nice voice leading (see Brendel's performance, segment ~0:35-0:47).

The blue lines connect notes in an independent voice. The green dot shows the entrance of an independent voice, while the red dot shows its exit. The orange dot shows the entrance of a voice as an entity that is largely subordinate to the top voice, and the orange lines emphasize this subordination.
Notice that on the third beat of the first seven measures the upper voice drops a step and then makes a substantial leap.  This adds a feeling of unity to the voice in the phrase and adds melodic interest: nice voice leading.  The step down resolves the suspension over the change in harmony on each third beat, and the jump up emphasizes the first beat of the next measure: nice voice leading.  The middle voice enters on measure four to fill out the harmony to raise intensity, but also provides a bit of counter to the first voice: nice voice leading.  It drops out at the end of measure five, temporarily reducing the intensity and shaping the phrases' mood.  But it comes back in measure eight, and this time in a more supportive role to the first voice, really raising the intensity.  In measure 9, the bass now has to get in on the escalation, doubling at the octave and rising up to meet the upper voices in a cadence.  The upper voice harks back to its suspending-resolving ways of measures 1-7 by making the cadence metrically unaccented.  Nice voice leading.
I'm not sure what subjective feelings of these (or any) were intended by Haydn, but the phrase sounds pretty cool to me, and it's largely due to the way he progresses the voices.
Comment: The example you show is rather simple and deceiving as the harmony changes on the 3rd beat which then supports the skip. The melody alone skips a bar line and this makes it seem like what are evading voice leading but in reality it is just a skip from a harmonic tone to another(since the chord has not changed). It's harmonic aspects would be better understood if the notation was shifted one beat(of course, the performance would change).  While I appreciate the example I think it is a bit simpler than it looks(basically two voices which it's more difficult to find problems of voice leading.
Comment: Although, even in the figuration of the bass, we see that voice leading does not hold up under the standard rules or at least is hard to decipher(blindly applying the rules will lead to failure). Of course, if we treat the figuration as a compound melody then we can see the lower notes act like a bass and jump around from roots (E E B E B A E) while the tenor voice seems to move step whiles across chords but leaps inside chords(which is ok but it is difficult to see at first glance)
Comment: I think this piece, though, is rather deceptively. It would be better for a true 4 part harmony. Since, as you stated, most of the time the melody follows proper voice leading(And the bass jumps around) so in a two part texture you don't have much to work with.
Comment: --"The melody alone skips a bar line and this makes it seem like what are evading voice leading but in reality it is just a skip from a harmonic tone to another."  I'm not sure I understand that sentence, but voices can skip to harmonically near or far tones and still retain integrity.  --"..I think it is a bit simpler than it looks."  How does it look?  Maybe I'll add a more intense example.  -- Are you concerned that voice-leading doesn't apply to the example?  I guess I'm having trouble understanding your concerns.
Comment: You do realize that the harmony changes on the 3rd beat and not the 1st beat(the last 2 eighth notes) I'm not saying the harmonic pulse changes on the 3rd beat but that the harmony changes(a bit different). `| I - (V7) | V - (I) | I - (IV) | IV - (I) |`  Which then, the melody can see has a series of suspensions with the last eighth note of each bar resolving the suspension. The leap, is just a leap between two CT's. No big deal. If you  try to analyze it transitionally(the harmony changing on 1 then the melody must be described in a much more complex way(a bunch of escape tones).
Answer: The trick with voice leading is that the concept of voices is meant to be somewhat more abstract than most people realise.
It is no accident that voice leading is traditionally taught in four voices.  One of these is the bass voice, which is unique, and obeys its own set of rules, because of its need to frequently sing/play the root of the chord.  The remaining three voices represent each of the three tones in a triad, which must each move in certain ways relative to each other.  In traditional voice leading instruction, these voices are treated as literal voices, that will sing actual melodies made up of the pitches that voice leading dictates (note that there are often multiple options).
As an example, when moving from a triad to another triad whose root is up a fourth, ignoring the bass line, the traditional patterns are: Common tone (the root of the first chord is kept to be the fifth of the second chord, and the third and fifth of the first chord both step up to become the root and third of the new chord, respectively); Contrary to the bass (all three notes move downward to the nearest chord tone - the third must actually skip down to become the fifth of the next chord); Tertian Leap (a combination of the last two:  the root of the first chord is kept common to become the root of the new chord, but the fifth falls to become the root of the new chord, and so the third must leap all the way to third of the new chord in order that the new chord has a third - in traditional voice leading, the chord must always have a third); and Triple Root (again, a combination of the first two, where the third rises and the fifth falls, both to become the root of the new chord, but the root skips down to become the third of the new chord - there is no fifth, which - unlike the third - can sometimes be omitted).
There are a couple of points to this.  First, these patterns are just ready-made combinations that happen to avoid the true voice leading errors (of which there are only a few).  No parallel fifths or octaves (if both chords are in root position, that means that in the upper voices, the root should never move to the root, the fifth should never move to the fifth), the chord must always have a root and a third, and should usually have a fifth.
Second, the voice leading of a voice partly determines and is partly dependent upon the other voices.  For instance, if the melody moves from the fifth of the chord up to the third of the next chord, the other two voices will most likely move as in the common tone patter (though atypical voice leading is possible if no rules are broken - however, this often makes proper voice leading in subsequent chords more difficult, which is part of why the patterns are used).
Most importantly, though, the voices aren't real.  They are artificial constructs that are created by the patterns.  It might be more accurate to call them "group chord-tone tendencies".  It doesn't really matter if there are voices, or how many there are.  What matters is how to move the various combinations of notes.  The guitar is a perfect example.  In spite of preceding comments, the guitar is actually surprising good at voice leading - as long as you don't care about the number of voices (which are all artificial anyway).  The traditional chord shapes mostly don't cause parallel motion (though barre chords do).  Suppose you were going to move from an E major chord to an A major chord.  In the E major chord, the root (E) is on both the fourth string and the first string, and in both cases, it stays common to become the fifth of the A major chord.  It is important to keep in mind that these are not two different voices, they are two instances of the same voice.  The third of the E major chord (G#) is on the third string, and it rises to become the root of the A major chord.  The fifths of the E major chord is on the second string, and it rises to become the third (C#) of the A major chord.  The same tone is also on the fifth string; once again, it is just a second instance of the same voice (not another voice), but this time it doesn't follow its partner,, it disappears, and the root from the sixth string moves up to the fifth string to become the new root (this is a bass line, and follows different rules).  There is absolutely nothing wrong with the duplicated voice or with the voice that disappears.  All that matters is that the notes themselves move according to one of the acceptable patterns.
To be fair, I should say that a single note that is doubled might be able to move in different directions.  For example, after the triple root pattern, the new chord has three roots (one is in the bass) and no fifth.  In this case, the two upper roots must move differently in order to avoid parallel octaves and in order to get a complete chord in the next chord.  In the case of the guitar, a true fifth voice may even show up, where multiple voice leading patterns are used at the same time, as long as there are no parallel fifths.  But a root still will not move to another root (other than the bass note or in inversions), and the fifth still will not move to the fifth.
The guitar makes another useful point.  These chords need not be strummed all together.  They are often arpeggiated, meaning that they are played one after another, melodically.  When you do this, you are not creating a melody.  The notes themselves remain as representatives of the imaginary voices, and even though they might occur on opposite ends measures, several beats apart, they should still move according to these patterns.  Suppose you arpeggiate the E chord from the bottom up to the top, and then the A chord from the top down to the bottom.  On the page, it looks like a melody that skips its way up and then back down, but in reality, it is multiple voices that are still connected to each other across the distance, as though all the notes were being played together.  And remember, the voices can enter and leave at any time, they can be doubled or lose their doubles at any time.  And if the notes are far enough apart, the voice leading doesn't really even matter.
When an actual melody does contain a leap, in a way, it is like the melody is moving from one "voice" to another - remember, these voices are abstract, not literal - and it takes on the voice leading tendency of the new voice it has moved into.  At any given moment, as a chord is about to change, the melody can be assigned to one of these abstract voices, and must move according to the rules; if it was previously on the fifth of the chord, it can move to the root or third of the new chord, but traditionally not to the fifth (it does sometimes happen in other styles of music, but this is simply because the rule about parallel fifths is style-specific, and not universal).  Once this note moves, any other notes that may happen to move at the same time, or nearly the same time, must move in ways that fit the patterns - or drop out.  If you pick "any random bar from Haydn", you should be able to see that this is so.
In the special case of guitar with, say, power chords, or bar chords moving in large leaps in parallel, we still have a kid of voice leading, it is just a different kind.  A classical theorist might call it poor voice leading (lots of parallel fifths and octaves), but that is stylistically okay in most modern popular music.  More sophisticated theorists may suggest that certain voices are simply shifted up an octave and then move correctly; this is a bit of a conceit, but it suggests another way of thinking about voice leading.  Imagine a kind of graph paper or template paper that you could write on.  Suppose you have a G chord.  On your template paper, you would have faint watermarks of all the possible notes of the G chord (GBD) in all possible octaves lightly highlighted, with faint arrows showing all the places they could go to when the chord changes.  With the understanding that anywhere a note can go in its own octave it can also go in other octaves (and so not showing all these octave possibilities), the paper would show a repetitive, wallpaper-like pattern all the way down as each voice reappears in subsequent octaves.  In a way, this wallpaper is implied underneath all music, and the melody, rather like finding a way out through a maze, just traces out some of those arrows.
In summary, voice leading does not apply to true voices, but rather to notes that represent abstract voices.  In a piano part that uses two hands, even though it looks like there are only two voices, in an abstract way, there are four voices, and the piano parts weave their way in and out of the various abstract voices, and when the chords change, the notes must move according to the patterns for whatever voice they happen to be in at that moment.  Consider Bach's Cello suites, for instance.  Only one instrument, usually only one note at a time, so it looks like one melody, but really, it is jumping around between abstract voices, and they all move as though they were a choir (I promise you this is true, I have spent a great deal of time tracing them out to verify).
Answer: Voice leading allows harmony to not just serve as series of chords but as several lines of melody that form chords between them as they move.
For example:

You can see how harmonically, the same thing is being accomplished: C to Em. However, the way the second set of C to Em is arranged to accommodate less/easiest movement as possible is a great example of voice leading.
If you want a real-life concept, think about choral music. Composers who write successfully sung/popular choral music are always aware of voice Leading. Voice leading allows singers to more successfully sing in harmony because their melodic line is easier and moves logically all at the same time.
If you are wanting an applicable instance of Voice leading, I might recommend looking into Bach's extensive use of counterpoint, which in my opinion is a more advanced version of voice leading.
Comment: "Can someone explain in a logical way how voice leading works when there are a large number of notes per chord and many choices." If your just look for an answer to this then you need identify two things: 1. Are these chords made up of multiple melodic voices? If so, do the melodies exhibit the basic principle's of voice leading? 2. If not, then it the principle of voice leading doesn't apply.
Comment: You have done nothing but give a very brief explanation of voice leading. It is way more complex than that and the things I'm talking about understanding generally involve voice transference(octave displacement resolution), hidden suspension resolution, auxiliary resolution displacement, etc... As I have said, I understand the "text book" voice leading which you give a synopsis of. In real world applications it generally is much more complex.
Comment: Correct, that is because it was meant for writing easier and more natural sounding music for singers/musicians. It isn't entirely applicable in this era of music.
Comment: I'm not talking about modern music. Any cpp example would work. I don't have time now to find a good example but all you have given is a very basic explanation, but as I have said, I understand that just fine. At least, in most theory books say voice leading is very important and tend to give many conjured up simple examples. A few books will analyze a piece that is more complex BUT it seems like a rather artificial analysis without a strong theoretical foundation... essentially just trying to explain away NHT's any way they can.
Answer: To properly answer your question, it would be helpful to know the context of the voice-leading you're talking about.  When I refer to context, I am of course speaking about which musical period.
For example, from your question, one could infer that you are speaking about early-classical voice-leading techniques since you referenced Haydn.  However, voice-leading techniques of different musical periods (most notably those that came after the classical period) have different rules that had to be expanded in order to accurately handle the expansion of harmonic language.
In addition, some composers of the late classical and early romantic period (such as Beethoven for example,) were notorious and even created their careers in part by "breaking" not only the rules of voice-leading, but also of form and convention in order to create a fresh sound that would catch listeners by surprise.
In part, I believe that you answered your own question when you talked about "resolution."
Regardless of the time period, the appropriate voice-leading techniques used are largely determined by the way the composer wants to create resolution - whether it is harmonic progression or regression.  When there are many notes to choose from, you have to look at how the notes change between the chords.  Once you do that, you have to think about the way the music was written at the time it was written, and then you would also be wise to compare it to other works by the same composer.  This is because composers tend to have certain stylistic "fingerprints" and if you see that a particular composer is doing something a certain way and it is consistent, then that makes it easier to analyze as there is a greater likelihood that it is a convention and less of a mistake.
Lastly, it's also important to know how and what was taught for voice-leading for the given time period.  Some of these composers rejected their teacher's approaches once they themselves became established composers, while others strove to master the rules to the best of their ability - most notably J.S. Bach, Handel, and Haydn just to name a few.
Those three composers were masters of counterpoint and considered by many to have brought the forms of their tradition to the highest possible degree.
As a final thought, I would recommend looking at a wider variety of sheet music for more evidence of the treatment of voice-leading.  Just because a chord is presented as an arpeggio does not mean that the composer cannot have smooth voice-leading to the next arpeggiated chord.

Voice leading confusion


Image of a union under a bijective restriction

Question: There's a result that seems obvious that I'm having a hard time formally proving. Let $f: X \to Y$, $A, C \subset X$, and $B \subset Y$ and suppose $f|_A: A \to B$ is a bijection. Then it should be the case that $f(C \cap A) = f(C) \cap B$ (Munkres uses this fact in his explanation that covering maps are open, for example). This seems obviously true, but I can't figure out how to formally show that, for $b \in B$, if $b \in f(C)$, then $b \in f(C \cap A)$.
Answer: This is not true with additional assumptions.  For instance, let $X=\{1,2,3\}$, $B=Y=\{1,2\}$, $f(x)=\min(x,2)$, $A=\{1,2\}$, and $C=\{1,3\}$.  Then $f(C\cap A)=\{1\}$ but $f(C)\cap B=\{1,2\}$.
Comment: I just realised that I misread Munkres' discussion and concluded that I was probably wrong, as well. Thanks for saving my sanity.
Comment: +1 Re clarifying that $f|_{A}$ being a bijection does not imply that $f(C \cap A) = f(C) \cap f(A).$


Can't position React Native View at the bottom

Question: I am trying to position a React Native view at the bottom of my screen:
  <TouchableHighlight onPress={() => this.logout()}>
    <View style={{ position: "absolute", bottom: 0 }}>
      <Text>{SignOut}</Text>
    </View>
  </TouchableHighlight>

And the parent:
  <Fragment>
    <View>
      <ProfileSettings profile={this.state.profile} />
      <MainSettings data={this.state} />

    </View>
    <LogoutSettings />
  </Fragment>

And then the layout:
  <Fragment>
    <StatusBar barStyle="dark-content" />
    <SafeAreaView>
      {/*<BackgroundProcess />*/}

      {this.props.children}
    </SafeAreaView>
  </Fragment>

As far as I can tell, this should get me all the way to the bottom...
However instead, my View centers right in the middle of the screen.
What am I doing wrong here? Is there a better way to position a view at the bottom of the screen? Plenty of tutorials say to use position absolute and bottom 0, but it does not appear to be working in my specific use case
Answer: You can do it without position absolute . Add "flex:1" to view before "LogoutSettings" so it will have full height and "LogoutSettings" will be shown at bottom
Try this in parent
<Fragment>
    <View style={{flex:1}}>
      <ProfileSettings profile={this.state.profile} />
      <MainSettings data={this.state} />
    </View>
    <LogoutSettings />
  </Fragment>

Remove position absolute
<TouchableHighlight onPress={() => this.logout()}>
    <View >
      <Text>{SignOut}</Text>
    </View>
  </TouchableHighlight>

Comment: Yep, that worked. I'm still getting the hang of flex in React. Most annoying is when I change styling and elements just straight up disappear. As far as I can tell that's due to not putting width and height on objects that are flexed. Anyway, that's off topic. Thank you.
Answer: I think you want the style on TouchableHighlight, not View
  <TouchableHighlight onPress={() => this.logout()} style={{ position: "absolute", bottom: 0 }}>
    <View>
      <Text>{SignOut}</Text>
    </View>
  </TouchableHighlight>

You don't really need that View at all actually
Comment: Nope, even putting the styles on the TouchableHighlight, it's still right in the middle
Comment: Need more of your code, sounds like something else is conflicting
Comment: settingsHeight = Dimensions.get('window').height - 80;
Comment: But that's literally my only structure - what I posted above, so I'm not sure why.