Por que ainda consigo acessar uma variavel na heap mesmo depois da funçao terminar?

Question: Faz um tempo q apreendi sobre heap e stack, estava testando alguns códigos quando me deparei com um comportamento estranho na heap veja;
#include <iostream>
using namespace std;

void Test1(int *i[]);
void Test2(int *i);

int main()
{
    int *p[10];// declara um vetor ponterio para 10 inteiros
    int num_ = 10; //criar um interio com o nome num_ de valor 10 na heap

    p[0] = &num_; //passa o endereço de num_ para a primeira posiçao do vetor de ponteiros inteiros
    cout<< *p[0]<<endl; // mostra p[0] primeiro valor da primeira posiçao do vetor de ponteiros
    Test1(p);// chama a funçao Test1 q receber um vetor de ponteiros no paramentos
    cout<< *p[0]<<"**"<<endl; // o valor agr é 47, pq ?

//////////////////////////////////////////////////////////////////////////////////

    /*int *p_;
    int num__ = 10;
    p_ = &num__;
    cout<< *p_<<endl;
    soma_(p_);
    cout<< *p_<<endl;*/

    return 0;
}

void Test1(int *i[])
{
    int p = 47; //criar um inteiro na heap com valor 47
    i[0] = &p;/*passa o emdereço do interio "p" criado na heap para o vetor de interios*/
    /* no caso a variavel "p" foi criado na heap quando
     * essa funçao termina o "p" devia ser apagado assim p *i[0] agr nao devia aponta para luga nemhum,
     * mas quando sai da funçao Test1 o valor ainda esta acessivel no p[0] da main
     *  */
}

void Test2(int *i)
{
    int p = 47;
    i = &p;
}

Por que ainda posso acessar o valor 47 da variável int p da função test1, se o valor foi para heap e quando a função termina o valor p deveria ser apagado? Pelo que eu entendi sobre variáveis na heap, as variáveis são apagadas quando a função termina.
Comment: Nunca mais volte para este local que ensina errado. Ao que parece é exatamente o oposto.
Comment: Não tem nada no *heap*, então a pergunta parte de algo bem errado.
Comment: mas na função test1(int *p[]) ha uma variavel int p = 47 ,onde ela esta se não na heap?
Comment: No Stack.......
Comment: ctz pq vi em alguns site que uma variável dentro de uma função esta sempre na heap, so esta no stack se usasse o operador new para criar
Comment: não não desculpe eu que confundir a heap seria a memoria maior q usa o operdor new para alocar ne
Answer: Em nenhum mo momento este código faz uso do heap, então a confusão do que está acontecendo aí é geral.
Imagino que nem percebe que está misturando código C com C++. Pode, funciona, mas não é desejável, se souber o que está fazendo, ok, mas em geral as pessoas fazem isto por acidente.
Seria bom ler algumas coisas antes para entender o básico desses conceitos. Pesquise mais no site porque tem outras perguntas feitas que ajudarão entender depois de aprender o básico.

O que são e onde estão a "stack" e "heap"?
Performance de acesso a dados na heap e stack e alocação de objetos
Qual a finalidade da função free()?

Este é um dos famosos códigos que funcionam, mas estão errados. A parte boa de fazer em C ou C++ é que dura pouco, rapidinho vai estourar e dar problema, será um pouco tarde demais em alguns casos, mas será tão caótico que a pessoa vai ter que arrumar. Na verdade quase todo mundo desiste dessas linguagens depois de passar esse aperto e opta por linguagens que os erros não causam tanto problema. Algumas linguagens deixam funcionar até coisas erradas por quase todo tempo e isto é suficiente para muitas pessoas. Aqui estou te dando a dica para evitar esse caminho, mas sei que a maioria ignora e continua preferindo só ver funcionando.

No caso todas alocações estão no stack. Variáveis locais e parâmetros que não deixam de ser variáveis locais.

int *p[10];// declara um vetor ponterio para 10 inteiros

Isto está errado. Está declarando um vetor de 10 posições com ponteiros para inteiros (esses ponteiros devem apontar para inteiros)

cout<< *p[0]<<endl; // mostra p[0] primeiro valor da primeira posiçao do vetor de ponteiros

Isto está confuso. Está mostrando o valor apontado pela primeira posição do vetor p.

cout<< *p[0]<<"**"<<endl; // o valor agr é 47, pq ?

Porque sempre que passa algo por referência, e um vetor sempre é uma referência (um ponteiro), não está passando o objeto, não está copiando aquele conteúdo, está copiando o ponteiro que aponta para o objeto real, então tudo o que fizer na outra função vai refletir no objeto original porque tanto aqui quanto lá está apontando para o mesmo objeto, então fica óbvio que uma mudança em algum elemento dele não importa onde aconteceu a mudança será feito no objeto apontado, qualquer lugar que acessar esse objeto terá os mesmos dados. Por isso dizemos que ele é um objeto mutável, diferente de um inteiro isolado por exemplo que é imutável e, por valor e o objeto sempre é copiado se tornando outro objeto em cada uso diferente.

 i[0] = &p;/*passa o emdereço do interio "p" criado na heap para o vetor de interios*/

Aqui é o erro que eu falei. Está guardando no vetor um ponteiro para o valor anteriormente declarado no stack. Como você deve ter aprendido, ao final da execução da função as variáveis do stack deixam de existir. Mas é a variável que deixa de existir, não o objeto, acabou o tempo de vida deles, mas n]ao há uma destruíção. Claro, se a variável não aponta mais para ele não considere seguro continuar acessando-o, a qualquer momento ele poderá deixar de existir já que ele não é mais necessário. Ali poderá ser substituído por outro valor, pode ser colocado outro objeto no seu lugar. Na verdade na primeira chamada de função que tenha variáveis locais que atribuírem valor para elas sobrescreverá ali em cima mesmo onde estava esse objeto (isso depende um pouco de alguns fatores, não é tão simples porque depende da implementação).
Como você não chamou nenhuma outra função que estragou seu objeto está funcionando, mas isso é uma coincidência, não conte com isso.
Se deseja que o objeto sobreviva ao fim da função uma das formas é colocá-lo no heap, e aí o gerenciamento do tempo de vida dele é determinado por você. Em C++ arcaico aloca-se com new e remove com delete com o era com malloc() e free() em C. Mas hoje em C++ se faz de forma bem diferente, mais segura e automática. Esses operadores viraram praticamente detalhe de implementação em quase todos cenários de código moderno.
Tudo isso não é obrigatório em C ou C++, mas é assim que todas implementações funcionam.
Na verdade esse código tem vários erros e nem compila então tudo isso é teórico. Eu refiz o código demonstrando o que está falando:
#include <iostream>
using namespace std;

void Test2(int *i) {
    int p = 147;
    i = &p;
}

int main() {
    int *p[10];
    int num = 10;
    p[0] = #
    cout << *p[0] << endl;
    Test2(p[0]);
    cout << *p[0] << endl;
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Comment: Excelente resposta, mas então apesar de funcionar quando chamo o "Cout<< *[0] ; mostrar o 47 mas pode da mer...


Find general solution in radians of $\cos x + \cos 3x + \cos 5x = 0$

Question: I study maths as a hobby. I have this problem:
Find in radians the general solution of:
$$\cos x + \cos 3x + \cos 5x = 0$$
I have said:
$\cos 3x + \cos 5x = 2\cos\left( \frac{1}{2}(3x + 5x)\right)\cos\left( \frac{1}{2} (3x - 5x)\right) = 2\cos 4x\cos x$
$\cos x + 2\cos 4x \cdot \cos (x) = 0$
$(1 + 2\cos 4x)\cos x = 0$
$\cos x = 0$ or  $\cos 4x = - \frac{1}{2}$
$x = \frac{\pi}{2}$ or $x = \frac{\pi}{3} $
My book gives the answers as:
$(2n + 1)\frac{\pi}{6}, n\pi \pm \frac{\pi}{3}$
So we agree on the second answer but is the book wrong when it says $(2n + 1)\frac{\pi}{6}$?
I get the answer as $x = n\pi + \frac{\pi}{2}$, which can be written as $(2n +1)\frac{\pi}{2}$
Comment: But $n\pi \pm \frac{\pi}{3}$ does not cover all cases when $\cos 4x = -\frac{1}{2}$. Take $x = \pi/6$ as an example.
Comment: The first answer in the book covers cases of $\cos x = 0$ and remaining cases where $\cos 4x = - \frac{1}{2}$. So I think book is right.
Answer: $$\cos 4x =-1/2 \iff \cos4x +\cos \frac{\pi}{3} =0
\iff 2\cos\left(2x +\frac{\pi}{6} \right)\cos\left(2x-\frac{\pi}{6} \right)=0 \\
\iff \cos\left(2x +\frac{\pi}{6} \right) = 0 \text{ or } \cos\left(2x -\frac{\pi}{6} \right) = 0 \\
\iff 2x +\frac{\pi}{6} = \frac{\pi}{2}+n\pi \text{ or } 2x -\frac{\pi}{6} = \frac{\pi}{2}+n\pi \\
\iff 2x = \frac{\pi}{3}+n\pi \text{ or } 2x = \frac{2\pi}{3}+n\pi\\
\iff x=\frac{\pi}{6} + n\frac{\pi}{2} \text{ or }x= \frac{\pi}{3}+n\frac{\pi}{2} \\
\iff x= (3n+1) \frac{\pi}{6} \text{ or } x= (3n+2) \frac{\pi}{6}$$ And as you said, for $\cos x=0$ you need to take $$x=(2n+1) \frac{\pi}{2} = (6n+3)\frac{\pi}{6}$$
This is, in fact, equivalent to the book's answer. To see this, observe that the union of $3n+1, 3n+2, ,6n+3$ is all the integers $m$ such that $m\equiv 1,2,3,4,5 \pmod 6$, which is further equivalent to the union of the odd numbers and numbers of the form $6n+2$ and $6n-2$. So, the solution set can be written as $$x=(2n+1)\frac{\pi}{6} \ \text{or} \ (6n\pm 2)\frac{\pi}{6} = (2n+1)\frac{\pi}{6} \ \text{or} \ n\pi \pm \frac{\pi}{3}$$
Comment: Good edit @Axel
Comment: @Steblo Tavish's answer and the books are equivalent, when you look at the sets of solution they are the same. I could post an explanation later of why is it true if you want.
Comment: I have added an explanation for the same.
Comment: I get lost from the 3rd line on. And your answer doesn't match mine or the book's.
Comment: @Steblo What exactly didn't you understand? It shouldn't matter if it matches the book or your answer, as long as it is mathematically correct.
Comment: @Steblo The problem here is that you can have solutions with different forms. Let me explain, to give you an example $\{2k+1 | k \in \mathbb{Z} \} = \{4k+1 | k \in \mathbb{Z}\} \cup \{4k+3 | k \in \mathbb{Z}\} $ it is the same set but the expressions look different. Tell me if my explanation is not clear enough.
Comment: I follow all your working up to the point "This is in fact..." I cannot follow the reasoning why $(2n + 1)\frac{\pi}{2} = 2n + 1)\frac{\pi}{6} $ I think it's partly because I haven't yet studied unions of sets.
Comment: @Steblo That equality does not hold. All I'm saying is that the set of solutions is of the form $\frac{m\pi}{6}$ where $m$ can be anything, except a multiple of $6$.
Answer: Breaking up the multiple angles.
$$\cos3x=4\cos^3x-3\cos x$$
$$\cos5x=16\cos^5x-20\cos^3x+5\cos x$$
Plugging everything together:
$$16\cos^5x-16\cos^3x+3\cos x=0$$
Dividing by $\cos x$, and $\cos x$ can't be zero. Defining and plugging in we get:
$$y=\cos^2x$$
$$16y^2-16y+3=0$$
Can you take it from here?
Comment: Take a look at : https://en.wikipedia.org/wiki/List_of_trigonometric_identities#Multiple-angle_formulae
Answer: Two methods of attack (that haven't been mentionned) for such issues with angles in arithmetical progression:
a) It's more efficient to group extreme expressions, here $\cos(x)+\cos(5x)=2 \cos(3x)cos(2x)$, then factor $\cos(3x)$, which gives you instantly the answer.
b) or (longer and advisable only for more complicated cases) use complex numbers
$$\Re(e^{ix}+e^{3ix}+e^{i5x})=\Re(e^{ix}(1+e^{2ix}+e^{i4x}))$$
and recognize the sum of an arithmetic progression...
Answer: Method$\#1:$
Using Prosthaphaeresis Formulas on $\cos x+\cos5x,$
we get $0=\cos3x(1+2\cos2x)$
$\implies x=(2m+1)\dfrac\pi6$ or $2x=\dfrac{2\pi(3m\pm1)}3\iff x=\dfrac{\pi(6m\pm2)}6$  where $m$ is any integer
Method$\#2:$
Using Prosthaphaeresis Formulas on $\cos3x+\cos5x,$
we get $0=\cos x(1+2\cos4x)$
$\implies x=(2n+1)\dfrac\pi2=\dfrac{(6n+3)\pi}6$ or $4x=\dfrac{2\pi(3n\pm1)}3\iff x=\dfrac{\pi(3n\pm1)}6$  where $n$ is any integer
Method$\#3:$
Like How can we sum up $\sin$ and $\cos$ series when the angles are in arithmetic progression?
multiply both sides by $\sin\dfrac{3x-x}2=\sin x\ne0,$ and use Werner Formulas
$$0\cdot2\sin x=\sin2x+\sin4x-\sin2x+\sin6x-\sin4x\implies\sin6x=0$$
$$\implies x=\dfrac{r\pi}6\text{ where }r \text{ is any integer, not divisible by }6\text{ as }\sin x\ne0\text{(why?)}$$
So, we need to establish that the following three sets are equivalent :
$$\{r; 6\nmid r\}; \{2m+1,6m+2,6m-2\};\{6n+3, 3n+1, 3n-1\}$$
Take modulo $6,$
$$2m+1\equiv1,3,5; 6m+2\equiv2; 6m-2\equiv4\pmod6$$
$$6n+3\equiv3;3n+1\equiv1,4;3n-1\equiv2,5\pmod6$$
Answer: You can rewrite the equation in this form: $$\cos(3x-2x)+\cos 3x+\cos(3x+2x)=0$$ This is equivalent to: $$2\cos 3x \cos 2x + \cos 3x = \cos 3x (2\cos 2x+1)=0$$ Eventually, we have the equations $\cos 3x=0$ and $\cos 2x=-\frac{1}{2}$. $$3x=\pi n +\frac{\pi}{2} \space \space \text{or} \space \space 2x=2\pi n \pm \frac{2\pi}{3}\space \rightarrow \space x=\frac{\pi}{6}(2n+1)\space \space \text{or} \space \space x=\pi n \pm \frac{\pi}{3}$$
This is just one way to look at it. You reached $\cos x=0$ and $\cos 4x =-\frac{1}{2}$ equations in your solution. In this case, your solution set is: $$x=\frac{\pi}{6}(6n+3) \space \space \text{or} \space \space x=\frac{\pi}{6}(3n\pm1) $$ The difference here is correlated with the horizontal compression of trigonometric functions.


How can I create a very simple entity definition for Webform submissions?

Question: I make extensive use of the Webform module and often use Views for managing the webform submissions.
I'm fairly new to the Actions/Rules/Triggers backend of Views Bulk Operations (VBO), but I'd really like to be able to use it in my submission management views.
I've written a module that accepts submission IDs from the URL like so: mymodule/form/314/submissions/201+202+203 and generates a page with information from all the listed submissions (in this case, submissions 201, 202, and 203).
I want to use the VBO "Pass ids as arguments to a page" operation to select submissions in a my Views table, and pass their IDs to my custom page.
As far as I can tell, this isn't possible since webform submissions are not entities. So what I'm wondering is, how can I define a very simple entity type for webform submissions, so that I can use VBO on them?
I assume I should implement hook_entity_info(). I think the entity really only needs to include the submission ID in my case (the sid column in the webform_submissions db table).
I've read through the docs on defining custom entities, but can't figure out how to apply that stuff where I'm not actually wanting to create an entity type from scratch. Thanks!
Comment: Sorry, I'm not able to help you. I just wanted to say that what I see here is an abuse of webform module. IMHO you should have done everything with nodes. You would have had entities, views, VBO, and everything.
Comment: I'm not sure what you mean. I would have had entities, views, VBO--everything except **everything that Webform offers**: _FAPI forms, conditionals, and validation through the UI, automatic submission receipts (emails), submission database storage, submission exports, etc_. I don't even know how you'd go about doing what you're suggesting. Maybe others in the community can set this straight?
Comment: I'm not sure about FAPI forms but, for conditionals you have conditional_fields module. For validations you have the normal fields/entity editor or field_validation module. The submission receipt can be overloaded with a hook (or maybe there's a module for that). Submission database storage and basic reporting: nodes and views are exactly the strongest tools to store and retrieve content in drupal. It's just my opinion.
Comment: @ermannob, I appreciate your response, but I don't think I understand you fully. Are you saying I should have created a content type for every webform (there are 50+) and allowed users to create new nodes of that content type for every submission? I fail to see how setting up all the modules you mentioned (the functionality for which Webform handles more-or-less out of the box), in addition to managing 50+ content types, and form-specific user permissions is a good way to go for the sole purpose of getting a VBO checkbox in a Views report.
Comment: I understand it's too late now... You did a really impressive job with webforms! When you will build a new website, try to consider the "node way"! :)
Comment: With some research, I'm starting to see what you're talking about. Thanks for that insight, though it (as you said) doesn't help me much with my current issue. It will be interesting to see if the Webform project continues to progress toward using the Field API and Entities. For now, though, Webform meets all my needs--some minimal VBO support would just be the cherry on top.
Answer: Got it working. In a custom module (mymodule), I implemented hook_entity_info() like so:
function mymodule_entity_info() {
  $info = array();
  $info['mm_submission'] = array(
    'label' => t('Simple Webform Submission Entity'),
    'base table' => 'webform_submissions',
    'fieldable' => FALSE,
    'entity keys' => array(
      'id' => 'sid',
      'label' => 'sid',
    ),
  );
  return $info;
}

This very simple entity definition was sufficient for VBO to treat my submissions as entities and pass their IDs to my custom URL.
Though I didn't need to, it should be possible to override the entity class controller and its entity functions (load, save, delete, etc) should you need to. This tutorial by Ronald Ashri was useful to me and talks more about that.
After installing my custom module, I was pleasantly surprised to see a "Bulk operations: Webform submissions" field magically appear in the list of available Views fields.
I didn't make any other connection between Webform submissions and my custom entity type, nor otherwise tell VBO to treat the Views results as mm_submission entities--somebody (Views/VBO/Webform?) just automatically made it happen; which is awesome.
I presume VBO knew to process the submissions as mm_submission entities because of the entity type base table attribute? Not sure without looking more closely; perhaps someone else can shed more light on that.
Answer: There is a module available called Webform Entity that does just that although it goes further and makes the submissions fieldable. From that project page:

This module exposes webform submissions as a fieldable entity on behalf of webform and optionally provides a bundle for each of the content types for which webform functionality is enabled. This allows you to configure fields on a base form that are appended to the fields for the webform for that individual node and these fields can be exposed to views.


Combinations and Outcomes Confusion (PMF)

Question: I have added a resource I found online. There are no answers just notes.
My understanding is that the coin is tossed 4 times and we are asking what is the probability that the random variable X is equal to x=2? In this case, 2 Heads.
But
a. Where is the actual probability? I guess you would need the full PMF to know this?
b. Does the answer of 6 (n=4 choose=2) tell us that there are 6 outcomes where there are 2 Heads? And the probability of there being 2 Heads with n=4 would just be the amount of outcomes here(x=2)/total number of outcomes?
c. How do we figure out how many possible combinations in total there are with 4 tosses? (including where there are not two heads?) Sometimes I get confused between Simple Counting and Combinations.
Comment: You may have a clear idea what problem it is you want help with, but you've presented it in a rather confusing way.  The lead sentence talks about a resource you "found online" without any link to that, and you say, "There are no answers just notes."  Readers are given little idea from the huge image posted under that what you wanted to ask about.  Please consider editing your Question to fully pose the problem (the setup and goal) that Readers should be trying to respond to.
Answer: I will attempt to give a better explanation to the steps to find the probability. Perhaps this will help answer your three questions you have listed.
To start, there are $2×2×2×2 = 16$ possible outcomes for flipping a coin four times. This can be easily seen by the fact that each flip has two possibilities. To find the number of these outcomes that have two heads, we need to realize we need to choose $2$ out of the $4$ to be heads. If you are familiar with combinatorics, it is clear that the number of ways is $\binom{4}{2} = 6$. However, to say the probability of two heads in four flips is $6/16$ just from this information alone would be incorrect if we are dealing with a weighted or biased coin.
If the probability of flipping a head is $p$, then obviously the probability of tails must be $1-p$. Then the probability of flipping two heads in four flips must involve a product of $p^2$ and $(1-p)^2$, to account for two heads and two tails. And we cannot forget that there are $6$ ways to flip two heads in four flips, so our factor of $6$ must also be involved. This leads us to the formula you have described: $$\binom{4}{2} p^2 (1-p)^2$$.
If we do not have a a specified value for $p$, then this is as far as we can get aside from algebraic manipulation. With a specific $p$ between $0$ and $1$, we can simplify to a single number to represent the probability.
Notice that if we have a standard, unbiased coin, then our probability of heads would be a $0.5$, and by plugging in this $p$ we will get our $6/16$ from earlier.
Comment: I get 3/8 from doing the math in the last paragraph of yours,,, the reduced form..that is still correct, right?
Comment: Yes, this works as all you are doing is simplifying the fraction
Comment: btw, how would we need to change this formula if the weightings are different?


How to update an ion-slide after removing an Item?

Question: I have a list of cards in ion-slide, and each card has a close icon to remove it.
    <ion-slides >
                <ion-slide *ngFor="let item of cart; let i = index" >
                    <ion-card>

                      <ion-img  src='close.png'    (click)="removeData(item)" ></ion-img>
                  </ion-card>
  </ion-slide>
              </ion-slides>

home.page.ts
async removeData(object) {
    .......
      // get the index of object
this.dataservice.removeItem(index);
        .....
        }

DataServiceService.service.ts
removeItem(index) {
    return this.getAllItems().then((result) => {
      if (result) {
        result.splice(index, 1);
        return this.storage.set('i', result);
      }
    });
  }

When a card is removed, I want the list to be updated or the current page to be refreshed. I tried in the removeItem function
"this.router.navigate(["/home"]);" but nothing changed, and "window.location.reload();" reloads all pages starting with login.
Could you please suggest a solution to the problem?
Comment: pass index in removeData and check this code `this.cart[index]. splice(index,1)`
Comment: @RaviAshara Can you please write it as an answer? to be able to accept it
Answer: It is solved by using splice
   this.cart.splice(index, 1);


Per-IP bandwidth monitoring and trafic shaping solution for 100Mb network

Question: I have about 30 servers connecting into a Cisco 3500 series switch, with 100M upstream bandwidth.  Periodically, one or more of my servers will do a large file transfer which will completely saturate the network and cause 10-15% packet loss to other devices.  I need a good solution to 1) monitor my bandwidth on a per-IP Address basis across all the servers  2) Prevent any given IP from consuming more than 50% of the available bandwidth 3) Give priority to certain protocols (streaming traffic, SSH) and lower priority to other traffic (BitTorrent, SMTP, FTP).  I can monitor traffic on a per-port basis with that switch, but that does not give me any IP level visibility and no bandwidth control besides setting the port speed.
I have a spare Dell R200 with dual 1G NICs that I can devote to the cause and I'm fairly comfortable around Linux. I know this can be done with IPTABLES, TC and HTB, but I would rather have a more packaged solution with decent documentation and a management interface.  If the answer is buy Cisco XXX, I'm open to that also, but since I have a server sitting around, I though I'd try that first.
So the question is:  What Linux/BSD Firewall/Router/QOS solution would be meet these requirements?  I've seen the list at http://en.wikipedia.org/wiki/List_of_router_or_firewall_distributions, but I'm looking for real-world experience with any of them.
Answer: A pre-packaged solution for this type of scenario would be great, but I have yet to find the ideal one.  MY particular setting is a smaller Wireless ISP, but it is a similar problem of presenting particular clients from flooding the network.  Two solutions I've used:

cbq.init or htb.init.  Both of these easy the administration of managing the various tc queues and filtering.  If you already understand tc and shaping, this might be a nice way to help manage the various queues.  This is the solution I use for most of our bandwidth management servers.  Works farily well, but no integration into iptables for marking traffic.  We use the tc filters, but they are less then ideal.
The shorewall firewall project is a Linux package for general firewall management.  It includes support for bandwidth management, and appears to allow packages to be marked with iptables rules, which I find easier to deal with.  Larger learning curve, but might be worth it in the long run.
Comment: I'm testing Shorewall out now.  it looks like it will probably do everything I need it to.  Thanks
Answer: You can use Mikrotik RouterOS for traffic engineering. You can see Traffic Engineering features in http://wiki.mikrotik.com/wiki/Category:Manual that might suit your need.
Answer: Why not use some of the rate-limiting and QoS features in IOS on your switch?
Comment: The only rate limiting in the switch is per-port -- not per IP address.
Comment: What would be the difference in this case?


Porque eu não consigo comparar um objeto com outro objeto?

Question: Tenho o seguinte código bem simples
var x = new String("html");
var y = new String("html");

window.alert(x == y);

E ele me retorna semple false é possível eu realizar a comparação entre dois objetos? E porque eu não posso comparar dois objetos sendo que ambos são iguais?
Answer: Bem os objectos são tratados como referência, ou apontador de memória, por isso, não é possível usar === ou == para comparar os dois. Uma maneira rápida de comparar os dois objetos é ver se têm o mesmo valor na chave. Isto pode ser feito usando JSON.stringify. Outra maneira é usar a função Lodash isEqual.
const ob1 = {obj: 'A'};
const ob2 = {obj: 'A'};

// JavaScript
JSON.stringify(ob1) === JSON.stringify(ob2); // true

// Lodash
_.isEqual(ob1, ob2); // true

Uma nota no caso de escolher usar o JSON.stringify() tenha em atenção que a ordem das coisas (o par chave valor) é importante, por isso se não estiverem nos objetos na mesma ordem o resultado vai ser diferente.


Diebold-Mariano test in case of nested models (Clark & McCracken, 2001)

Question: I have become aware of Clark & McCracken (2001) showing that the asymptotics of the Diebold-Mariano test will potentially collapse when comparing forecast accuracy of nested models (such as GARCH / GJR-GARCH / APARCH).
How badly will this affect my results?
References:

Clark, Todd E., and Michael W. McCracken. "Tests of equal forecast accuracy and encompassing for nested models." Journal of Econometrics 105.1 (2001): 85-110.
Comment: I was going through my old answers and noticed this one was not accepted. Do you perhaps need further clarification?
Answer: It depends on what you want to learn from the test result.

If you wonder whether one forecast (say, $f_1$) is statistically more accurate than another (say, $f_2$), the Diebold-Mariano (DM) test will tell you that. At this point there is no talk of the models that generated the forecasts.
The DM test (as any other statistical test) targets making inference on the population rather than the current sample. If (1) the DM test tells you with 95% confidence that $f_1$ beats $f_2$ and (2) the forecast generating processes and the data generating process all remain unchanged in the future, then you would expect that $f_1$ will beat $f_2$ also in the future.
How can you benefit from this result? If you have the forecast generating process available, you could choose to use the one for $f_1$ rather than for $f_2$. However, Diebold (2015) does not encourage that:

The Diebold-Mariano (DM) test was intended for comparing forecasts; it has
  been, and remains, useful in that regard. The DM test was not intended for comparing models. Much of the large ensuing literature, however, uses DM-type tests for comparing models, in pseudo-out-of-sample environments. In that case, simpler yet more compelling full-sample model comparison procedures exist; they have been, and should continue to be, widely used.

If you wonder which of the alternative models is more likely to have generated the data, using the DM test will be problematic in case of nested models, as explained in Clark & McCracken (2001). (Once again, Diebold did not intend the test to be used for comparing models -- see the quote above.)
How bad does the DM fail in this sense? There are simulation results reported in the tables of Clark & McCracken (2001), you may check them.

References:

Clark, Todd E., and Michael W. McCracken. "Tests of equal forecast accuracy and encompassing for nested models." Journal of Econometrics 105.1 (2001): 85-110.
Free version here.
Diebold, Francis X. "Comparing predictive accuracy, twenty years later: A personal perspective on the use and abuse of Diebold–Mariano tests." Journal of Business & Economic Statistics 33.1 (2015): 1-9.
Free version here.


Finding the causal representation $x_t = 0.8x_{t-1} - 0.15 x_{t-2} + W_t - 0.30 W_{t-1}$

Question: I'm having troubles finding the causal representation of the ARMA model $x_t = 0.8x_{t-1} - 0.15 x_{t-2} + W_t - 0.30 W_{t-1}$. I began by removing the redundancy in the model such that
$\phi(B) = (1-0.5B)(1-0.3B)X_t$ and $\theta(B) = (1-0.3B)W_t$ becomes
$(1-0.5B)X_t = W_t$ but I'm not sure how I should expand it out in terms of $\psi = \phi^{-1}(B) \theta(B) $. Any ideas? Thank you!
Answer: $(1- 0.8 B + 0.15 B^2)x_t = (1 - 0.30 B)W_t$
$x_t = (1 - 0.30 B)/(1-0.8B + 0.15B^2) W_t $
$x_t = (1 - 0.30 B)/((1- 0.3B)(1- 0.5B)) W_t$
$x_t = W_t/(1- 0.5B)$
Then, you can use the geometric series formula and obtain
$x_t = \sum_{i=0}^{\infty} 0.5^{i} \times W_{t-i}$


Picture inside a row wrap container overflows just a little

Question: All of that container's items article wrap the way they should but the right border of that image overflows the container's article border.
My workaround is to add a mediaquery @1041px and a little padding so the border never reaches the image's border but there must be a cleaner way to figure that out.
And w/ or w/o the figure the result is the same.
article {
      border: solid black;
      border-width: 6px;
      font-family: 'Lato';
      font-size: 2.5em;
      display: flex;
      flex-direction: row;
      flex-wrap: wrap;
      justify-content: center;
      align-items: center;
      text-justify: distribute;
      padding: 5px;}

figure {
      margin: 0;
      line-height: 0;}

img {
      max-width: 100%;
      height: auto;
      border: black solid;
      border-width: 6px;
      margin: 5px;}

////

XXX XXX är född i XXX XXX och bosatt i XXX XXX.

Hon har vuxit upp i en mångkulturell familj med XXX
  bakgrund och är verksam som XXX,
  XXX och XXX.

XXX XXX är doktor vid XXX XXX och har
  också läst XXX XXX samt
  XXX XXX på XXX XXX i XXX XXX.

https://codepen.io/cykelcykel/pen/dyyvGBg
I don't want the container's right border to touch the image's border when resizing.
Answer: Try using box-sizing: border-box for the img as this will account the border added and apply margin for figure than the img itself.

article {
  border: solid black;
  border-width: 6px;
  font-family: 'Lato';
  font-size: 2.5em;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
  text-justify: distribute;
  padding: 5px;
}

figure {
  margin: 5px;
  line-height: 0;
}

img {
  max-width: 100%;
  height: auto;
  border: black solid;
  border-width: 6px;
  box-sizing: border-box;
}

.intro {
  display: flex;
  flex-direction: row;
  flex: 1;
  padding: 5px;
  align-items: center;
}

#one {
  border: solid black;
  border-width: 6px;
  margin: 5px;
  flex: 2;
}

#two {
  border: solid black;
  border-width: 6px;
  margin: 5px;
  flex: 2;
}

#three {
  border: solid black;
  border-width: 6px;
  margin: 5px;
  flex: 1;
}

XXX XXX är född i XXX XXX och bosatt i XXX XXX.

Hon har vuxit upp i en mångkulturell familj med XXX bakgrund och är verksam som XXX, XXX och XXX.

XXX XXX är doktor vid XXX XXX och har också läst översättning samt tolkning på XXX XXX i XXX.

Answer: Set the border on the figure element instead:

article {
  border: 6px solid black;
  font-family: 'Lato';
  font-size: 2.5em;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
  text-justify: distribute;
  padding: 5px;
}

figure {
  margin: 0;
  line-height: 0;
  border: solid 6px #000;
}

img {
  width: 100%;
}

.intro {
  display: flex;
  flex: 1;
  padding: 5px;
  align-items: center;
  flex-wrap: wrap;
}

#one, #two, #three {
  border: solid black;
  border-width: 6px;
  margin: 5px;
  flex: 2;
}

#three {
  flex: 1;
}

XXX XXX är född i XXX XXX och bosatt i XXX XXX.

Hon har vuxit upp i en mångkulturell familj med XXX bakgrund och är verksam som XXX, XXX och XXX.

XXX XXX är doktor vid XXX XXX och har också läst översättning samt tolkning på XXX XXX i XXX.


Is there a particular reason why the progression I - II4/2 - V6/5 - I was such a popular opening progression for Baroque keyboard preludes?

Question: I'm currently reading John Mortensen's wonderful book on keyboard improvisation. (See this link  here.)
In the chapter on figuration preludes he states that the progression I - II4/2 - V6/5 - I was a popular "opener" or "page one" progression for such preludes. The most famous example being of course Bach's Prelude in C Major from WTC 1, BWV 846.
But why this particular progression? In particular, I wonder about the role of II4/2 here. Not by any stretch an uncommon chord in the late Baroque, but not particularly ubiquitous either.
Of course, the goal of any opening progression should be to establish the tonality firmly, but there must be dozens of progressions that accomplish this.
Comment: Was it as famous before the Bach Prelude, or did it really become popular afterwards?
Comment: @Richard: Honestly, I don't know. I suppose Bach wasn't the very first to come with it.
Comment: @Richard as far as I can tell there's no evidence that the Bach prelude was particularly widely known during the baroque period.
Comment: Now I really want to get that book!
Comment: @MichaelCurtis It does look good. I know you've cited Gjerdingen before, does he (or does Sanguinetti, etc.) ever mention this particular idiom?
Comment: @Richard, I don't think Gjerdingen mentions it. But, he does mention two "openers" QUISENZA, which uses a tonic pedal, and a version of ROMANESCA which uses a tonic `I2/4` they all share certain similar elements.
Answer: If you are talking about the part of the book on pages 6 and 7 (that's what I can see in the Amazon preview), the author gives V6/5 in the harmonic skeleton, but some of the examples hold a tonic pedal for all the chords. So I think we need to be flexible about that particular chord.
When looking at the Bach example in D minor I notice, if you hold a tonic pedal and then play in the treble, the scale in thirds descending from the tonic, you pass through the sort of prototype "opener" harmony.
For simplicity, transposed to C...

I'm not sure this is really an answer. It's more an observation.
Of course ii4/2 is then just the result of holding a pedal while the treble works through the motion that - despite the endless variety of figuration - can be viewed as a descent from the tonic by thirds.
Comment: See example 2.2, he really does specify it with the Roman numerals I mentioned. Otherwise I like your explanation, which seems to hint that it's basically just a harmonic elaboration of a pedal point. Mortensen does mention the Quiescenza schema as another popular opening.
Comment: @KimFierens, Yes, I missed it! I tried re-wording my answer accordingly.


Introduction to Markov process: How to prove that a process is Markov? Part 1

Question: In paper: A Framework for Investigating the Performance of
Chaotic-Map Truly Random Number Generators under Section II it is mentioned that the sequence $\{x_n\}$ generated from the output of a chaotic discrete map is a Markov process.
The reference is also provided which is a book. I have skimmed through the book and resources available in internet but could not find how to show or prove that the sequence is a Markov Process. In essence, do I need to show the Markov property of memory-less property ? But, I cannot understand how to show analytically. It will be of tremendous help if some directions for the proof and references where it exists are provided.
Any other example will also be helpful.
Comment: Indeed the sequence is a Markov chain, but a very special one since its transition kernel $$K(x,A):=P(x_{n+1}\in A\mid x_n=x,x_{n-1},\ldots,x_0)$$ is such that, for every $x$, $K(x,\ )$ is a Dirac mass (at $M(x)$). Not your typical Markov chain, but a Markov chain yes.
Comment: Thank you for your answer, can you provide links where I can find more information? I am not aware of this proof and how to show what is a Dirac mass and hence the proof.
Comment: "can you provide links where I can find more information?" More information about what? "how to show what is a Dirac mass" One does not "show what is a Dirac mass", either one reads the definition to know what is a Dirac mass or one shows that something is a Dirac mass. For your information, the Dirac mass at $y$ is the unique measure $\mu$ such that $\mu(A)=1$ for every $A$ such that $y\in A$ and $\mu(A)=0$ for every $A$ such that $y\notin A$.
Comment: How to show that K(x) is a dirac mass? Is it needed to show this in order to prove that the sequence output from the chaotic map is a Markov chain? Can you outline the steps to show that the chaotic map generates r.v which forms markov chain?
Comment: "Can you outline the steps to show that the chaotic map generates r.v which forms markov chain?" I already did. Perhaps you are missing the point but *every* deterministic sequence $(x_n)$ such that $x_{n+1}=M(x_n)$ for some function $M$ is a (very degenerate) Markov chain. Proof: Look up the definitions.
Answer: From the article : "The output of the map function from the previous time-step is fed back as the input of the current time-step. That is $x_n=M(x_{n-1})$."
Therefore, the information about $x_n$ is described by its immediate previous state (all the information about past states is irrelevant), making it a Markovian process.
If you don't want to use words :
$P(x_n\in A_n |x_1\in A_1,...x_{n-1}\in A_{n-1}) = P(x_{n-1}\in M^{-1}(A_n))$
Comment: The identity at the end is 1. false in the case at hand, 2. not how one characterizes Markov chains


Annotation error in Java

Question: I have this piece of code in my Java entity class:
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;

@Entity
@Table
@NamedQueries(@NamedQuery(name="Student.getAll", query="SELECT e FROM Student e"));
public class Student implements Serializable{
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column
    private int studentId;
    @Column
    private String firstname;
    @Column
    private String lastname;
    @Column
    private int yearLevel;

    public int getStudentId() {
        return studentId;
    }

And more methods from then on. The error im getting is after the @Entity annotation. It says "class, interface, or enum expected". It's weird because im watching a tutorial and there's no error there. What is wrong with it?
Answer: You aren't importing javax.persistence.NamedQuery and javax.persistence.NamedQueries, and you have an extraneous semicolon at the end of your annotations.
Also, if you only have the one query, you can put @NamedQuery directly on the entity class instead of wrapping it.
Comment: I did it, but the error still persists. I edited the question including the imports.
Comment: @JeanCarlosSuárezMarranzini Just noticed the other error and updated my answer.
Comment: Even removing the `@NamedQueries` there's still the error. But I think the semicolon thing did the trick.

Annotation error in Java


How can I divide a file into sections and put them in a dictionary using robot framework

Question: I have a file that goes like this:
<code>Name: John
Class: II
Age:  8
Interest: Sports

Name: Emma
Class: III
Hobby: Dance
</code>
So I want to read this file and put the contents into a dictionary with Name as key. The sections vary in number of lines. How can I achieve this dictionary using Robot Framework keywords.
Comment: the simplest solution would be to write a keyword in python. Is that an acceptable solution, or do you need to do this all using built-in keywords?
Comment: I need to use only builtin-keywords. But just to be aware, would like to know the python implementation as well.
Comment: there is no simple way to do what you want with built-in keywords. It's likely achievable, but will require a lot of code. you need to read the file, split it into lines, loop over the lines, and create a dictionary.  As written, this question is just too broad. You should  try to solve the problem yourself, and then come back when you have a more specific question.
Answer: Is this what you need?
<code>*** Settings ***
Library    OperatingSystem
Library    String
Library    Collections

*** Test Cases ***
Split File By Names
    ${my_dict}    Create Dictionary
    ${data}    Get File    <path_to_your_data>
    @{lines}    Split To Lines    ${data}
    Remove Values From List    ${lines}    ${EMPTY}
    :FOR    ${line}    IN    @{lines}
    \    ${key}    ${value}    Split String    ${line}    :
    \    ${name}    Set Variable If    '${key}' == 'Name'    ${value.strip()}    ${name}
    \    Run Keyword If    '${key}' == 'Name'    Set To Dictionary    ${my_dict}    ${name}=@{EMPTY}
    \    Run Keyword If    '${key}' <> 'Name'    Append To List    ${my_dict.${name}}    ${line}
    Log    ${my_dict}
</code>
Anyway, the RF way to parse the file sucks. I would rather go for python.
<code>#!/usr/bin/python
# -*- coding: utf-8 -*-

class ParseFile:

    def __init__(self):
        self.my_dict = {}

    def parse_file_to_dict(self):
        with open('<path_to_your_data>') as f:
            lines = f.read().splitlines()
            for line in (l for l in lines if l != ""):
                key, value = line.split(":", 1)
                if key == "Name":
                    name = value
                    self.my_dict[name] = []
                else:
                    self.my_dict[name].append(line)
        return self.my_dict
</code>
... and then just call it in RF.
<code>*** Settings ***
Library    ParseFile.py

*** Test Cases ***
Do It In Python
    ${my_dict}    Parse File To Dict
    Log    ${my_dict}
</code>
Please note that both ways are strictly tight to data structure you provided. I.e. if "Name" is not at the first line of each section, it will not work and will need more handling with the data.
Comment: Little tweak to bring suitable output and this code works exactly well for me. Thanks a ton!

I had a failure in this line so had to lose them and use a Create List before the loop and Append.
 \    Run Keyword If    '${key}' <> 'Name'    Append To List    ${my_dict.${name}}    ${line}
Comment: I'm glad it works. Anyway it would be nice to increase robustness for case of incorrect/incomplete data - and that's the moment when python solution is really worthy because it is much more flexible.


How to package prebuilt shared library inside an APK

Question: This question seems to have been asked a lot but all were trying to use eclipse to package the library inside the APK.
However, my requirement is to package the library inside the APK (which will later be loaded using System.loadLibrary() through Java) using the Android build system, i.e. i want to write an Android.mk file that does this job.
Requirement:
1. Prebuilt shared library: libTest.so
2. Write an Android.mk file that will package this to libs/armeabi-7 inside the apk.
I don't know much about the build system I am using but the compilation is done using "mm" command after exporting the required environment variables.
When I provide libTest for LOCAL_JNI_SHARED_LIBRARIES, it tries to find it inside its exported paths and fails to find it there and hence build fails.
Can anyone please give any pointers on writing an Android.mk file that will package my prebuild shared library into the APK?
Answer: In order to prebuild your native library you have to

Create jni folder in your project folder
Create libs folder in your project folder
Add Adnroid.mk make file to the jni folder, it should looks like
this:
LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_LDLIBS    := -llog
LOCAL_MODULE    := Test
LOCAL_SRC_FILES := Test.cpp

include $(BUILD_SHARED_LIBRARY)

Note 1: Test.cpp is the main library source file containing implementation of native methods. You can add more sources as a space separated list.
Note 2: Do not include headers, they are included automatically.
Note 3: If you need to enable C++ STL, then create another make file - Application.mk, add it to the jni folder and set APP_STL := stlport_static flag in it.
Then you will have to set up a builder. Refer to this article for how to do that:
After these steps, the builder will create your library in the libs folder which will be automatically packed into the apk when building the whole application.
Note: Your library name should be lowercase, it is a Linux convention. The "lib" prefix will be automatically added, so the final library name will be libtest.so.
Answer: Let's say there is one libxxx.so shared library under libs/armeabi/ of project which you want to pack into apk. There are 2 things you need to do in the Android.mk as below:

# 1. Copy .so to out/target/product/***/obj/lib
$(shell cp $(wildcard $(LOCAL_PATH)/libs/armeabi/*.so $(TARGET_OUT_INTERMEDIATE_LIBRARIES))

# 2. Make libxxx to be packed into apk
LOCAL_JNI_SHARED_LIBRARIES := libs/libxxxx

Then you can use apktool to unpack the built apk, you will find the libxxx.so will be located in libs/armeabi*/. It is indeed packed into the apk.
Answer: I had two LOCAL_JNI_SHARED_LIBRARIES that I wanted to build into my APK. I manage to do it by setting the following in my Android.mk:
LOCAL_MODULE_TAGS := samples

After re-compiling the module I was able to find both libraries inside the .apk under /lib/.


Operação em PHP. Multiplicação usando porcentagem

Question: <?php echo $i['sellingStatus'][0]['currentPrice'][0]['__value__']; ?>

Como posso multifiplcar '__value__' por 2 e depois somar 60% ao valor total?
Exemplo:
Valor = 10
Multiplica por 2 = 20
Acrescenta 60% = 20 * 60% = 12
Total = 20 + 12 = 32.

Answer: Versão "curta":
<?php echo $i['sellingStatus'][0]['currentPrice'][0]['__value__'] * 3.2 ;>

Explicação:
Calcular acréscimo de 60% é a mesma coisa que multiplicar por 1.6.
Afinal 100% = 1, portanto 60% = 0.6.
Como queremos acréscimo, queremos 100% + 60%, ou seja multiplicando por (1 + 0.6) => (1.6)
Se você quer multiplicar por 2 e depois acrescentar os 60%, seria equivalente a
valor * 2 * 1.6

Simplificando
valor * 3.2

Versão "longa":
Se quiser usar a fórmula em vários ítens com porcentagens diferentes, aí a coisa muda.
Poderia usar uma função para isso:
$indice = 2; // Acrescentado com base no comment, que vai ser o índice do dólar.
echo acrescimo( $i['sellingStatus'][0]['currentPrice'][0]['__value__'] * $indice, 60 );

function acrescimo( $valor, $porcentagem) {
   return $valor * ( 1 + $porcentagem/100 );
}

Comment: A versão curta acho que funcionou melhor, pois ainda sou um pouco leigo em PHP. O desafio agora é: o valor citado como '2' na verdade será o quanto o real está valendo a cada 1 dollar.
Comment: @GustavoCave editei a resposta pra acrescentar o `$indice`.
Comment: fiz um script para determinar o valor que será multiplicado por 60% (ou 1.6). Este valor vem através da variável $valor. No caso  como devo fazer para o '__value__' multiplicar pelo valor determinado pela variável $valor e depois acrescentar 60% ?
Comment: @GustavoCave é o que está na versão longa, só que eu chamei de $indice. na versão curta seria ...'value'] * $valor * 1.6 (ou seja, primeiro multiplica pelo seu $valor, depois poe os 60% em cima do resultado)
Comment: Ótima explicação +1.
Answer: Tenta assim, seguindo a formula para descobrir a porcentagem é: (numero1/100) * a porcentagem que você quer descobrir
    valor = 10;
    multiplicado = 10*2;
    porcentagem = (multiplicado/100)*60;
    total = multiplicado+porcentagem;

Answer: Vou apenas complementar as respostas, anteriores, pois ambas estão certíssimas:
<?php
function acrescenta($valor, $percentual){
    return($valor * ( 1 + ($percentual / 100)));
}
?>

Você usa assim (supondo que o valor original seja 50):
<?php
$total = $total * 2;
$total = acrescenta(50, 60);
?>


Trying to keep the last li item of navbar to rightmost corner. Float :right wont work as expected. How can I fix this?

Question: This is my code(something like this). Trying to keep last li at right corner. But float wont work as expected. Help appreciated.

                      test

                      test

Answer: There are several ways to go about it, but it will also depend on whether you have:

Multiple
s
Single
 with only 2 dropdowns
Single
 with multiple dropdowns

Multiple
s
If you can change its layout, you can break up the dropdowns into 2 .navbar-nav, and set justify-content as space-between on .navbar-collapse so that the right .navbar-nav will be pushed to the right, since .navbar-collapse has already been displayed as flex-box:

    Navbar
    <button />

demo: https://jsfiddle.net/davidliang2008/62sf4kvr/19/
Documentation for Bootstrap flex-box built-in classes: https://getbootstrap.com/docs/4.5/utilities/flex/

Single
 with only 2 dropdowns
If you can't change the layout and have to go with a single
 approach, and you only have 2 dropdowns, you can apply the same concept on .navbar-nav instead of .navbar-collapse: to set justify-content: between;. The only additional thing you would need to do is to set the width of .navbar-nav to 100%.

    Navbar
    <button />

demo: https://jsfiddle.net/davidliang2008/62sf4kvr/23/

Single
 with multiple dropdowns
If you have multiple dropdowns but only want to put the last one to the right, while the rest will align to the left, the above approaches won't work because they use justify-content: between; for the effects.
In order to do that with multiple dropdowns, you can set the margin left of the last dropdown to auto, which will push itself to the furthest to the right:

    Navbar
    <button />

demo: https://jsfiddle.net/davidliang2008/62sf4kvr/26/
Comment: I am generating this list through backend so i have to do it without splitting in two ul. Is there a way we can do it in single ul ?
Comment: @testguest: please see my updates. I hope those includes all the cases you have and answer your question.
Comment: Thank you soo much. Was really struggling with this one . Really appreciate your help.


How do I use drupal_mail() without the $to value?

Question: I'm trying to send same email to several users at once. They should not see each other's email addresses, so I add them as Bcc in the header.
However, the problem is that Drupal seems to require the $to parameter passed to drupal_mail() function. I tried passing both NULL and an empty string but without success. System would return the Unable to send e-mail. message.
I don't want to use some random email address instead and I want to avoid new modules.
How can I send an email just with BCC recipients?
Comment: You can't - emails require at least one recipient, that's not a Drupal thing. Just send it to `variable_get('site_mail')`, that's the most oft-used solution I've seen
Comment: Could also loop through your list of addresses and send them one by one.
Comment: @Ivanhoe123 I know. Kinda. I know that only way to really know is to test. It depends on your server's performance. And performance of it's network. And exact configuration. And the fact if you are using mailserver or sending directly. If via mailserver, then it depends on it's performance too. If directly, performance of recipient's servers may be (or not) a problem. Too many factors to really know. But with good use of batch api you should be reasonably safe.
Comment: Thanks for quick response Clive. I guess I'll have to send them through as queue batch and see how other modules solved this problem. Please add your comment as a separate answer so I can accept it.
Comment: The way I did it was: ask admins to configure "resend" address on the mail server. Update recipient list daily via XML. Yes, hard part was on their side. Then I was just sending mail to that address and mailserver was re-sending it where needed. So it's like @Beebee solution, only with "loop" moved elsewhere ;)
Comment: @Mołot thanks for the comment; in this particular case the recipients are determined dynamically (values are from the DB) so it's not possible to update the list manually.
Comment: @Beebee do you know if this would work without issues if I'm trying to send ~50 emails at once?
Comment: Thanks again. I believe the server side won't be a problem; it's a dedicated server without any limits for sending emails. I guess I'll have to experiment with Queue API now, as this is happening in the background.
Answer: You do this by putting the string 'undisclosed-recipients:;' (notice the colon and semicolon at the end) is the $to parameter you pass to the drupal_mail function. E.g.:
drupal_mail('mymodule', 'send', 'undisclosed-recipients:;', $language, $params);

You can now add the list of bcc-recipients to the header.
Comment: This is the accepted way of leaving the recipient empty. It is used in examples in RFC 2822.
Comment: Didn't know for this approach, thanks a lot! Do you know if it will generate some error logs in the background or this is an accepted way of leaving recipient empty?
Comment: Thanks again for lightning fast response :) I will check this  and post back/mark the question as the answer.
Comment: Thanks once again, and sorry it took me so long - I simply forgot about it. This worked perfectly.


Ignoring XSD Sequence Order on Serialization in .NET

Question: I am consuming a 3rd-party web service (of which, I have no control over) in .NET.
I noticed some of my properties were not being set when the response was returning and being serialized from the service.
I have noticed something strange with their response though.
This is a sample of their WSDL
<xs:complexType name="letters">
    <xs:complexContent>
        <xs:extension base="tns:response">
            <xs:sequence>
                <xs:element name="a" type="xs:long" />
                <xs:element minOccurs="0" name="b" type="xs:dateTime" />
                <xs:element maxOccurs="unbounded" minOccurs="0" name="c" nillable="true" type="tns:anotherComplexType" />
                <xs:element minOccurs="0" name="d" type="xs:dateTime" />
                <xs:element minOccurs="0" name="e" type="tns:string" />
                <xs:element minOccurs="0" name="f" type="tns:boolean" />
            </xs:sequence>
        </xs:extension>
    </xs:complexContent>
</xs:complexType>

And this is a sample of the relevant part of the response:
<letters>
    0
    2015-02-03T11:59:18+11:00
    <d>2015-02-03T12:00:00+11:00</d>
    <f>true</f>
</letters>

I suspect that because they are defining a <xs:sequence> for the elements in the <letters> part, that the .NET Serializer is expecting the response to have ALL elements present in the response? (And thus, their response breaks their WSDL definition?).
Thanks
EDIT
It appears that the response is returning an unknown element, specifically
<letters>
    0
    2015-02-03T11:59:18+11:00
    <d>2015-02-03T12:00:00+11:00</d>
    <otherElement>blue</otherElement>
    <f>true</f>
</letters>

Which is not part of the WSDL. This means that the <f> element is not being serialized. Is there a way for me to disregard unknown elements?
Answer: No, xsd:sequence merely means that the elements must be in order.  It is the @minOccurs attribute on each xs:element that indicates requiredness.  When @minOccurs = 0, the element is optional.  (Note that the default values for @minOccurs and @maxOccurs is 1, indicated "required".)  Since many of the elements in that sequence are @minOccurs = 0, all elements do not have to be present in your response.
Comment: Thanks, that is correct in the context of my original question, but it appears they are returning an unknown element as part of their response. Is there anyway to disregard this?
Comment: If they're returning a response that includes elements that are not allowed per the WSDL response XSD, then they are in violation of the interface contract.  Tell them to fix their code or fix their XSD.


How to get better sound through multi-effects processors

Question: I wondering if sound quality is meant to reduce through multiple multieffects processors.
I have a Boss GT10 as well as a Boss RC300 loop pedal running through some decent little 25 to 30 W bedroom amps. My electrics and acoustics all sound worse through it all, I'm not very experienced with the set up because I hate setting up and unpacking especially when I can get much better clean sounds by themselves.
My Cole Clark FL1A acoustic sounds big and beautiful itself, when I plug it in to my amp, it looses some bassy-ness and depth (but it has sounded much better through big keyboard amps), when I plug in my GT10, it sounds a bit worse, like it's going through a filter or something, adding the loop pedal to the mix adds the same dampening effects.
Do you think the root cause could be poor amps, or poor adjustments of sound and tone through the pedals themselves, or combinations? I was just thinking of trying a bigger better amp but I'm hesitant with my money these days and it would suck if it didn't help
Answer: You are probably using the wrong equipment to get a good amplified sound from your acoustic guitar.
1) You can't get a good sound by running an acoustic guitar through an amp designed for an electric guitar. Amps designed for electric guitar are designed to color the sound and add distortion (by very subtle amounts or in the extreme) and they do not reproduce the full frequency response of the acoustic sound of the instrument.
On the other hand, there are special amps designed for amplifying acoustic guitar; for example, the Fishman Loudbox series. They are designed to "purely" amplify the sound without imparting any artificial coloring, distortion, compression, etc. If you are serious about getting a good sound from your acoustic guitar, you should invest in a dedicated acoustic guitar amplifier. They can be quite expensive, because they produce much higher audio fidelity than your average electric guitar amplifier.
2) Performers who want to amplify an acoustic guitar for stage use, if they do not purchase a dedicated acoustic guitar amplifier, always use a dedicated external acoustic guitar preamplifier which is used in conjunction with a direct box, so that the guitar's signal can be sent not to a stage amplifier but directly to the hall's mixing console, thence to go straight to the hall's stereo speakers/PA system.
3) Most, but not all, guitar multi-effects units have effects and reverbs and compressors, etc. which are designed to bring out the best sound in an electric guitar, not an acoustic guitar. Your Boss GT10 is not advertised as being useful for acoustic guitar. You can create some interesting experimental sound effects by running an acoustic guitar signal into such a multi-effect unit, but you won't get a good, natural-sounding acoustic guitar sound from one of these. They are simply not designed for that.
Go to a music store and take your acoustic guitar with you. Ask to play your guitar through various acoustic guitar preamplifiers or multi-effects units specifically designed for acoustic guitar (there are a few on the market). Let your ears guide you.
Comment: A lot of acoustic guitars have built in preamplifier, so just need a DI box.   (I don't understand way the are not designed output a balanced signal directly apart from guitar makers not talking to PA operators.)
Answer: I'd advocate reading the instructions !!  Yes, it's tedious, but you'll find out how to tell the effects what sort of amps you're putting them through, which way you want to route the signals, which order you would like the effects to be affected by the pedals, and other important stuff.
As they're sophisticated these days, in comparison to a little single pedal of 30 yrs ago, they have so many parameters that just plugging in and hoping doesn't work.
Tedious, boring, maybe, but if all else fails, read the instructions !! There must be thousands of people who have machines, etc., in cupboards and drawers, almost brand new, put away 'cos I can't make it work properly'. I was that man, till I saw the light, and used it to illuminate the instructions.
I use a Boss looper, and experience no quality loss, but was careful how I configured the signal route.
Answer: First of all, an acoustic guitar can sound odd through an amplifier that is designed for electric guitars. So that might be your first problem.
For your electric guitars, make sure that your effect chain is set up correctly. There are plenty of tutorials on Google and on Youtube on how to do that. However, if all effects are turned off and your electric guitars sound terrible, then there is something wrong. Perhaps your cables are of low quality (between the 2 effects). It might also be the case that your pedals are not true bypass.
Comment: Use of effects in the right sequence is very important. I've tried an acoustic through an electric guitar am, and they sound very flat.


PG::UndefinedFunction: ERROR: operator does not exist: character varying @> point

Question: I have a Rails app and am running this query:
partner_found = Partner.find_by("partners.geo_polygon @> point '(:lat,:lng)'", lat: latitude, lng: longitude)
In my dev environment this runs fine, but in test it throws an error:
PG::UndefinedFunction: ERROR:  operator does not exist: character varying @> point
Both my dev and test environments are running Postgres databases. What am I missing?
edit: More info, my test database created the geo_polygon columns as character varying while it is correctly polygon in the development database.
Comment: I guess you are missing postgres hstore in test database.
Answer: Thanks Rahul! The test database was missing hstore. I turned it on is psql with CREATE EXTENSION IF NOT EXISTS hstore;
I also added to my migration: enable_extension "hstore"
Also I found these answers at http://nandovieira.com/using-postgresql-and-hstore-with-rails


Check conditions into if check

Question: I use this code to calculate the padding of a button on a page from the browser border.
        Dimension dm = new Dimension(1024,768);
        //Setting the current window to that dimension
        driver.manage().window().setSize(dm);

        // Click Login button to submit login form
        WebDriverWait loginButtonWebDriverWait = new WebDriverWait(driver, 4000);

        WebElement loginButtonWebElement = loginButtonWebDriverWait.until(ExpectedConditions.presenceOfElementLocated(By.id("login")));

        int loginButtonX = loginButtonWebElement.getLocation().getX();
        int loginButtonY = loginButtonWebElement.getLocation().getY();
        int loginButtonWidth = loginButtonWebElement.getRect().getWidth();
        int loginButtonHeight = loginButtonWebElement.getRect().getHeight();
        System.out.println("Login Button is " + loginButtonX + " pixels from left border.");
        System.out.println("Login Button is " + (screenWidth - loginButtonX + loginButtonWidth) + " pixels from right border.");
        System.out.println("Login Button is " + loginButtonY + " pixels from top border.");
        System.out.println("Login Button is " + (screenHeight - loginButtonY + loginButtonHeight) + " pixels from bottom border.");

        // We need to check that the size is not less than 10 pixels. If the space is less trow exception and fail the test.
        assertThat(loginButtonX).isGreaterThan(5);
        assertThat(loginButtonY).isGreaterThan(5);

I need to implement some check like this:
(window_width - loginButtonWidth) < loginButtonX < window_width

and
0 < `loginButtonY` < loginButtonHeight.

Do you know how I can implement properly check like this:
if((screenWidth - loginButtonWidth) < loginButtonX < screenWidth){

}

Now I get error: Operator '<' cannot be applied to 'boolean', 'int'. How I can solve this issue?
Answer: (screenWidth - loginButtonWidth) < loginButtonX returns true or false based on whether the condition is true. So in your case, the statement (window_width - loginButtonWidth) < loginButtonX < window_width would be equal to:
if(true/false < number)

Which gives you the error: Operator '<' cannot be applied to 'boolean', 'int', since you cannot check whether a boolean is bigger or smaller than a number.
You should be doing the following:
int subtracted = screenWidth - loginButtonWidth;
if(subtracted < loginButtonX && subtracted < screenWidth){

}

Check conditions into if check


How to get the name from a nixpkgs derivation in a nix expression to be used by nix-shell?

Question: I'm writing a .nix expression to be used primarily by nix-shell. I'm not sure how to do that. Note this is not on NixOS, but I don't think that is very relevant.
The particular example I'm looking at is that I want to get this version-dependent name that looks like:
  idea-ultimate = buildIdea rec {
    name = "idea-ultimate-${version}";
    version = "2017.2.2"; /* updated by script */
    description = "Integrated Development Environment (IDE) by Jetbrains, requires paid license";
    license = stdenv.lib.licenses.unfree;
    src = fetchurl {
      url = "https://download.jetbrains.com/idea/ideaIU-${version}-no-jdk.tar.gz";
      sha256 = "b8eb9d612800cc896eb6b6fbefbf9f49d92d2350ae1c3c4598e5e12bf93be401"; /* updated by script */
    };
    wmClass = "jetbrains-idea";
    update-channel = "IDEA_Release";
  };

My nix expression is the following:
let
  pkgs = import <nixpkgs> {};
  stdenv = pkgs.stdenv;
  # idea_name = assert pkgs.jetbrains.idea-ultimate.name != ""; pkgs.jetbrains.idea-ultimate.name;
in rec {
  scalaEnv = stdenv.mkDerivation rec {
    name = "scala-env";
    builder = "./scala-build.sh";
    shellHook = ''
    alias cls=clear
    '';
    CLANG_PATH = pkgs.clang + "/bin/clang";
    CLANGPP_PATH = pkgs.clang + "/bin/clang++";
    # A bug in the nixpkgs openjdk (#29151) makes us resort to Zulu OpenJDK for IDEA:
    # IDEA_JDK = pkgs.openjdk + "/lib/openjdk";
    # PATH = "${pkgs.jetbrains.idea-ultimate}/${idea_name}/bin:$PATH";
    IDEA_JDK = /usr/lib/jvm/zulu-8-amd64;
    # IDEA_JDK = /opt/zulu220.127.116.11-jdk8.0.144-linux_x64;
    # IDEA_JDK = /usr/lib/jvm/java-8-openjdk-amd64;
    buildInputs = with pkgs; [
      ammonite
      boehmgc
      clang
      emacs
      jetbrains.idea-ultimate
      less
      libunwind
      openjdk
      re2
      sbt
      stdenv
      unzip
      zlib
    ];
  };
}

I have commented out setting PATH as it depends on getting idea_name in the let-clause. As an interesting side note, as is, this does not fail if I leave it uncommented but causes a very bizarre error when executing nix-shell about not being able to execute bash. I've also tried the more simple case of let idea_name = pkgs.jetbrains.idea-ultimate.name; but this fails later on when idea_name is used in setting PATH since idea_name ends up being undefined.
Update:
I began exploring with nix-instantiate, but the derivation of interest seems empty:
[nix-shell:/nix/store]$ nix-instantiate --eval --xml -E "((import <nixpkgs> {}).callPackage ./3hk87pqgl2qdqmskxbhy23cyr24q8g6s-nixpkgs-18.03pre114739.d0d905668c/nixpkgs/pkgs/applications/editors/jetbrains { }).idea-ultimate";

<?xml version='1.0' encoding='utf-8'?>
<expr>
  <derivation>
    <repeated />
  </derivation>
</expr>

Comment: I've also tried using something like `nix-shell --verbose --verbose  --verbose --verbose --verbose --verbose --show-trace ` to understand why an assertion fails, but despite the vast quantities of information printed, that information doesn't include the assertion values.
Answer: If your intent is to get idea-ultimate into nix-shell environment, then just include that package to buildInputs. I see it's already included, so it should already be present in your PATH.
BTW, you can extend your shellHook and export PATH and other variables rather from there, where you have full bash. Why would you do it from bash? Less copying. When you specify
IDEA_JDK = /usr/lib/jvm/zulu-8-amd64;

in Nix, the file /usr/lib/jvm/zulu-8-amd64 get's copied to nix store and IDEA_JDK is set to point to file in /nix/store. Was that your intent?
Regarding nix-instantiate:
$ nix-instantiate --eval -E 'with import <nixpkgs>{}; idea.pycharm-community.outPath'
"/nix/store/71jk0spr30rm4wsihjwbb1hcwwvzqr4k-pycharm-community-2017.1"

but you still have to remove doublequotes (https://gist.github.com/danbst/a9fc068ff26e31d88de9709965daa2bd)
Also, nitpick, assert pkgs.jetbrains.idea-ultimate.name != ""; can be dropped as it's impossible to have empty derivation name in Nix.
And another nitpick. You'll soon find very incovenient to launch IDE from shell every time. It seems a good idea to specify, that some package is used for development, but nix-shell doesn't work well for non-cli applications. Not to mention occasional problems with Nix GC and nix-shell. You'd better install IDE globally or per-user, it is better long-term solution.

[ADDENDUM]
You are looking for this (dev-environment.nix):
with import <nixpkgs> { };

buildEnv {
  name = "my-super-dev-env";
  paths = [
      #emacs
      nano
      idea.pycharm-community
  ];
  buildInputs = [ makeWrapper ];
  postBuild = ''
    for f in $(ls -d $out/bin/*); do
      wrapProgram $f \
        --set IDEA_JDK "/path/to/zulu-jdk" \
        --set CLANG_PATH ... \
        --set CLANCPP_PATH ...
    done
  '';
}

which you install using nix-env -if ./dev-environment.nix. It will wrap your programs with those env vars, without polluting your workspace (you can pollute it further using nix-shell with shell hook, if you want).
Comment: Thanks for all the suggestions! Is it possible to use a nix expression to specify the user environment? By the way, I wanted to get the idea path in order to run `idea.sh` directly as part of a workaround of using a different JDK than the one in nix.
Comment: @bbarker it's a tricky question, because, while it is possible in Nix, it has drawbacks. I'll add required steps to my answer then
Comment: Thanks! I am using this from a container, so In a way I view the whole thing as a transient environment.


Simple question. How do you solve and factorize this using a CAS tool?

Question: Simple question for you awesome guys :)
I've got the formular for a polynomial:
7x^4-56x^3+224x^2-56x+231=0

The thing i need to do is to solve and factorize the above equation.
How can I do this?
Comment: Are you looking for a real solution? (There are no real solutions.)
Comment: In this case, i guess it's a complex solution :)
Comment: Maxima didn't factor it for me...
Comment: My answer is also only based on the help page, I haven't tested whether it works with the given polynomial.
Comment: http://www.wolframalpha.com/input/?i=7x%5E4-56x%5E3%2B224x%5E2-56x%2B231%3D0&dataset=
Comment: Not that it matters, but you might as well use $x^4-8x^3+32x^2-8x+33 = 0$.
Answer: Besides to another answer, you can use the fsolve command. Firstly define your polynomial as

p:=7x^4-56x^3+224x^2-56x+231;

in Maple environment and then enter the following command as I pointed:

fsolve(p=0);

As you see below, I check of probable solutions by making a plot. It tells us that p=0 has no real solutions.
Answer: The factor command will help you. For example
factor(x^3+5,complex)

Will factor your polynomial in the complex plane. See the maple help here.
Comment: I hope I don't get into any trouble if I admit that this was a logo from some Mozilla side regarding thunderbird. If so, I will of course change it, though I never thought about it. Just liked the guy on the picture.
Comment: I like your avatar.
Comment: It is soooo funny to me. $\ddot\smile$


MySql how to generate a complete calendar from an interval?

Question: i'm new to mysql procedures. I ask your help for generate an calendar with some kind of procedure (generate a row for every day in an interval)... on stackoverflow i found this function:
CREATE PROCEDURE filldates(dateStart DATE, dateEnd DATE)
    BEGIN

          WHILE dateStart <= dateEnd DO
            INSERT INTO mytable (mydate) VALUES (dateStart);
            SET dateStart = date_add(dateStart, INTERVAL 1 DAY);
          END WHILE;
        END;

    CALL filldates('2014-01-01','2014-12-31');

But gives me an error near INSERT INTO mytable (mydate) VALUES (dateStart); I use MySql 5.5.35-33 and i will run the query on PhpMyAdmin. I tried the query alone but it work as it should.
An php solution it's ok too... also some kind of generator of .sql file to import etc thanks :D
The result must be something like that table:
  ID | Date       | Price | ..
______________________________
   0 | 2014-01-01 |   40  | ..
   1 | 2014-01-02 |   40  | ..
   2 | 2014-01-03 |   40  | ..
 ... |    ...     |  ...  |
 365 | 2014-12-31 |   40  | ..

If you know how to generate this kind of table i will be very grateful.
Others mysql infos
innodb_version : 5.5.35-rel33.0
protocol_version : 10
slave_type_conversions
version : 5.5.35-33.0-log
version_comment: Percona Server (GPL), Release rel33.0, Revision 61...
version_compile_machine : x86_64
version_compile_os : Linux

Answer: Assuming your table has got at least this CREATE TABLE statement:
CREATE mytable(
  ID INT,
  date DATE,
  Price INT
);

Then you could insert rows for every day of the year with following statement:
INSERT INTO mytable (ID, date, Price)
SELECT
    t.n,
    DATE_ADD('2014-01-01', INTERVAL t.n DAY),
    40
FROM (
    SELECT
        a.N + b.N * 10 + c.N * 100 AS n
    FROM
        (SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) a
       ,(SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) b
       ,(SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4) c
    ORDER BY n
) t
WHERE
    t.n <= TIMESTAMPDIFF(DAY, '2014-01-01', '2014-12-31');

Demo
Explanation
The subselect creates a temporary table with a row for every day between start ('2014-01-01') and end ('2014-12-31'). So MySQL has only to do one single INSERT and this is much faster than a row by row insert.
If you only want the dates, omit the columns ID and Price that I took from your example:
INSERT INTO mytable (date)
SELECT
    DATE_ADD('2014-01-01', INTERVAL t.n DAY)
FROM (
    SELECT
        a.N + b.N * 10 + c.N * 100 AS n
    FROM
        (SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) a
       ,(SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) b
       ,(SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7) c
    ORDER BY n
) t
WHERE
    t.n <= TIMESTAMPDIFF(DAY, '2014-01-01', '2014-12-31');

Comment: My bad, I've left a comma by removing the not needed columns, same mistake as first try. Corrected now. Time to go to bed!
Comment: THANKS YOU MEN :D Worked like a charm!
Comment: Hi thanks for your help...i pasted your code in SQL 'Tab' on PhpMyAdmin but as result i get this error: #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DATE_ADD('2014-07-01', INTERVAL t.n DAY),
Comment: I missed a comma in the first line of the select, fixed now. Had another typo too, added fiddle.
Comment: Ok seems to work but i have an conflict with this #1136 - 'Column count doesn't match value count at row 1' , can you do somthing to generate only the date column values, please? In future i would like to take the same ids . Thanks in advice :D
Comment: Your column list in the `INSERT` statement must match the column count in the `SELECT` statement. Added date-only solution.
Comment: I tried to re-run the query but i have this error "#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM (
    SELECT
        a.N + b.N * 10 + c.N * 100 AS n
    FROM
        ' at line 4 " I never used temporary tables before so sorry for my "dumbness". Actually i dont have time to study it well so sorry for bothering. I promise that i will learn more as soon as possible :)
Comment: Before you go to sleep (in Italy it's almost midnight), one last thing: how do I create a table type for 2 years? When I do the query even on SQL-fiddle it stops to 499 records ...
Comment: You've got to expand the third row of the UNION. I ended it with 4, so the greatest number will 499. You need at least a 7. Same timezone here in Germany.
Comment: @VMai Demo link's dead/empty.
Comment: @Fred-ii- It seems sqlfiddle has got currently a problem. IE presents me an error message if I try to create a fiddle.
Comment: @VMai Ah, ok. I guess it stands at coming back when they've "shoo'd" the bugs out of the system lol - Thanks for the update, *cheers*
Comment: @Fred-ii- It shows us why answers that rely on external sources only are low quality answers. Added minimal `CREATE TABLE` statement for copy and paste if one's got his own MySQL server.
Comment: @VMai That was a good idea. I did +1 originally, great answer! Somebody posted a question a little while ago asking about calendar creation and thought of your answer. Whether they'll use it or not, is up to them. I did save that fiddle in a file though when the demo was up, but that's not really a requirement anyway. But you're right about not having to rely on external sources. *Cheers!*


What would cause a lack of access to wi.gov domains?

Question: Problem
I work in a technical capacity at my job and we recently noticed that we can no longer access wi.gov domains from our network.
One of our clients working for the state of WI (inside a wi.gov domain) also contacted me to inform me that he can no longer reach our website either. My emails via Exchange are also bouncing back as "Delivery Delayed" and then "Delivery Failed". The client's emails are reaching us successfully.
It also seems that wi.us domains are blocked too. Other state .state.gov sites work fine. So do federal .gov sites (atf.gov, etc.)
Troubleshooting Attempts
In doing some basic troubleshooting we have tried the following:

Rebooted modem, router, and firewall and checked for any rules that
might be filtering URLs.
Contacted our ISP to see if they knew what might
be causing the block
Ran a Traceroute to various wi.us and wi.gov
sites with the following results regardless of .wi address

Summary (TLDR)
We can't access wi.gov, wi.us, etc. domains and they can't access us. Our emails are blocked when going to wi.gov email addresses, but they can still email us. We tried a few things and found nothing on our end that we can do, but we did find that a traceroute shows a time out occurring when it hits the UW Wisconsin - Madison (WiscNet) hop.
It seems as if we have been "blacklisted" by the state.
Does anyone know what might be occurring here and how to fix it? How to prevent it from happening in the future?
Thanks in advance for any information you can provide.
Comment: I can get beyond that in a traceroute. I'd probably pick up the phone and call WiscNet.
Comment: It certainly sounds like a problem out there in cloud-land between you and `wi.gov`, but beyond picking up the phone, there's not much you could do.  You could hit up availability testing sites to check on yourself and the `wi.gov` sites you're having trouble with to check how widespread the problem is... but ultimately, that's not going fix it.  For whatever it's worth, I can reach the site for Wisconsin's DOT.
Comment: Thanks guys, I have already contacted WISCNET and they have already told me "not my problem". They did give me a contact email for someone who maybe can help, but they said this is a common problem they get calls about. They can't do anything because they don't administer the firewalls blocking the connection.
Answer: I contacted WiscNet and got this sorted out. We support some government health facilities with our software and they apparently didn't like some of the traffic we were sending to our clients for licensing checks, etc.
They directed me to someone else who was able to assist.
Answer: Had the same issue this week.  Just got it solved.  In order to do this, you need to contact the Wisconsin Department of Administration.  Their help desk # is:
608-264-9383


Name of fifth organ manual

Question: In the manual-naming system that uses Choir, Great, Swell, and Solo, for the first four manuals (bottom to top) of an organ with four or more manuals, what is the usual name for the fifth manual on a five manual or more organ.  Google gives so many answers that it confuses more than helps, and Wikipedia seems unsure.  To make sure I'm making myself clear, let me ask the same question a slightly different way.
What indication would an American or British organist expect to see as the name in an organ score for a fifth manual, when such is to be used?
Answer: Organs with 5+ manuals are very rare, very expensive and virtually always unique creations planned from scratch. People and institutions who build or commission one usually want to get something unique and disringuished.
So for several reasons, there is no such standard: the set of relevant examples is too small and the people who could establish one aren't exactly keen on being conformist as opposed to original. The result of your searches just confirms this.
Comment: Indeed. St Paul's Cathedral London uses the fifth manual for the Dome Organ. [Specification, PDF](https://www.stpauls.co.uk/documents/Music/St%20Paul's%20Cathedral%20Organ%20Specification.pdf)
Answer: For the very few organs of that size, usually the number of manual divisions of the instrument is bigger than the number of manual keyboards, and most if not all of the divisions can be assigned to any keyboard. So the "traditional" concept of naming each keyboard according to which group of pipes it controls doesn't really mean anything.
Also, even in a list of the 20 largest pipe organs ever built that are still fully operational, several only have 4 manuals.
But with those caveats, "echo" would be as good a name as any. On a large 4-manual instrument, the fourth manual may provide both "solo" and "echo" stops - i.e. two separate divisions on one keyboard, since there would be no practical purpose in using the loudest and softest stops of the instrument at the same time.
If a piece was written that absolutely requires an instrument of that size (and such pieces are very rare), most likely it would have been written for one specific instrument (since no two are alike!) and in that case, the most sensible naming system would be whatever the organ builder had used.
Answer: Of those organs I have seen up close, the fifth manual is often assigned for orchestral and antiphonal stops.
I agree that the larger organs are often custom built, and therefore vary in purpose between manufacturers and builders.  I am familiar with two such organs, both located in Salt Lake City, Utah.  The famous Tabernacle Organ (which I have played once), and the newer organ built for their Conference Center.  Both have FIVE manuals.
LDS Tabernacle Organ :  Choir (I), Great (II), Swell (III), Solo/Bombarde (IV), Antiphonal (V)
LDS Conference Center Organ : Choir (I), Great (II), Swell (III), Solo (IV), Orchestral (V)
One of purposes of building an organ with multiple manuals is to provide the organist greater flexibility in the variety and richness of sounds, and to be able to quickly switch between stop combinations.  Couplers are provided that combine the manuals and ranks together, as well as mixing various instruments, percussion, and other sounds.
So the naming of the manuals often identifies the general ranks they are associated with.
Comment: If a single organization has commissioned two similar-sized organs in the same geographical location, there are obvious practical reasons for building the second one with a similar disposition to the first (e.g. one assumes their "staff" organist(s) will regularly play both instruments). I would be cautious of drawing a general conclusion from that specific example.
Comment: Michael, I really appreciate the LDS organ details.  I was not even aware that the Conference Center organ HAD five manuals!  (Having never seen or heard it.)  Thanks. --L3B
Answer: The only one I have ever seen called it an Echo.  It had not occurred to me that this was not the standard term.
Answer: Depends on both the "regional flavor" and to some extent the whim of the designers. The large 19th century Cavaille-Coll instrument in Saint Sulpice Paris has 5 keyboards, and these are used in a somewhat unusual way, but quite logical given the time and the region. Most C-C organs separated each division into "foundations" (Fonds -- flutes, diapasons, strings, and soft reeds) and "loudations" (Anches -- loud reeds, mixtures, mutations, etc.) and these were on separate chests with separate wind supplies. There would be a foot lever that could turn on or off the wind -- called a "ventil" -- in the Anches chest. This would allow a loud-adjunct combination to be set up on the Anches chest and brought on by turning on the wind.
The organs from that period did have touch assists (done by pneumatic amplifiers called "Barker Levers") but they didn't have stop combination memories or crescendo pedals, etc. So the ventil levers were useful.
Also, the Barker levers made coupling really useful. The order of manuals in these organs from the bottom is Grand-Orgue (Great), Positive (Choir), Recit (Swell), and they are often played all coupled together -- and this allows going from loud to softer to softer by moving up the manuals, and vice versa.
A fourth manual is usually call "solo" and it is usually the topmost.
"Full Organ" is called "Grand-Choeur" and it is most everything with everything coupled.
Cavaille Coll got the idea for this large organ of its time (100 stops, now 102), to have two keyboards for the Great manual, and at the bottom of the stack: have the "Anches" for the Great be on the bottom manual, and the Fonds for the Great be on the second manual, and have them usually coupled together. This is very handy, and allows rapid easy contrasts. The bottom keyboard is called the Grand-Choeur not just because it is loud, but because it is often the case that all 5 keyboards are coupled together, so that one gets both different colors and loudness on each, but so that one can move down to get full organ.
To make this work, one still needs to control the pedal loudness and timbres, and again a lot is done with both coupling and ventils.
The order from the bottom is Pedal, Grand-Choeur, Grand Orgue, Postive, Recit, Solo.
The other important detail about this large organ is that it uses quite a few ranks of pipes from the previous baroque organ, and these are generally softer. So the build up of sound on the Saint Sulpice instrument is done by using a lot of stops, and the voicing is quite marvelous to allow a very clear sound rather than just mud. One of the most thrilling sounds on any organ is "all the flutes" on all the manuals coupled together and played separately and together.
The current main organist at Saint Sulpice is Daniel Roth, and besides pieces played by him on YouTube, you can also find "Daniel Roth demo" clips of him showing how the instrument is organized.
Answer: I was looking into this exact question, even though 5 manual organs are rare beasts, and almost non-existent as far as I know for European organs before the 19th century. To identify the 5th manual (topmost), it can be helpful to apply a few very general rules:

Choir (from the word 'Chair') is the lowest manual
Swell is the topmost for 2 and 3 manual organs
Great is in the middle of a >2 manual organ, or at least one up from Choir.
Solo is generally the topmost manual in a 4 manual organ
This leaves the topmost manual in a 5 manual organ being either an Echo or Antiphonal.
Echo may be more common than Antiphonal in 5 manual organs

After a bit of research, here's my summary of the manuals - from 2 to 5 manual organs. Big rider though: we know there's variability in the manual designs across different organs, and across English/German/French/Dutch organs etc.
FWIW, here's a quick reference table I made:
(From bottom manual to top, excluding pedal)

2 manual: Great - Swell
3 manual: Great - Swell - Solo OR Choir - Great - Swell
4 manual: Choir - Great - Swell - Solo
5 manual: Choir - Great - Swell - Solo - Echo or Antiphonal

Regarding 3 manual organs, I'm not sure which is the more common variant of the two above: a Solo manual at the 'top', or a Choir at the bottom and no Solo
I'm by no means an expert in organ design, so any corrections gratefully accepted!
Comment: One small update - after doing some organ work lately, I realised the order of my manuals is not quite right (for the Engish organ layout). In the '3 manual' organ, the order from bottom to top should be Choir - Great - Swell. This applies to all 3 and 3+ manual organs, with the main rules being 'Choir' is at the bottom of the console manuals. 'Solo' is unusual in a 3 manual organ (if not 'never happens' - I'm not 100% sure!).
Answer: You've answered your own question.  There is no standard name for a 5th manual, though 'Echo' may be as common as anything else.
You obviously wouldn't write a piece requiring 5 manuals unless you had a particular performance on a particular instrument in mind.  Use the name THAT one uses.

Name of fifth organ manual


How can I add a border to the Drop-down area of a ListBox?

Question: I am using the following code to override and draw each list item within a ListBox.
      if (e.Index < 0) return;
        // if the item state is selected then change the back color
        if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
            e = new DrawItemEventArgs(e.Graphics,
                                      e.Font,
                                      e.Bounds,
                                      e.Index,
                                      e.State ^ DrawItemState.Selected,
                                      e.ForeColor,
                                      Color.Red); // Choose the color

        // Draw the background of the ListBox control for each item.
        e.DrawBackground();
        // Draw the current item text
        e.Graphics.DrawString(studentsListBox.Items[e.Index].ToString(), e.Font, Brushes.Black, e.Bounds, StringFormat.GenericDefault);
        // If the ListBox has focus, draw a focus rectangle around the selected item.
        e.DrawFocusRectangle();

The code is works as I would suspect, however I would also like to add a border to the entire drop-down portion of the list box (see the example image below.)  How can I add the border to the entire list?
Comment: You're asking two questions-- How can you draw a border on the drop-down list and how can you modify the look of each element in your list?  Please update your question to reflect the nature of your question or ask two separate SO questions.  Thank you.
Comment: @RLH i modified my question would you pls help on this one..
Answer: Since the title is referring to the border, I'll focus on that.  I'm assuming you want to change the BorderStyle beyond just the given "None", "FixedSingle" and "Fixed3D"?
The ListBox does not support any kind of BorderColors, etc.
Your best bet is to change change the BorderStyle to "None", IntegralHeight = False, and Dock = Fill, and then place it inside a panel.
For your panel, change BorderStlye = None, Padding (All) = 2, BackColor = Red.
With WinForms, your choices are limited.
Comment: one more question i want to add the data like indicated in figure and title also ....how will i do that would you pls give any idea ....
Comment: @user899271 You are already using DrawString, try changing the font to bold for the header items and change your e.Bounds rectangle to indent it to the right for your subitems.  Instead of a listbox, this looks like a TreeView, maybe try using that control instead.


Compare two columns in sheet1 with two columns in sheet two and display a value from sheet 2

Question: I have a horse show points spreadsheet where horses names and riders need to be matched up with the same pairs from other sheets.  So, column 1 being the horse name, and column 2 being the rider name, I would like to display the point total from another sheet with the same horse/rider pair.
So, sheet1`row1 column 3 would need to find the same horse/rider pair (column a and b) from sheet 2 and display the point total (which is totaled in sheet2 column q of some row wherever that horse/rider pair is listed).
I'm not sure where to start with creating a formula like this.  I did try with vlookup, but that doesn't seem to allow me to make an array of two columns and compare that with another array which I think is what I'm trying to do.
Answer: I think you may find the simplest solution (other than running a macro someone else has written for you of course) is to insert a column at the extreme left of both sheets and put something like =B2&" | "&C2 in Row2 of those columns (assumes your other columns have labels) then copy down and use a formula such as:
=IFERROR(VLOOKUP(A2,'Sheet 2'!A:R,18,FALSE),"")

(also in Row2 and copied down) to look up the points.
Answer: If you want to use VBA, you can insert a new module and copy this code in. Then you can use the function in a cell with =GetPointTotal(HorseCell, RiderCell)
Option Explicit

Function GetPointTotal(horseRange As Range, riderRange As Range)

    Dim cell As Range, searchRange As Range
    Dim displaySheet As Worksheet, pointSheet As Worksheet
    Dim iEndRow As Integer
    Dim horseCol As String, riderCol As String, pointCol As String, points As String
    Dim b As Boolean

    'Configuration
    Set displaySheet = ThisWorkbook.Worksheets("Sheet1")
    Set pointSheet = ThisWorkbook.Worksheets("Sheet2")
    horseCol = "A"
    riderCol = "B"
    pointCol = "Q"
    'EndConfiguration

    iEndRow = pointSheet.Range(horseCol & 1).End(xlDown).Row
    Set searchRange = pointSheet.Range(horseCol & 1 & ":" & horseCol & iEndRow)

    b = False
    For Each cell In searchRange
        If b = True Then Exit For
        If cell.Value2 = horseRange.Value2 Then
            If cell.Offset(0, 1).Value2 = riderRange.Value2 Then
                points = pointSheet.Range(pointCol & cell.Row).Value2
                b = True
            End If
        End If
    Next cell

    GetPointTotal = points

End Function

Comment: @pnuts It can be whatever column he wants, that's why it's under the `Configuration` section. You set the column letters and sheet names to be whatever you want. But I changed it to `Q` to reflect the OP's question


Showing that a function is uniformly continuous but not Lipschitz

Question: If $g(x):= \sqrt x $ for $x \in [0,1]$, show that there does not exist a constant $K$ such that $|g(x)| \leq K|x|$ $ \forall x \in [0,1]$
Conclude that the uniformly continuous function $g$ is not a Lipschitz function on interval $[0,1]$.
Necessary definitions:
Let $A \subseteq \Bbb R$. A function $f: A \to \Bbb R$  is uniformly continuous when:
Given $\epsilon > 0$ and $u \in A$ there is a $\delta(\epsilon, u) > 0$ such that $ \forall x \in A$ and $|x - u| < \delta(\epsilon,u)$ $\implies$ $|f(x) - f(u)| < \epsilon$
A function $f$ is considered Lipschitz if $ \exists$ a constant $K > 0$ such that $ \forall x,u \in A$ $|f(x) - f(u)| \leq K|x-u|$.
Here is the beginning of my proof, I am having some difficulty showing that such a constant does not exist. Intuitively it makes sense however showing this geometrically evades me.
Proof (attempt):
Suppose $g(x): = \sqrt x$ for $x \ in [0,1]$
Assume $g(x)$ is Lipschitz. $g(x)$ Lipschitz $\implies$ $\exists$ constant $K > 0$ such that $|f(x) - f(u)| \leq K|x-u|$ $\forall x,u \in [0,1]$.
Evaluating geometrically:
$\frac{|f(x) - f(u)|}{ |x-u|}$ = $\frac{ \sqrt x - 1}{|x-u|}$ $ \leq K$
I was hoping to assume the function is Lipschitz and encounter a contradiction however this is where I'm stuck.
Can anyone nudge me in the right direction?
Comment: HINT: The inequality you want to disprove can be rephrased as follows: "the function $|x|^{-\frac12}$ is bounded on $(0,1]$". Is this true? If you can show it's not, you are finished.
Answer: Take $u=0$. Then you should have $|f(x)|\le K|x|$ for $x\ne0$. Notice that $|f(x)|/|x|\to\infty$ when $x\to0$, which contradicts to this inequality.
Answer: Well, choose $u=0$. What can you say about $\frac{|f(x)-f(u)|}{|x-u|}=\frac{\sqrt{x}}{x}$ as $x$ gets closer to zero?
Here is another proof using derivatives.
Since $f'(x)=\frac{1}{2\sqrt{x}}$, it follows that
$$\lim_{x\to 0} f'(x)=+\infty$$
This means that for every $M>0$ there exists $\delta$ such that for every $x$ in $I=[0, \delta]$, $f'(x)>M$.
Suppose by contradiction that such $K$ exists.  Consider $M=K+1$ and $x_0\in \text{int}(I)$: then
$$f'(x_0)=\lim_{x\to x_0}\frac{f(x)-f(x_0)}{x-x_0}>K+1$$
But then there exists an interval $J$ such that for every $x\in I \cap J$
$$\frac{f(x)-f(x_0)}{x-x_0}>K+1$$
$$\implies |f(x)-f(x_0)|>(K+1)|x-x_0|$$
contradicting our hypothesis.