Como simplificar um problema para pegar os nomes dos meses do ano?

Question: Estou a começar a programar em C e realizei este problema cujo enunciado é o seguinte:

Escreva um exercício que solicite o número de um mês ao utilizador e que imprima no ecrã o nome do mês. Por exemplo, o utilizador introduz 1 e o programa escreve "Janeiro". Caso o utilizador introduza um número que não corresponda a qualquer mês, deve escrever uma mensagem de erro apropriada no ecrã.

Para já, ainda só sei o básico (if, else...), como tal, fiz assim:
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int mes;
    printf("Numero do mes: \n");
    scanf("%d",&mes);
    if (mes == 1)
        printf("Janeiro\n");
    else if (mes == 2)
        printf("Fevereiro\n");
    else if (mes == 3)
        printf("Marco\n");
    else if (mes == 4)
        printf("Abril\n");
    else if (mes == 5)
        printf("Maio\n");
    else if (mes == 6)
        printf("Junho\n");
    else if (mes == 7)
        printf("Julho\n");
    else if (mes == 8)
        printf("Agosto\n");
    else if (mes == 9)
        printf("Setembro\n");
    else if (mes == 10)
        printf("Outubro\n");
    else if (mes == 11)
        printf("Novembro\n");
    else if (mes == 12)
        printf("Dezembro\n");
    else if ((mes<1) || (mes>12))
        printf("Erro\n");

    return 0;

}

Como posso resolver este mesmo problema com um código mais simplificado?
Comment: Pesquise pelo comando switch/case.
Comment: Note que em seu programa você testa todos os números de mês válidos (1 a 12) portanto não há necessidade do último if.
Comment: Alguma das respostas resolveu sua dúvida? Acha que pode aceitar uma delas? Veja o [tour] como fazer isso, se ainda não o fez. Você ajudaria a comunidade identificando qual foi a melhor solução para você. Pode aceitar apenas uma delas. Mas pode votar em qualquer pergunta ou resposta que achar útil no site todo
Answer: Algumas coisas aí estão sobrando, mas a maior simplificação é usar um array  no lugar de um if. Você pode colocar todos os nomes nesse array  e acessar através do índice dele conforme a digitação. A validação precisa ser feita antes. Note que retirei algumas redundância, afinal simplificação implicam nisso.
#include <stdio.h>

int main() {
    int mes;
    printf("Numero do mes: ");
    scanf("%d", &mes);
    if (mes < 1 || mes > 12) {
        printf("\nErro");
        return -1;
    }
    printf("\n%s", (char *[12]){ "Janeiro", "Fevereiro", "Marco", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro" }[mes - 1]);
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Comment: Não seria melhor usar uma função que retornasse o mês escolhido?
Comment: @gato, não sei, depende do que se quer fazer, em um exercício que faz quase anda e quer ser simples uma função parece ser canhão para matar passarinho. Há um forte justificativa para usar a função?
Comment: Aumentar a legibilidade e evitar a repetição do array, o princípio da função é apenas retornar o mês escolhido.
Comment: Não há repetição, legibilidade é discutível. Em um exercício que queira ser simples o ato de criar uma função piora a legibilidade, e é *overengineering*.
Answer: Armazene os meses num array: const char *strings[] = {"Janeiro","Fevereiro"...};, e acesse o respectivo mês com a entrada do usuário:
printf("Numero do mes: \n");
scanf("%d",&mes);

printf("%s", meses[mes-1]);

Comment: Por que esse "i" no printf? Ele não está definido...
Comment: Caramba! Nem tinha percebido rs.
Answer:  #include <stdio.h>

 int main() {
    int mes;
    printf("Numero do mes: ");
    scanf("%d", &mes);
    const char *meses[] = {"Janeiro", ...};

    for(int i = 0; i < 12; i++) {
        if(mes == i) {
            printf(meses[i]);
        }
    }
 }

Comment: Oi, Juliana, da uma olhada nesse tópico e entenda porque você pode levar pontos negativos com respostas no formato da sua (Em apenas código): https://pt.meta.stackoverflow.com/questions/7634/voc%C3%AAs-acham-isso-certo?cb=1


Erro ao executar um HttpResponse no Android Studio

Question: estou tentando enviar uma string de um aplicativo Android para uma página PHP, porem, quando realizo o envio, ocorre um erro no método
HttpResponse response=httpclient.execute(httppost);
Caso alguém possa me ajudar com qualquer informação pra tentar resolver este problema, agradeço desde já!
Já realizei uma boa pesquisa na internet e uma das formas mais válidas que encontrei para minha situação foi este método abaixo
referencia: https://stackoverflow.com/questions/16079991/send-a-string-on-android-with-httppost-without-using-namevaluepairs
public void postData0(View v){
    try {
        Log.v("GG", "Sending sever 1 - try");
        // start - line is for sever connection/communication
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://meuSite.com.br/listener.php");

        httppost.setEntity(new StringEntity("legume = batata"));

        Log.v("GG", "erro ocorre na linha abaixo. . .");

        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        // end - line is for sever connection/communication
        InputStream is = entity.getContent();
        Toast.makeText(getApplicationContext(),
                "Send to server and inserted into mysql Successfully", Toast.LENGTH_LONG)
                .show();
        // Execute HTTP Post Request
        response= httpclient.execute(httppost);
        entity = response.getEntity();
        String getResult = EntityUtils.toString(entity);
        Log.e("response =", " " + getResult);

    } catch (Exception e) {
        Log.e("log_tag", "Error in http connection "
                + e.toString());
    }

}

E este é o código que fiz para receber a String.
$tudo = $_REQUEST['legume'];
var_dump($tudo);

$fp = fopen('teste/teste.txt', 'w');
fwrite($fp, $tudo);

Obrigado pela atenção.
Comment: E/log_tag: Error in http connection android.os.NetworkOnMainThreadException
Comment: Relacionado [Erro NetworkOnMainThreadException usando HTTPClient](http://pt.stackoverflow.com/questions/69894/erro-networkonmainthreadexception-usando-httpclient)
Comment: Qual erro acontece? o que ele diz?
Comment: ele da o erro do

catch (Exception e) {
        Log.e("log_tag", "Error in http connection "
                + e.toString());
    }

quando chega neste método  HttpResponse response = httpclient.execute(httppost);

da o erro
Comment: Qual é mensagem?
Comment: OnMainThreadException significa que você não pode executar o httpclient na thread principal. Para isso  crie um `AsyncTask` e execute seseu código dentro do AsyncTask
Comment: Obrigado galera, vou pesquisar uma maneira de fazer com Async Task e ver se da certo. qualquer coisa volto aqui.
Valew o apoio!!
Comment: Infelizmente só poderei testar amanha, porem aquele erro realmente sumiu, Muito obrigado pela ajuda :D

Amanha confirmo aqui se deu certo ou não, mas a principio ta tudo ok :)
Answer: Dalhe galera!!
a funcionando!!!
fiz algumas alterações no escopo e utilizei algumas dicas fornecidas pelo LeoSantana e deu certo aqui
o código ficou assim
public void postData0(View v){new LongOperation().execute("");}

private class LongOperation extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... params) {
        try {
            Log.v("GG", "Sending sever 1 - try");
            // start - line is for sever connection/communication
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://meuSite.com.br/listener.php");

            //httppost.setEntity(new StringEntity("legume = batata"));
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("legume", "{\"usuario\":[{\"nome\":\"fulano\",\"idade\":\"97\",\"email\":\"email@example.com\", \"sexo\":\"masculino\"}]}"));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            Log.v("GG", "erro ocorre na linha abaixo. . .");

            HttpResponse response = httpclient.execute(httppost);
            Log.v("GG", ":D :D :D . . .");
            HttpEntity entity = response.getEntity();
            Log.v("GG", "1 . . .");
            // end - line is for sever connection/communication
            InputStream is = entity.getContent();
            Log.v("GG", "2 . . .");
            //Toast.makeText(getApplicationContext(),
            //      "Send to server and inserted into mysql Successfully", Toast.LENGTH_LONG)
            //      .show();
            // Execute HTTP Post Request
            response= httpclient.execute(httppost);
            entity = response.getEntity();
            String getResult = EntityUtils.toString(entity);
            Log.e("response =", " " + getResult);

        } catch (Exception e) {
            Log.e("log_tag", "Error in http connection "
                    + e.toString());
        }

        return null;
    }

    @Override
    protected void onPostExecute(String result) {
    }

    @Override
    protected void onPreExecute() {
    }

    @Override
    protected void onProgressUpdate(Void... values) {
    }
}

Obrigado pela ajuda :D


How visible is my /var/www to the outside world?

Question: I suppose this is more of a house keeping question, but here it goes.
If I create a backup file of my index.html called index.html.bak, is it possible that someone from the outside using http on my apache2 server is able to list the contents of my /var/www directory?  I currently know no method of doing this, but this could be due to my lack of experience in this area.  Should I store files that need not to be in view somewhere else?
Currently, the only feasible way I can think that someone might discover the file is if there was an explicit link somewhere pointing to the file.  How visible is my web directory?
Answer: If you specify Options -Indexes for the Directory in question, then Apache will not generate a directory listing. However, if someone guesses the filename they could still access it if the operating system allows the web server to access the file.
Comment: Yup. If you have something you don't want served up on the web, don't keep it in `/var/www`.
Comment: Computers do the guessing these days. So don't rely on obscurity to protect anything important. BTW, I upvoted the other answer. :)
Comment: This is the best answer for those `tl;dr` people with the answer by Craig, although Craig's is more thorough.
Comment: @nonak Up vote both :)
Comment: On the topic of guessing, guess how long it would take to find index.html.bak or index.bak.html, etc. Anything that obvious doesn't really stand a chance.
Comment: Michael is right on this. There are many many sripts that are  botnet-driven and scan huge amounts of ip's for common misconfigurations such as this one, lloking for passwords and other things that could be of interest. Security by obfuscation is pretty much the same as having no security nowadays.
Answer: To directly answer your questions - you can either keep such files somewhere else or you can configure apache to deny access to them - denying access to *.bak is relatively simple.
Apache will, unless configured not to do so (as mentioned by MH above), generate and display a directory listing for any directory that does not contain an index file - defined by the DirectoryIndex directive, but typically index.html, index.htm, index.php, and similar.
On a more general note:
You may want to consider using a revision control system such as SVN or git (or even RCS) to keep old versions AND a change history of your web pages (including the ability to see what changed and when and, more importantly, the ability to revert to a previous version)
Both git and svn need a repository set up somewhere else.  RCS is fairly primitive and basic but doesn't require any setup, it keeps the revision history in either the same directory or in a ./RCS subdirectory if one exists.  One minor annoyance with RCS is that when you check-in a file, it changes the permissions to read-only, so you have to check it out again before you can edit it again (or use ci -l to check-in a file and immediately check it out).
IMO git is probably overkill for this job, SVN is close to ideal in terms of complexity vs capability for managing the revision history of a set of hand-edited HTML pages, and RCS is archaic but still useful.  With RCS you can only edit files directly within /var/www which means the changes are "live" as soon as you save the file.  With svn or git you can check out a local copy in, e.g., your home directory on your desktop machine, edit the files, check-in the changes, and then check-out the updates into /var/www on the server when it's finished.  You can also check-out the changes to a staging server first for testing, before checking them out on the production server.
You can then deny access to the .svn/, .git/, RCS/ etc subdirectories with apache - e.g. see https://stackoverflow.com/questions/398008/deny-access-to-svn-folders-on-apache
Of course, using revision-control effectively will take a little discipline. you'll have to get into the habit of checking in your changes whenever you make them - it's worth the effort.
Answer: If you have directory listing enabled then that file is certainly visible. Even if directory listing is not enabled, it isn't recommended to save a file that you don't want someone to see in /var/www because it is made for public documents.
Answer: I don't see any point in keeping the backup file in /var/www.
Backups are made to quickly fix things when you screw them up. I'd suggest you to make a new backup directory, in some core drive (unaccessible to the outer world), & store your backups there.


Lock configurations

Question: I have EForm module installed on my Drupal 8 website. My customer uses EForm module to create new forms. The problem is that newly created forms are storing in configurations. Every time I deploy my code to the production instance I deploy it without configurations for newly created forms and when I do sync on the production it deletes forms that were added by the customer since they are not in my configurations. Now I need to download latest backup from the production to keep customers forms and it is very annoying. So I wonder is there any way to lock particular configurations in Drupal 8 either using contrib module or programmatically.
I've found Configuration Read-only mode module but it locks all configurations but not particular one.
Answer: What you can do is to use --skip-modules if you sync configuration with drush. You can even put it in a drushrc file so you don't need to remember it.
Doing will will make drush skip the sync of the entire module. It's not possible to omit only some config files, like a reg ex pattern etc.
Comment: Thanks for answer. I was thinking about it, but I would like to be able to lock configuration instead of skipping. New developers may not know about skipping during drush sync or even use UI sync and they can break forms added by the customer
Answer: You could have a look at the drush CMI tools recently published by PreviousNext: https://www.previousnext.com.au/blog/introducing-drush-cmi-tools
That allows you to have exclude patterns of certain config, so they're not maintained with git at all.
I don't use them yet. My workflow is basically to do new development in a separate branch, staging or something else. Then before the deployment, I export production config, sync it back to local, commit that, merge in your branch that contains the new config, resolve possible merge conflicts, deploy, run drush cim and verify that there are only expected config changes.
It's not perfect, there is a possibility that a config change happens right between those steps, but it is rather unlikely and in the case of contact forms or eforms, easy to spot.

Lock configurations


$\frac{|\sin x|}{x}$ is not integrable on $[1,\infty)$

Question: I understand how to show that
$$\frac{\sin x}{x}$$
is improperly integrable, but I'm having troubles with showing that it is not absolutely integrable.
Here is my work:
$$\frac{|\sin x|}{x}\leq \frac{1}{x}$$
and I know $\int_{1}^{\infty}\frac{1}{x}dx=\lim_{d\to \infty} \log(d)\to \infty$
but that doesn't prove that $\frac{|\sin x|}{x} \to \infty$ since it is less than $\frac{1}{x}$.
I was thinking about doing squeeze theorem
Answer: Hint:
$$\int_{(k-1)\pi}^{k\pi}\frac{|\sin x|}{x}\,dx
  \ge\int_{(k-1)\pi}^{k\pi}\frac{|\sin x|}{k\pi}\,dx
  =\frac1{k\pi}\left|\int_{(k-1)\pi}^{k\pi}\sin x\,dx\right|
  =\frac2{k\pi}\ .$$
Answer: If we define
$$ F(t) = \int_{0}^{t}\left|\sin x\right|\,dx $$
it is not difficult to show that $F(t)=\frac{2t}{\pi}+O(1)$, for instance by exploiting the Fourier cosine series of $\left|\sin x\right|$. By integration by parts it follows that
$$ \int_{1}^{N}\frac{\left|\sin x\right|}{x}\,dx = \frac{F(N)}{N}-\frac{F(1)}{1}+\int_{1}^{N}\frac{F(t)}{t^2}\,dt = O(1)+\frac{2}{\pi}\int_{1}^{N}\frac{dt}{t}$$
hence the LHS diverges like $\frac{2}{\pi}\log N$.


Is K-Nearest Neighbor and Nearest Neighbor algorithm the same?

Question: Does anyone know if there is a difference between K nearest neighbor (KNN) and nearest neighbor algorithm (NN)? And if they are how are they different?
So far all I know is that NN is unsupervised learning while KNN is supervised learning.
Comment: When you say "NN is unsupervised learning", are you reading NN as neural networks rather than nearest neighbours?
Answer: Nearest Neighbors (NN) is a catch-all term for a whole family of methods that use search among the neighbors for different purposes. Scikit-learn named a whole module like this. $k$NN is a regression and classification algorithm that works by searching the database to find $k$ points the most similar to an example and average them to make the prediction. The other use may be in a content-based recommender system, where we are searching for some number of similar products to present them as recommendations. In both cases, we use the nearest neighbors search as a workhorse. Also, keep in mind that it is not a single algorithm, but there are multiple algorithms and their implementations for it, including exact and approximate ones (e.g. Spotify's Annoy).


Porque 'getAttribute()' não é uma função?

Question: Estou tentando acessar o atributo xlink:href de um  dentro de um SVG. Porém quando tento acessar esse atributo, o Console Log retorna que getAttribute() não é uma função.
O HTML:
<svg version="1.1" id="svg-map" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="450px" height="460px" viewBox="0 0 450 460" enable-background="new 0 0 450 460" xml:space="preserve">
    <g>

            <path stroke="#FFFFFF" stroke-width="1.0404" stroke-linecap="round" stroke-linejoin="round" d="M289.558,235.641
                c16.104,0.575,44.973-31.647,44.835-45.259c-0.136-13.612-17.227-58.446-22.349-66.088c-5.122-7.628-37.905,2.506-37.905,2.506
                S234.852,233.695,289.558,235.641z"></path>
            <text transform="matrix(1 0 0 1 287.0137 188.3208)" fill="#FFFFFF"></text>
            <image width="42" height="55" xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACoAAAA3CAYAAAB6i9geAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyZpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNi1jMDY3IDc5LjE1Nzc0NywgMjAxNS8wMy8zMC0yMzo0MDo0MiAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENDIDIwMTUgKFdpbmRvd3MpIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOjYyQkZCQUVDOEUxQjExRTVCMjMxQ0YyNkU3MjA2NjMyIiB4bXBNTTpEb2N1bWVudElEPSJ4bXAuZGlkOjYyQkZCQUVEOEUxQjExRTVCMjMxQ0YyNkU3MjA2NjMyIj4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6NjJCRkJBRUE4RTFCMTFFNUIyMzFDRjI2RTcyMDY2MzIiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6NjJCRkJBRUI4RTFCMTFFNUIyMzFDRjI2RTcyMDY2MzIiLz4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz7CC2p7AAAHgElEQVR42syZa2wUVRSAz8zudqG0trTLtos8jCCEClqiRdpoRCGSIEKJ/aHyqDx8tIUQYzAxCj4SA6hEhNIiyg9oSPSHQBEUtAiBQguEN7SotNLWvrbbQmm73dfM9dztaOfOzL53CTc5me7M3blfzzn3PO5yEOYg+/TD8PIMyvMoj6NMRDGhDPOc94DdCeSuAEIngTs2QV9nFZMOEKN+x8JN7bZw1uPCAJyOlwKUlymU1hwKKjrV9x349WtOqL8pjFifv61jZ0xAETALL5+jzAg01xeofNwQ4PYFh3n10hJrWVRAJRNvRCkM9h8LBtT7bpQqh+5qo940M/+r9o6wQRGS+t1elAy/84gInEcEIgx8FlvwnosSoyBwIOh/RHAet6fnLi9tOxwyKEJm4+UQynDN54IApAd1YscPQgDN4XOxD/9AIR7tOX0EyE9205v5JbbvtJ7r/EAeRUlUPRNxpduovS784JLsF8i/eADeiELfFid9T2TnxHHATTTY503INLXsP2e/EBBUMncFygOqFe3oe1ZpoTAHZxgA5kTJPeQwaN+xBvvcjMy06vJzfXU+TY+QQ/ByFmWKcgGxGzV5V2PlISbgxy8BGIPhNGUCQHwavhVf6+zB+X8DtFQDqfsRSEeV2nL96DWdaqs0CeCocFosb29rveMLdDNeVqteeNsDpFdxc6gF+OkbgGS8hqbVB1Zl6xkgVR8BaT6iCq4emxq20mG4NHOre6rK9AhJswsNwjwD2YOQCk3y4xYDl4v7bORTqDw+OJsnjgJu0iLg4scCaSofBMP/kdMPaFc+RunF9HGZ5hp0gRpQQG1U+awbfbJbATl1LcCc3QDGpPCcdMpS4OefAjAMLs3FDwizDs3LemuJ/DPVJlXxbJVf4s7mZCbhM1YBPP0pRDwezAF+zlEgMsfTpShtCTDZCKZdheZX5Rot0Nrh8t3Np07D5PklRG2MmQG6rA3MttYlqqc9pOtc532M2sQIB+0ojC3FdgVo3hkAyzSI6hDcQPZkAumuGUy/zWyM7cOQ/UO/JZlqNFsJCR4F5Oh50Yf02tsAXNZaNs4OYacM44FLAPcyCjpLFY7sihuTV0DMxiO5mJYG6XQahaNZ15PHS0UvCyorIrwOP2ZG7EAxx3Cj82QJBLWqyJepOud4XqrMFXWafDeiyeMSIZaDS3tSkfjZjyYeUihouj9QeOBhiPlIGsfGUAP7GHeSnteqkJhhTIk9qDfwyNxNEU+HchBE/vPYYw8qsgUtp1E6UlBVTSTPGMTeHHvQ3hZVoc3kHjKg5BtaNeP/X7KdptVybEE7r7Ogijq1VYA+Cvq7P1BwYf9gvRRbyzf+wmiTuBU9ldt4jZeqeb/ZAWq/jx1l2zl0vlo22Sh8tF1I2EdBT6CwrWo8z/ipWPsFQH9nbEDPf+03K3aLIPZwxmKeW+Chit6t3GN8vCKunv4k+pBNJ0Cs3yMrUtCaCv+87DJcLCxpsf8Xnr5VB2GO1WrNVoCbB6MHiRYiFfmsNrtUzSk0uFPXMj0Tlnv78TLfb0OHLQM/H6PAyOzIIF3Y+JXPA7Ht+OA9rC88VnbaFTe0ZW0Gi7IVUdmWT8Ltb2BdQCzPAag7FD7k3SYge2ezkLh5PBpb4FK/eY2vLvQAXl5SnYi0EZVN+EkrAXLQKvHmIE/Z0AGv7wFyeiVWZz1seLKqj33k2gR1lwJrFCUJllw64M3qmWJtMYi7sIc/9q63dwfRx1lNdwPAxW1Ayh4D8Vi+CpJ0qCFpYrriTF/q9+wJtboFL6vUOV8A0YaadfvQGHaVXEoOxmBUgi4OiKMDyB3MOL5SMFpI6FBnITpO9huuzCp2M3Wy1snBxyivoIxgKxzUbDo2MPTcqVfjW268314ZzFGUt4enHa5WZqZx8xakLsBMoCpK2Ky0wEOPv97RXgK1NlwPPPWc+DA2kgMBcX3B5rt8OO5I/mZFcVt9KMeO9OzlBb+aoX6JmYQ4pIMzRdXjPWLE+2L/AGSg2ua6E7ryysea6hsaVIbxd2j0FvVpf4W198wpAWibyPzvnstuLzwRQoj/WMqd96TN1YLUNL3MBW75dgG/evbGjVAg6aiwJ5W9UdJe5eu53wofYXdKp84xHVedYH3vUPLr/uYEcxS3jNausYLEICKedVme82XyoEFRqzQDL4GgDsFDdhL41Z76QeH21ppAc4M63ERYWlyvjzboCYexcklp54Zg5vIhvHedVjcQ7qhxQ9dfHtPMYOcHDYpaFaSM1RgppE0AodppyS4qbXZFHVSCpcVY3kD1GN5wo2Me6TcvLyht/TOU7/GhLoSw2I1BUbigh/uSypaVWneFvG7YO3affruUvdSFlo/fQqudfM2zW8RHw1mPj8DVaCl4NNjJN3DzNBqUx3b3AFTqXqm//hFobosArkqH5YnFm1r77zmoBEt/WXsRpcvXnB4sUw/3ps8t2t56K5K1+EhDDcLS3yxztSIBrfKOOFNXFexo+y3SdSIGlWBP4mURyFpAgmHooD1508Lizm1wvw2MBKtRiPtDIPuLEvbC/TwQ9LNT78f9HO33/ivAAO3E9ZnXS3B1AAAAAElFTkSuQmCC">

    </g>
</svg>

E o meu JavaScript:
document.querySelector('#svg-map').addEventListener('mouseover', function(){
    var link = this.getElementsByTagName('g a');
    console.log('Hello World ' + link.getAttribute('id'));
});

O que estou fazendo de errado?
Answer: Porque getElementsByTagName() retorna um HTMLCollection (que se comporta como um array), então você precisa acessar como um array: link[0].getAttribute('id').
Outro problema é que .getElementsByTagName('g a') não é valido, uma vez que essa função aceita apenas o nome de uma tag, não várias, a melhor solução seria utilizar .querySelector(), como você fez na primeira linha.
document.querySelector('#svg-map').addEventListener('mouseover', function(){
    var link = this.querySelector('g a');
    console.log('Hello World ' + link.getAttribute('id'));
});

Answer: O método getElementsByTagName retorna uma lista de elementos e não um único elemento, por isso desse problema, no array não existe a função getAttribute.
Faça assim:
document.querySelector('#svg-map').addEventListener('mouseover', function(){
    var link = this.getElementsByTagName('g a')[0];
    if (link !== undefined) {
        console.log('Hello World ' + link.getAttribute('id'));
    }
});

Comment: Acredito que getElementsByTagName('g a')[0]  não trará nenhum retorno, deveria seguir a orientação do @Sanção e querySelector
Answer: Tente com attributes assim:
document.querySelector('#svg-map').addEventListener('mouseover', function(){
    var link = this.getElementsByTagName('a');
    console.log(link[0].attributes['xlink:href'].value);
    console.log('Hello World ' + link[0].id);
});

Saida:
#tocantins
Hello World BITCH!

Veja funcionando no Jsfiddle.


Why do professional sports teams hold training camps train in a different location (city) during the off season?

Question: It strikes me as odd that teams who have stadiums built for their games don't use the fields for training.  Is this done to make room for other sports teams to use the fields during the off-season?
Comment: If they train outdoors, they might go someplace warmer during a winter break for instance.
Comment: They want a break?
Answer: The answer varies significantly by sport, and in part by team.
Those reasons that are common:

Training camp is often much more focused practice and learning time than other times (during the regular season).  Think of it sort of like a retreat: you live in a more confined area, with just your teammates, and think "your sport" 24/7. It allows teammates to build chemistry and focus on their studies.
Stadiums and arenas are expensive to use - even just to turn on the A/C at something like the United Center is quite expensive.  They also aren't built for training: for example, for a basketball court they've only one set of backboards.  You would rather have a purpose-built facility for training: one with many courts/rinks/etc., more room for strength equipment, that sort of thing.  In fact, most teams in sports like basketball have a separate training facility even during the year, sometimes in the home city, sometimes nearby. Further away is often cheaper, and quite often also closer to where the players live. (For example, until this year, the Chicago Bulls practiced and trained in the Berto Center, in suburban Deerfield; this year, they built a new training center across from the United Center in Chicago.)
For grass fields, you want to give the grass as much time to grow as possible.  Each game wears on the field, so you'd rather have some games elsewhere to let the groundskeepers have more time to do their magic.  You also often don't have as many fans willing to come to games in the preseason - so you hold games somewhere that people might come as a vacation, or where the people in that area might not normally have a chance to see games.  Hence Spring Training for the baseball teams in Florida and Arizona - destination vacation spots that time of year - and until the last two decades, without major league teams nearby; but also with many retirees who love to see the teams they cheered for in their youth.
Comment: you may add the aspect of PR. Especially the last years a lot of european football (soccer) teams did their training camps in US or Asia to make new markets accessible.


Regex para ignorar nomes de arquivos inválidos

Question: Olá, estou tentando adicionar uma regex no app.yaml para ignorar arquivos com nomes estranhos no Google App Engine, mas não esta funcionando.
Minha expressão regular:
skip_files:
- [.\\~#%&*{}:<>?|\"-!]

Estou recebendo este erro:

appcfg.py: error: Error parsing /home/klarkc/project/dist/app.yaml:
  while scanning for the next token found character '|' that cannot
  start any token   in "/home/klarkc/project/dist/app.yaml", line 49,
  column 18.
Comment: Você precisa de uma expressão que ignore os caracteres: `.\~#%&*{}:<>?|"-!`, certo?
Comment: Isso mesmo, que funcione no yaml
Answer: A expressão abaixo permite que case apenas os carácteres alfabéticos letras de A..Z e a..z e números 0..9 e os símbolos -, _, . e o espaço em branco  , veja.
Expressão:
^[\w\-. ]+$

Para faze o inverso e permitir que cases apenas os símbolos especiais *&%#^~ basta usar a lista negada ^, veja abaixo:
Expressão:
^[^\w\-. ]+$

Fonte: Regular expression for valid filename.
Comment: @WalkerLeite você fez uma edição que alterou coisas substanciais na resposta, por isso foi rejeitada. Quando quiser sugerir alterações substanciais que possam alterar o sentido da pergunta/resposta, notifique o autor sobre as mudanças e peça que ele mesmo faça.
Comment: Teria como negar essa expressão? Já que o parâmetro é para filtrar os arquivos que serão ignorados e não os que arquivos a serem aprovados.
Comment: Apesar da outra solução do @Gomiero ter funcionado, no final das contas acabei usando a sua solução, porque filtra tudo que não é válido, em vez de procurar por caracteres específicos. A única mudança que eu fiz foi usar a regex assim: ^.*[^\w\-.\s\/]+.*$ para adicionar também o separador de diretório à lista de caracteres aceitos e .* pra dar match em caracteres anteriores e posteriores respectivamente.
Answer: Você precisa escapar alguns caracteres, veja abaixo como deve ser sua regex;
[\.\\~#%&\*\{\}\:<>\?\|\-!]
na sua original faltou escapar o

. -> Equivale por qualquer caractere
{} -> para informar uma quantidade de repetidores ex .{4}
:-> Não sei a funcionalidade, "alguém edita"
? -> significa que tem que terminar assim a expressao
| -> Operador OU
- -> usado para grupos, tipo 0-9
Answer: A expresssão abaixo, encontra os nomes arquivos com os caracteres da lista .\~#%&*{}:<>?|"-!::

^[^\\\#\%\&\*\{\}\:\<\>\?\|\"\-\!]+$

Veja um caso de uso funcionando no regex101

^  match no início da linha
+  uma ou mais vezes
$  match no final da linha
Mais exemplos (talvez melhores) em:
Skipping Files.
Para validar a sintaxe dos arquivos YAML (antes de utilizá-los):
Online YAML Parser
Code Beautify - YAML Validator
YAML Lint


parsec: unexpected character parsing nested comments

Question: I am trying to parse nested C-like block comments
import Text.ParserCombinators.Parsec
import Control.Monad (liftM)

flat :: Monad m => m [[a]] -> m [a]
flat = liftM concat

comment :: Parser String
comment = between (string "/*") (string "*/") (try nested <|> content)
  where
    content = many (try (noneOf "*/")
                   <|> try (char '*' >> notFollowedBy (char '/') >> return '*')
                   <|> try (char '/' >> notFollowedBy (char '*') >> return '/'))
    nested  = flat $ many comment

"1234567890" parses fine, but when I try
parse comment "" "/*123/*456*/789*/"

I get
Left (line 1, column 3):
unexpected "1"
expecting "/*" or "*/"

I cannot figure out why, I have try everywhere I can think of. Please help.
Answer: In an expression like a <|> b, if a can match the empty string then b will never be tried, and this is happening in try nested <|> content.
You can fix your approach by requiring at least one comment match or another character:
comment :: Parser String
comment = between (string "/*") (string "*/") ( flat $ many $ (try comment <|> liftM toString other ) )
  where
    toString x = [x]
    other = try (noneOf "*/")
            <|> try (char '*' >> notFollowedBy (char '/') >> return '*')
            <|> try (char '/' >> notFollowedBy (char '*') >> return '/')

FWIW, here is how Text.Parsec.Token does it:
https://github.com/aslatter/parsec/blob/master/Text/Parsec/Token.hs#L698-714
For your specific case the equivalent code is:
import Data.List (nub)

commentStart = "/*"
commentEnd = "*/"

multiLineComment =
    do { try (string commentStart)
       ; inComment
       }

inComment = inCommentMulti

inCommentMulti
    =   do{ try (string commentEnd) ; return () }
    <|> do{ multiLineComment                     ; inCommentMulti }
    <|> do{ skipMany1 (noneOf startEnd)          ; inCommentMulti }
    <|> do{ oneOf startEnd                       ; inCommentMulti }
    <?> "end of comment"
    where
      startEnd   = nub (commentEnd ++ commentStart)


Interplay between early stopping and cross validation

Question: I am a little bit confused by early stopping and in particular by how it can be inserted inside a CV framework. As far as I understand, I can fix the optimal number of epochs (for NN, or number of trees for XGB) by early stopping, that is:

pick a validation set,
train with increasing number of epochs until a predefined metric evaluated on the validation set starts worsening
that is the optimal number of epochs to prevent overfitting

and that's fine. But then I would like to insert this early stopping framework inside a CV framework: Suppose I have a model with 10 hyperparameters I want to fix via CV. And suppose that there is an eleventh hyperparameter, the number of epochs.
My feeling is that one can do like this:

create the K resampled folds, for each of which you have a training and validation set
choose a suitable grid for your 10 hyperparameters
for each point on the grid train your model in each fold with early stopping, that is use the validation set of the fold to keep track of the preferred metric and stop when it gets worse
take the mean of the K validation metric
choose the point of the grid (i.e. the set of hyperparameters) that gives the best metric

Questions:

What number of epochs should I choose as optimal? in each of the K folds I have, in general, a different number of stopping epochs. H20 doc seems to suggest they take the mean of the K stopping epochs. Is this right?
Is it actually a "fair" practice to use the validation metric coming from the early stopping as a proxy of the out-of-sample metric? As Max Khun seems to point here in section 3.4.5, maybe the best thing to do would be:

...if you want to do early stopping, then in each fold you should take your training set and split it again, holding out a small early-stopping-set to guide the early stopping, and then evaluate the model on the validation set of that fold.

But this seems to me a really intricate process...

Unfortunately, I wasn't able to find references where this issue is presented in a clear and transparent form.
Comment: have you ever come to the best practice regarding this issue?
Answer: This topic has been already discussed from several angles:

Neural network training without early stopping
Is epoch optimization in CV with constant mini-batch size even possible?
How to correctly retrain model using all data, after cross-validation with early stopping

However, I think that none of the answers covers your question fully, so I will summarize:

You should not use the validation fold of cross-validation for early stopping—that way you are already letting the model "see" the testing data and you will not get an unbiased estimate of the model's performance. If you must, leave out some data from the training fold and use them for early stopping.
However, this does not help you too much, for two reasons:

Optimal stopping epoch may have large variance between different folds and there is no guarantee that taking the mean will be optimal in any way.
If you decide to train on the whole dataset, length of an "epoch" will change: Epoch is defined as "using the whole dataset once", so how many weight updates happen in one epoch depends on the training set size and the batch size. Early stopping generally aims at limiting the maximal number of weight updates, so optimizing "epoch count" on a dataset of different size makes no sense.
Thus, if anything, optimize early stopping in terms of weight updates, not epochs.

Finally, I think the best approach is not to use cross-validation for early stopping tuning, instead tune all the other hyperparameters and then during the final training leave aside a small validation set which you use for early stopping.
Comment: Ah, good point! I would just split the training fold again, as you mention in the second question. It's not as intricate as it seems. Or to simplify things, you could even leave an early stopping validation set before starting the cross validation on the rest of the data and use this one in every run...
Comment: thanks a lot for your answer. Regarding the comment on *epochs* versus *weights*, that's fine. But I was more concerned on the actual building of the framework. From your last point, I understand that early stopping should be made in the very last run, but what number of epochs should I use for optimizing the hyperparameters in first place?


Remote controller name from CakePHP URL

Question: I have a problem with the url rewriting.
The problem that I am facing is that currently our urls are like this:
http://www.xyz.com/sc_users/index
I dont want the controller name to be shown in that url.
Is there a way to achieve that??
First of all thank your guys..
Like I have 8 controllers I dont want the controller name to be shown in my url....this is what I want..
To be more precise no controller name in my url
Answer: You can define custom routes in app/config/routes.php. You'll find the all about routes in the CakePHP cookbook under Defining Routes. For example, a custom route can look like this:
Router::connect(
    '/the_url_you_want_to_use/*', array('controller' => 'sc_users', 'action' => 'index')
);

Answer: You need to read up about CakePHP routing, look at the examples under 'defining routes'. Update your question with what you would actually like your URLs to look like and we will be able to help you more effectively.
Comment: First of all thank your guys..Like I have 8 controllers I dont want the controller name to be shown in my url....this is what I want..to be more precise
Answer: That's simple :
there is a file called routes.php in /config directory :
You can do url rewriting stuff there like this :
Router::connect('/pages/*', array('controller' => 'cmsPage', 'action' => 'render'));

You can pass more complicated variables to your controller :
Router::connect('/:id-:lang-:profile-:firstName-:lastName-:profile.htm',
    array('controller' => 'profiles','action' => 'view'),
    array('id'=>'[0-9]*', 'lang'=>'fr','firstName'=>'[^-]*','lastNAme'=>'[^-]*','profile' => $util->keywords['profiles'][0]['fr'], 'pass' => array('id', 'lang'),'profile' => $util->keywords2['profiles'][0]['en'])
)

;
As you can see in the last example I have passed 2 parameters to the controller through 'pass' => array('id', 'lang')

Remote controller name from CakePHP URL


IMAP preauth with Dovecot

Question: What's the command line for preauth IMAP using Dovecot? Many sites give:
dovecot --exec-mail imap

But on my system this returns:
Usage: dovecot [-F] [-c <config file>] [-p] [-n] [-a] [--help] [--version]
       [--build-options] [reload] [stop]
Fatal: Unknown argument: --exec-mail

Comment: Possible duplicate of [How to make dovecot not ask passwords from localhost?](https://serverfault.com/questions/165862/how-to-make-dovecot-not-ask-passwords-from-localhost)
Answer: dovecot --exec-mail imap

is not a valid command line switch in recent releases of Dovecot. There is now a separate binary named simply "imap" which launches a pre-authenticated IMAP session.
Source of information: Dovecot's upgrading to 2.0 instructions
On Ubuntu, this binary is not in the default path, it's located at /usr/lib/dovecot/imap

IMAP preauth with Dovecot


How to define the note frequency from spectrogram?

Question: because when I press for example on a piano key, that I trace the spectrum of the sound, I have this (amplitudes in function of frequencies)

Question: how to define the fundamental frequency of the note?
Is this

A) F0 because it is any sound emitted the lowest (less than 1 Hz)

B) F1 because it is the most serious peak, even if the peak is rounded

C) F2 because among the highest peaks (only the very high peaks are taken into account), it is the most serious

D) F3 because it is the strongest peak
Comment: There is a related Q&A at the Digital Processing SE: [Finding pitch from a wideband spectrogram](https://dsp.stackexchange.com/q/414)
Comment: Regarding rounded peaks, consider that most frequency plots like this have a log scale for the frequency axis.  This is useful in a music production context, since the low end is where things tend to get crowded and muddy, making more resolution there valuable.  It does, however, tend to skew the perspective of the 'strength' of each peak, as peaks will get wider and shorter on the graph at lower frequencies for the same peak width in absolute frequency terms.
Answer: If we assume that this is a harmonic sound (which is a good enough assumption for pianos) and that this is a spectrum of only one note being played, then the fundamental frequency n will be the highest frequency such that F1 = a1n, F2 = a2n, F3 = a3n, ..., where a1, a2, a3, ... are all positive integers.  (In other words, n is the greatest common divisor of F1, F2, F3, ...)
For example, if we were given a plot with F1 = 200Hz, F2 = 300Hz, F3 = 500Hz, F4 = 600Hz, then we could say pretty confidently that the fundamental is 100Hz, since the peaks are at 2*100, 3*100, 5*100, 6*100.
One way to make a guess at n is to look at the difference between two peaks (e.g. 600Hz-500Hz = 100Hz).  There's a pretty good chance that this will be the fundamental, but you have to go back and verify that your guess is right...  It's possible for tones to be missing harmonics (The example I gave here is missing the 400Hz harmonic, so you might guess that the fundamental is 200Hz, which is not right).
(And if you were given a plot with F1 = 201Hz, F2 = 297Hz, F3 = 499Hz, F4 = 602Hz, you would conclude that the fundamental is still 100Hz but there's some measurement error, or the tone isn't quite perfectly harmonic... Most of these plots are not precise enough for tuning)
Comment: It's not uncommon for the even harmonics to be missing, in which case the fundamental is half the difference.
Comment: This is a good answer in that it gets to the heart of what makes a harmonic sound harmonic.  The only thing missing IMO is the phrase "[greatest common divisor](https://www.wolframalpha.com/input/?i=gcd+200%2C+300%2C+500%2C+600)".
Comment: Essentially, I used a definition of "greatest common divisor"... But yes, I'll add that term in here.
Comment: I think this previous answer has links to a more accurate formula taking into account inharmonicity using for example string tension and width https://music.stackexchange.com/a/112009/60885.
Comment: @Emil The inharmonicity for the first few harmonics of a piano is low enough that it's just not worth solving a few fourth-order differential equations to find the fundamental.  Never mind the data collection required to fill in the coefficients...
Comment: @Edward: I think it was just a corrective factor with a square root and some material properties, no need to solve PDEs.
Answer: Your diagram is not very well drawn and I would refrain from drawing a conclusion based on it.  That said, it does look like your higher frequencies are evenly spaced.
Your descriptions of F0 (non existent) and F1 (serious?) are misleading.  Why is F1 "serious"?
You also claim that F2 is highest and F3 is "strongest", what's the difference?  High = strong in spectral analysis.
Based only on the data provided you may not be able to tell what the fundamental is.  Perhaps you have 6 distinct fundamentals created by pure tone generators.
You state that this is a piano key being played.  Each key in an acoustic piano strikes 3 strings, so there is no way you are going to get a pure spectrum for a single string.  Of course the multiple strings are tuned to complement each other and reinforce harmonics.
In general, the fundamental would be the common difference between the peaks in the sequence.  It looks like F3-F2 = F4-F3 = F5-F4 = F6-F5 so I would say that this is the fundamental.  Just based on appearances this delta does NOT line up with F1 so I can't tell if that is the true fundamental.
It is rather common for harmonics to be missing so you may need more information that just consecutive differences to determine the true fundamental.
Also, it is very common for higher harmonics to be stronger than the fundamental so the strongest peak should never be assumed to be the true fundamental.  In fact the brain has a signal processing feature called fundamental tracking that will cause a listener to hear the fundamental even when it's missing as long as there is enough data in the harmonics present for the brain to determine a common delta.
Comment: Although most keys on a piano correspond to 3 strings, the F1 key will have only 1 or 2 on most pianos.
Comment: Thank you.  I knew most had more than one but I'm not that well versed on piano construction.
Comment: The question doesn't actually claim that F2 is highest, only that it's among the highest peaks.
Comment: But it then claims it is the most serious, not among the most serious.  Very confusing.


Phoenix/Elixir: How to set the action in a test connection with Plug.Test.conn()?

Question: I wrote a little plug that accepts a list of actions as options. When the action that is currently called is in this list, the plug will behave differently.
For testing this I need to set the action in my unit tests. Is this possible? I didn't find anything in the docs.
This is the short example given in the Docs of Plug.
defmodule MyPlugTest do
  use ExUnit.Case, async: true
  use Plug.Test

  @opts AppRouter.init([])

  test "returns hello world" do
    # Create a test connection
    conn = conn(:get, "/hello")

    # Invoke the plug
    conn = AppRouter.call(conn, @opts)

    # Assert the response and status
    assert conn.state == :sent
    assert conn.status == 200
    assert conn.resp_body == "world"
  end
end

Comment: Can you clarify what you mean by an action?
Comment: Do you mean this `conn = put_private(conn, :phoenix_action, :action_name)` (replace :action_name with the action's name)?
Comment: If not, could you post the source of the Plug? I'm not sure I understand the question.
Comment: @Gazler I mean a controller action (new, create, index, etc). When I pass the option `except: [:create, :new]` into the plug, it shouldn't do some checks when the action is either `:create` or `:new`. So for testing this I need to be able to call a specific action in my tests.
Comment: @Dogbert Thank you, that did the trick!
Comment: @Dogbert It is a contribution to a public repo. I'm not sure if they will accept my PR. But I can post a link in a second.
Answer: I would consider integration testing these in your controller tests. Since the conn.private storage is designed for libraries, it is liable to change at any time.
If you are not concerned about it changing in Phoenix, then you can do something like:
conn =
   conn(:get, "/hello")
   |> put_private(conn, :phoenix_action, :index)
   |> AppRouter.call(conn, [:index])


How to get the height of a div that is expandable & collapsible

Question: Hope to get some help on this, I'm no expert on jQuery so bear with me.
I have 2 expandable/collapsible
's containing dynamic search refinement links, the default collapsed state shows the first 12 links with a 'show more' toggle button which when clicked expands the
 to reveal the full set of links.
I need to know the height of these
's which I can get like this:
var heightRefLinks = $('.search-refine').outerHeight(true);

But this only captures the collapsed height prior to the 'show more' toggle button being clicked, how do I get the expanded height also?
The reason I need to do this is because I have a toolbar element which 'sticks' to the top of the viewport once you've scrolled to it, the toolbar is only required to 'stick' to the viewport whilst the search results listings are in view, once they're not in view then the toolbar becomes 'unstuck' from the viewport. In order to 'unstick' I have to set a px value for the plugin option: bottomBound which is the height in px from the bottom of the viewport to the bottom of the listings. I have a few elements underneath the listings and they all have static heights so it's no bother getting the 'unstick' behaviour to work but then came the aforementioned expandable/collapsible
's.
EDIT: Included the jQuery which uses this plugin: http://themousepotatowebsite.co.za/introducing-the-stick-to-top-plugin/
// get the heights of various elements
var heightToolbar = $('.sticky-panel-toolbar').outerHeight(true);
var heightContentMeta = $('.property-listing-meta').outerHeight(true);
var heightLastPropItem = $('.property-listing:last-child > .property-tile:last-   child').outerHeight(true);
var heightFooter = $('.footer').outerHeight(true);
// set bottom gaps
var bottomGap = heightFooter + 32;
var bottomGapToolbar = heightToolbar + heightFooter + heightContentMeta +    heightLastPropItem;

// 'Toolbar - Search Results' version
$('.sticky-panel-toolbar-search').stickToTop({
bottomBound: bottomGapToolbar,
onStick: function() {
    $(this).addClass('stuck');
},
onDetach: function() {
    $(this).removeClass('stuck');
}
});

heightContentMeta is what I'm struggling with as this is the container
 for everything that comes after the search results listing and within this
 are the 2 expandable/collapsible
's. I also have a Google Adwords injected  in there also which I'm also having trouble getting the height but I wanted to focus on the expandable/collapsible
's first.
Comment: Call the same code when the element is expanded/collapsed, perform any calculations you need to, and then update the `bottomBound` value for the plugin.
Answer: This should give you the height of the content of the element.
$(".search-refine")[0].scrollHeight

DEMO
Comment: Thanks, I'll give this a go & if it works I'll accept this is my answer.
Comment: Thanks for setting up the demo, `scrollHeight` is good to know. It's not working unfortunately. Let me explain more how the expandable/collapsible ``'s are working: the default visible collapsed state is 1 `` that holds the 0-12 links then there's the 2nd `` that holds all links which is in the source but hidden with `display: none;`, I'm then using jQuery's `slideUp` & `slideDown` effects to collapse/expand the ``'s via the injected toggle button.
Comment: You should update your question with code instead of trying to explain it.
Comment: Nice one for toggle purposes starting in a collapsed state .. Thanks


Object references an unsaved transient instance - save the transient instance before flushing Hibernate

Question: I'm using Seam Framework. I have 2 Entity:
Request.java
@Entity
@Table(name = "SRV_REQUEST")
public class Request {

private Long id;

@Id
@Column(name = "ID_")
public Long getId() {
   return id;
}

and RequestEvent.java
@Entity
@Table(name = "SRV_REQUEST_EVENT")
public class RequestEvent {

private Long id;
private Request request;

@Id
@GeneratedValue
@Column(name = "ID_")
public Long getId() {
   return id;
}

@ManyToOne
public Request getRequest() {
   return request;
}

When I do this transaction:
Request request = new Request();
// I have to set ID manually
request.setId(12345);

entityManager.persist(request);

RequestEvent event = new RequestEvent();
event.setRequest(request);

entityManager.persist(event);

I got this error:
object references an unsaved transient instance - save the transient instance before flushing: kz.gov.mci.ipsc.services.RequestEvent.request -> kz.gov.mci.ipsc.services.Request

Comment: I guess adding entityManager.flush() after entityManager.persist(request) is not an option
Answer: try this
    Request request = new Request();
    // I have to set ID manually
    request.setId(12345);

    entityManager.persist(request);

    entityManager.flush();//this point is important

    RequestEvent event = new RequestEvent();
    event.setRequest(request);

    entityManager.persist(event);

Answer: try to add {CascadeType.PERSIST, CascadeType.MERGE} on getRequest method
Comment: After adding this I got this error: ERROR: duplicate key value violates unique constraint "srv_request_pkey"
  Detail: Key (id_)=(2000703891) already exists. However in the database there is no such request entry.
Comment: I guess if you wanna set Id manually you need flush(Save your entity before assign it)
Comment: Use entityManager.flush().
Comment: add  {CascadeType.PERSIST, CascadeType.MERGE} and remove first persist


nginx uLimit 'worker_connections exceed open file resource limit: 1024'

Question: I keep getting this error in nginx/error.log and its driving me nuts:
8096 worker_connections exceed open file resource limit: 1024

I've tried everything I can think of and cant figure out what is limiting nginx here. Can you tell what am I missing?
nginx.conf has this:
worker_processes 4;
events {
        worker_connections 8096;
        multi_accept on;
        use epoll;
}

I changed my system's Ulimit in security/limits.conf like this:
# This is added for Open File Limit Increase
*               hard    nofile          199680
*               soft    nofile          65535

root            hard    nofile          65536
root            soft    nofile          32768

# This is added for Nginx User
nginx           hard    nofile          199680
nginx           soft    nofile          65535

It was still showing the error. So I also tried editing /etc/default/nginx and added this line:
ULIMIT="-n 65535"

It is still showing the same error. Can't figure out what is limiting the nginx worker connection to only 1024. Can you point me out?
I've got Debian 7 + nginx
Answer: Set worker_rlimit_nofile 65535; in nginx.conf within the main context.
Comment: @Xavier this did removed the error msg, but can you explain why this works without changing ulimit as mentioned in the answer below? google searches tell to change ulimit in limits.conf or the systcl.conf, but none works for me.
Comment: Thats it! That fixed it. Oh you are a saviour. It works now even when the ULimit is not manually set in `/etc/default/nginx file`. Awesome. Thank you @Xaviour
Comment: well done Xavier.
Answer: Become the user:
su - nginx

Check the limits:
ulimit -Hn
ulimit -Sn

Edit the number of files the file system will let you have open:
vi /etc/sysctl.conf
fs.file-max = 70000

load your changes:
sysctl -p

See if that helps.
Comment: I am using init and havent installed systemctl. Would that make a difference?
Comment: When I changed to Nginx user, the ulimit -Hn is showing correctly there. I then checked `init.d/nginx` and it checks if ULIMIT is set in default folder (where it is set already) and then its supposed to set that value but it doesnt: `Check if the ULIMIT is set in /etc/default/nginx`
Comment: After changing file-max and as soon i run `sysctl -p` ubuntu 18.04.2 hangs, throws too many files open and doesn't boot, had to remove the code in secure boot to make the OS boot again.


Definition of a confidence interval

Question: In one exercise of a mathematical statistics lecture, the teaching assistant wrote the following :

A confidence interval for a given parameter $\theta$ is an interval
[A,B] at level $\alpha$ such that : $$ P(A < \theta < B) = 1 - \alpha
 $$

However I'm skeptical about that definition. I believe that either theta lies in this interval or it does not. According to my understanding, the only thing which could be told about $\theta $ is that it is equal to its true value with probability 1 and equal to any other value with probability 0.
Reading about confidence interval, I came across the following quote from Neyman :

"It will be noticed that in the above description, the probability
statements refer to the problems of estimation with which the
statistician will be concerned in the future. In fact, I have
repeatedly stated that the frequency of correct results will tend to
α. Consider now the case when a sample is already drawn, and the
calculations have given [particular limits]. Can we say that in this
particular case the probability of the true value [falling between
these limits] is equal to α? The answer is obviously in the negative.
The parameter is an unknown constant, and no probability statement
concerning its value may be made..."

How can one properly define a confidence interval then ?
Comment: I think if you put a hat over theta, then the TA gave you the general recipe for calculating a CI. It's very common that folks will not be precise about the random estimator and the population parameter, which is a constant. But that is not the correct definition or the interpretation of a CI, which you have correct.
Answer: The Confidence Interval (CI) definition the OP has provided is more or less the working definition - perhaps not the most rigourous one if we were to involve samples, but this form is used in general.
However, one should note that
The CI is random, not the parameter
The population parameter $\theta$ is a fixed, unknown constant. It is by definition the true value, which is technically stronger than OP's understanding that "it is equal to its true value with probability 1 and equal to any other value with probability 0."
What is random is the interval bounds $A$ and $B$. This question contains a lengthy discussion on this topic, but I don't think it is a duplicate due to the point below, which I believe is where the confusion arises in this question.
The definition is/should be a statement on the overall procedure, not a probability result on one estimation
For one estimation procedure, once we calculated the interval the OP is more or less in the right thinking that

either theta lies in this interval or it does not

which is supported in Neyman's quote in the question [1]. However, this is not the intended level of view where we make such probability statement [2] - it should be viewed from a meta level (i.e. across many estimation procedures) instead.
In other words, the definition is (or should be) saying that if one repeats the estimation procedure (not necessarily based on the same data or the same $\theta$) many times, around $1-\alpha$ of the times the calculated CI $(A, B)$ will cover $\theta$. It says nothing about one particular estimation procedure.
Neyman has written the following after what the OP quoted (pp. 349-350 of [3], emphasis mine, variables renamed to match what's in the question):

The theoretical statistician constructing the functions [$A$] and [$B$], [...] may be compared with the organizer of a game of chance in which the gambler has a certain range of possibilities to choose from while, whatever he actualy chooses, the probability of his winning and thus the probability of bank losing has permanetly the same value, $1-\alpha$.
The choice of the gambler on what to bet, which is beyond the control of the bank, corresponds to the uncontrolled possibilities of [$\theta$] having this or that value. The case in which the bank wins the game corresponds to the correct statement of the actual value of [$\theta$]. In both cases the frequency of "successes" in a long series of future "games" is approximately known. On the other hand, if the owner of the bank, say, in the case of roulette, knows that in a particular game the ball has stopped at the sector No. 1, this information does not help him in any way to guess how the gamblers have betted. Similarly, once the sample [...] is drawn and the values of [$A$] and [$B$] determined, the calculus of probability adopted here is helpless to provide answer to the question of what is the true value of [$\theta$].

[1] More rigourously it should be "the interval either contains theta or it does not", which hopefully implies the interval is the moving part, not theta. Ah, the nuances in English.
[2] In fact, no such probability statement can really be made from a frequentist perspective.
[3] J. Neyman (1937) Outline of a Theory of Statistical Estimation Based on the Classical Theory of Probability. Philosophical Transactions of the Royal Society of London. Series A, Mathematical and Physical Sciences, 236:333–380. http://doi.org/10.1098/rsta.1937.0005
Comment: Thanks for your thorough answer !

Definition of a confidence interval


EXECUTE IMMEDIATE not working with INSERT in bigquery

Question: I am trying to run this following code:
EXECUTE IMMEDIATE "INSERT INTO `bombora_surge.company_intent_history` (RowKey,?) VALUES ('sample',?)" USING "1",2;

But I am continuously getting the following error:
Invalid EXECUTE IMMEDIATE sql string `INSERT INTO `bombora_surge.company_intent_history` (RowKey,?) VALUES ('sample',?)`, Syntax error: Unexpected "?" at [1:19]

How do I resolve this?
Comment: Why are you giving a `?` as a column name, as in `(RowKey,?)`?
Comment: you need to back-quote the `?` like `(RowKey, \`?\`)` if you want to use `1` as a column name.
Answer: Posting this as a wiki for a better visibility for the community:
as @Jaytiger suggests you can use back-quote for the question mark symbol as it will recognise it as a column name and not as a place holder for execute immediate.

you need to back-quote the ? like (RowKey, ?) if you want to use 1 as a column name.

Good reference:
https://cloud.google.com/bigquery/docs/reference/standard-sql/procedural-language#execute_immediate


I want to output multiple triangles side-by-side but they all appear on top of each other

Question: There's an exercise that wants me to output as many triangles side-by-side as the number inputted. So my code looks like this:
public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int triangles = in.nextInt();
    int i, j, k;
        for (int n = 1; n <= triangles; n++) {
            for (i = 1; i <= triangles; i++) {
                for (k = 1; k <= triangles - i; k++) {
                    System.out.print(" ");
                }
                for (j = k; j <= triangles; j++) {
                    System.out.print("*");
                }
                for(int l = triangles - 1; l > k - 1; l--) {
                    System.out.print("*");
                }System.out.println("");
            }
        }

Input 5 and the output is five triangles with five lines each, but they all come out on top of each other.
Am I doing something wrong?
Answer: Here goes one ugly mofo (that works):
public static void main(String[] args) {
    int triangles = 5;

    //initialize column count
    int columns = triangles * 2 - 1;
    int[] starsPerRow= new int[triangles];

    //how many stars in each row
    for (int i=0; i<triangles; i++) {
        starsPerRow[i] = i*2+1;
    }

    //create a triangle "template". only one triangle map
    char[][] triangeMatrix = new char[triangles][columns];
    for (int i=0; i<triangles; i++) {
        for (int j=0; j<(columns - starsPerRow[i])/2; j++) {
            triangeMatrix[i][j] = ' ';
        }
        for (int j=0; j<starsPerRow[i]; j++) {
            triangeMatrix[i][j + (columns - starsPerRow[i])/2] = '*';
        }
        for (int j=0; j<(columns - starsPerRow[i])/2; j++) {
            triangeMatrix[i][j + (columns + starsPerRow[i])/2] = ' ';
        }
    }

    //print triangle map n times
    for (int i=0; i<triangles; i++) {
        for (int j=0; j<triangles; j++) {
            for (int k=0; k<columns; k++) {
                System.out.print(triangeMatrix[i][k]);
            }
        }
        System.out.println();
    }

}

Comment: Not sure I'm getting it, but I'll figure it out... thanks!


Get a file from remote login with known address

Question: I haved ssh-ed to a remote cluster and figured out an address: file://localhost/archive/path/to/the/file/filename.something. How can it I download over the network? Also please explain what such as address means opposed to something like: /home/somedir/path/to/the/file/filename.something. Thanks
Answer: scp
You can use scp(OpenSSH secure file copy) to download or upload files between your host and remote. just assume your remote ip is 184.108.40.206
copy from host to remote:
upload directory /root/lk to remote's directory /home/lk/cpfile
scp -r /root/lk email@example.com:/home/lk/cpfile

copy from remote to host:
download remote's /home/lk/to your host's /root:
scp -r firstname.lastname@example.com:/home/lk /root

other tools
If you are using tools like xshell, there are some integrated tools with interactive GUI, like rz(upload) and sz(download), see https://blog.actorsfit.com/a?ID=00850-983aedfb-0a2e-425d-8fce-f54197b12caf


SAP Business Objects Cross Table Data Duplication

Question: I'm using Business Objects to construct a simple report on whether a unit is on or off for a given day. When constructing a vertical table, the data is correct and looks like such:
<code>Unit ID | Status | Date
1       | On     | 2016-09-10
1       | On     | 2016-09-11
1       | Off    | 2016-09-12
2       | Off    | 2016-09-10
2       | Off    | 2016-09-11
2       | On     | 2016-09-12
</code>
However the cross table I've created, with columns of "date" and rows of "Unit ID" is duplicating Unit ID and having an entire row of 'On' followed by an entire row of 'Off' like:
<code>____| 2016-09-10 | 2016-09-11 | 2016-09-12
1   | On         | On         | On
1   | Off        | Off        | Off
2   | On         | On         | On
2   | Off        | Off        | Off
</code>
instead of what it should be as:
<code>____| 2016-09-10 | 2016-09-11 | 2016-09-12
1   | On         | On         | Off
2   | Off        | Off        | On
</code>
Any suggestions as to why it's doing this?
The table isn't particularly useful if it has these duplicate rows and I can't understand why it's resulting in this odd table.
Comment: Could you update the question with the three objects' definitions? It would be helpful to know what type (dimension, measure) as well as datatype they are and what formula is behind them (if any).
Comment: It depends on what the key is (primary/natural or the pivot) and how you are constructing the query, but the first result looks like a cartesian "cross"/"full outer" join - which you did name it as ("cross table"). Similar scenario here http://stackoverflow.com/q/21845564/16391
Comment: I've posted an answer as to what happened. The Status field needed to be a measure
Answer: Turns out what happened is the "Status" field was a dimension type, but the cross table requires the data field to be a measure type. Simply making a new variable that was a measure equal to "Status" solved the issue.


htaccess to remove exact match of index with no extension

Question: Seems straight forward, but I'm stuck...  My .htaccess looks like this
RewriteEngine On

// stop folder access
Options -Indexes

// force https
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]

//
// make all requests append php ext. ie /page = /page.php
RewriteRule ^([A-Z0-9a-z\-]+)$ $1.php [L,NC,QSA]

// redirect /home to /
RewriteCond %{REQUEST_URI} ^/(home.php)$
RewriteRule ^(.*)$ https://example.com [R=301,L]

// this is where im stuck!!! make index(no file extension) redirect but match exactly so indexn or indexnth wont redirect
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /index [NC]
RewriteRule . https://example.com/ [R=301,L]

// make index.php redirect to /
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /index\.(php|html) [NC]
RewriteRule ^(.*)$ https://example.com/ [R=301,L]

// push all processed requests through index.php just exclude the css|images|js|fonts folders
RewriteRule ^(css|images|js|fonts)($|/) - [L,QSA]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?path=$1 [NC,L,QSA]

In a nutshell, It works almost exactly as I want but for some reason it won't match https://example.com/index exactly (no file extension). If you put https://example.com/index{anythingelsehere} it treats it the same as https://example.com/index.
I want to only redirect the exact match of https://example.com/index.
Comment: Both problem and solution require heavy use of regex so it is pertinent to use that tag here.
Comment: @MrWhite: Thanks for restoring original tags. It is strange folks are removing tags. Also may I bring your attention to these close votes suggesting question doesn't belong to SO. I have added a comment above showing otherwise. This has been discussed again and again and it has been settled already that most of the rewrite rules are created and maintained by developers of the web applications/frameworks.
Comment: As per [this meta post](https://meta.stackoverflow.com/questions/283057/mod-rewrite-questions-getting-migrated-to-sf) and [this meta post](https://meta.stackoverflow.com/questions/283033/are-htaccess-questions-ever-on-topic-at-so) this question is not at all off-topic for SO so close vote is wrong.
Comment: A regex like `^/index` matches anything that simply _starts_ with `/index` (followed by anything). _Aside:_ You've used `//` to delimit your comments, however, this is not valid on Apache and will break _horribly_ - did you change this just in your question?!
Answer: Have it like this:
# stop folder access
Options -Indexes
RewriteEngine On

# force https
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]

# redirect index.php to /, /foo.php to /foo, /home.php to /, /index to /
RewriteCond %{THE_REQUEST} \s/+index\s [NC,OR]
RewriteCond %{THE_REQUEST} \s/+(.*?/)?(?:index|home|(\S+?))\.(?:php|html)[/\s?] [NC]
RewriteRule ^ /%1%2 [R=301,L,NE]

# make all requests append php ext. ie /page = /page.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^(.+?)/?$ $1.php [L]

# push all processed requests through index.php just exclude
# the css|images|js|fonts folders
RewriteRule ^(css|images|js|fonts)($|/) - [L,NC]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?path=$1 [L,QSA]


Possible to estimate distribution around mean given #samples, mean, highest and lowest?

Question: For a project for which there are multiple bidders, the following is known:

Number of bidders: 24
Mean bid: 104
Highest bid: 356
Lowest bid: 20

Given the above, is it possible (however roughly) to estimate (i) the number of bids above and below the mean and (ii) the median?
Comment: Not necessarily, if the other 22 values can be anything within that range.
Comment: by *not necessarily*, you mean not likely, right?
Answer: No. There is not enough information in the descriptive statistics you have provided to estimate 1) number of bids above and below mean and 2) median.
For 1), you need information regarding the overall shape of the distribution. At the very least you'd want information regarding whether the distribution is symmetrical around the mean or not.  This information could be expressed as a Bernoulli trial: $p = Pr(x > \bar x )$.  Obviously, if you knew $p$, you could multiply it by the total number of bids to estimate the number of bids above the mean, and the subtract from the total number of bids for the reverse.
Are $x_{min}$ and $x_{max}$ informative regarding $p$?  Not sufficiently informative, unfortunately. (EDIT: they do provide a sliver of information that allow you to rule the most extreme estimates for 1). But in most cases, this sliver of information is not very useful.)
For 2), you also need information regarding the overall shape of the distribution.  For example, it would help to know the number of modes and their positions, and some information about the skew of the distribution.

If you have out-of-band information (e.g. from simulations) regarding the shape or type of distribution (e.g. Beta distribution) then you can combine this prior information with these descriptive statistics to estimate 1) and 2).
Comment: It's not true that there's *no* information available here. For example, we know that the number of bids below the mean is greater than 1; if the other 22 observations were each $104 + \varepsilon$, the mean would be $\frac{22}{24}(104 + \varepsilon) + \frac{20}{24} + \frac{356}{24} = 111 + \frac{11}{12}\varepsilon$. It is true that without some assumptions on the distribution we can't say much about the probabilities other than where they must be 0.
Comment: @Dougal - You are correct.  MIN and MAX provide a *sliver* of information, but as you say that information isn't very useful most of the time.
Comment: @MrMeritology I see, thanks. I would have thought that given that the highest bid is a lot higher than than the mean than the lowest was lower than the mean, that we might be able to infer that the majority of the bids were above it. But like you say, if we don't have any information to make this inference, so be it.


Interpretation of partial autocorrelogram function

Question: The partial autocorrelogram function for the time series I am working with shows a significant spike at lag 1 and a minor one at lag 3. For another time series, it shows the significant one also at lag 1 and another one at lag 6. How do I interpret this in terms of the time persistence of the series?
Comment: post your data.
Comment: World
3.938778488
3.940091294
4.209060429
6.806065336
6.289135202
7.206773191
7.040203117
7.006369822
9.422525827
14.78167006
12.08543594
11.85049286
6.096991494
8.274836551
10.90349004
13.18041154
20.17498689
29.03911562
36.56050186
46.19967533
46.8956634
38.23858744
38.48410819
44.91172889
52.64530876
65.11802409
70.5930687
83.71220182
119.497105
187.510739
205.0370008
103.1435646
82.19722524
88.96659363
145.0188001
131.0793709
218.0340534
340.8520813
270.3304434
174.3270871
216.1603205
247.105952
198.7762798
Comment: I cannot copy and paste the charts. It might be because I am using XLSTAT...
Comment: Is the seasonality is 1?
Answer: The data has a major change(maybe you should include a causal that explains the large bumps in the data?) and the model before period 19 is different after period 19.  This will "cloud" your ACF/PACF.  If you use the Chow test you can identify a break in the model and then using the last 25 observations, a difference model with an outlier at period 38. I ran this with Autobox(I am affiliated).
[(1-B1)]Y(T) = +[X1(T)][(1-B1)][(+ 96.6698)]   :PULSE            38
                +          +   [A(T)]
Comment: Many thanks. I downloaded the trial version of Autobox a few weeks ago but it gave me a lot of problems and had to desinstall it. Do you recommend applying the Chow test assuming that the breaks are in period 19 and 38? Thanks again
Comment: Did you send an email or call?  I will say not.  FYI:You need to be installed as an admin....otherwise it won't work.  There is just one break being identified.  The period 38 is just an outlier.
Comment: No, I did not as I am pressed for time. It interfered with excel downloads. Thanks for the clarification on the admin issue and on the break point.


Save canvas in client side

Question: JavaScript
if (!window.Clipboard) {
   var pasteCatcher = document.createElement("apDiv1");
   pasteCatcher.setAttribute("contenteditable", "");
   pasteCatcher.style.opacity = 0;
   document.body.appendChild(pasteCatcher);
   pasteCatcher.focus();
   document.addEventListener("click", function() { pasteCatcher.focus(); });
}

window.addEventListener("paste", onPasteHandler);

function onPasteHandler(e)
{
    if(e.clipboardData) {
        var items = e.clipboardData.items;
        if(!items){
            alert("Image Not found");
        }
        for (var i = 0; i < items.length; ++i) {
        if (items[i].kind === 'file' && items[i].type === 'image/png') {
            var blob = items[i].getAsFile(),
                source = window.webkitURL.createObjectURL(blob);

            pastedImage = new Image();
            pastedImage.src = source;

            pasteData();
            }
        }
    }
}

function pasteData()
{
    drawCanvas = document.getElementById('drawCanvas1');
    ctx = drawCanvas.getContext( '2d' );
    ctx.clearRect(0, 0, 640,480);
    ctx.drawImage(pastedImage, 0, 0);
}

DIV

Paste Test

Above javascript will capture image from clipboard and paste in the DIV. How do I save the canvas in clientside. I'm not using any server so i need to save the canvas in client side.
I found that canvas.toDataURL() will convert contents as a base64 encoded PNG file, but how do I do if i want the image save in my local. Let say, I have a folder Image in my C://. How do I do if i want the image saved in particular folder.
Answer: Just set an html img element's src to canvas.toDataURL()
Then right-click-save-as.
    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");

    ctx.fillRect(50,50,150,75);

    var theImage=document.getElementById("toImage");
    theImage.src=canvas.toDataURL();

Here's a complete example:
<!doctype html>

<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" />

    <canvas id="canvas" width=300 height=300></canvas>

Comment: where the image saved. How if i want to save in C://Images folder.
Comment: When you right click on the image, you will get a context menu.  One of the context menu options is "Save Picture As" (this wording will vary by browser).  Then navigate to your c:images folder and press the save button.  Browsers disallow programmatic saving of files to local system for security reasons, but most users are familiar with and comfortable with the right-click-save-as method of saving images to the local file system.
Comment: My user will paste the screen shot. I need to save automatically after user paste the image. If user right click and save, the image will saved in user's local. I want it to save server so the admin can retrieve back.
Comment: I'm confused...your question says "I'm not using any server so i need to save the canvas in client side".  Anyway, if you want to send the dataURL to a server, just do an AJAX post.
Comment: I'm sorry for confusion. Yeah I don't have any server (PHP or Perl). I need to save the image in Image folder in my HTML project.
Comment: How if I want to create save button and save the image
Comment: You can't do save image programmatically for security reasons.

Save canvas in client side


Overriding Exceptions in Java

Question: public class Student {

    checkAge (Student student) {
        try {
            if (student.getAge() > 18 ) {
                throw new CustomException("Student is older than 18 years.");
            }
        } catch (CustomException e) {
            handleException(e);
        }
    }

public class HandleException {
    public static sendToErrorReport (CustomException customException) {
        //trying to do something like this, but the below code throws an error.
        customException.setMessage(customException.getMessage() +" ; Student -> " + customException.getStudent().getStudentName);
    }
}

I've created a custom class for handling exceptions that occur in my project. My requirement is to change the message for the exception and append some data to the exception message and pass it to my custom class.
So essentially I need to edit the exception message once it has already been set.
Is there any way I can do this?
Comment: post an example code?
Comment: To understand correctly: (1) to catch an exception and rethrow an other exception, or (2) throw a child exception with an `@Override getMessage() { return super.getMessage() + ... }`?
Answer: you can override getMessage method of Exception class
class CustomException extends java.lang.Exception{

    @Override
    public String getMessage(){
        return super.getMessage() + "- My Message";
    }

}

Answer: In your code when it throws exception
try{
//Some code here
}catch(Exception e){
 throw new CustomeException("Your text here")
}

When you catch CustomeException in some other place you can modify same.
try{
//Some code here
}catch(CustomException e){
String message = e.getMessage();
//Do stuff with previous message
 throw new Custom2Exception("Your next text here")
}

Answer: Here is the full CustomException class which extends RuntimeException Class. You can define code and message.
public class CustomException extends RuntimeException {

    private String code;
    private String message;

    public CustomException() {
        super();
    }

    public CustomException(Exception e) {
        super(e);
    }

    public CustomException(String code, String message, Exception e) {
        super(message, e);
        this.code = code;
    }
}

Overriding Exceptions in Java


$\pm\infty$ versus neutral $\infty$ in extensions (compactifications) of $\mathbb R$

Question: One context in which a distinction between $+\infty$ and $-\infty$ is important is in things like
$$
\lim_{t\,\to\,+\infty} \frac 1 {1+e^t} = 0, \qquad \lim_{t\,\to\,-\infty} \frac 1 {1+e^t} = 1.
$$
However, with rational functions $f(x)$ one can write
\begin{align}
& \lim_{x\,\to\,\infty} f(x) = \ell \\[8pt]
\text{and } & \lim_{x\,\to\,c} f(x) = \infty
\end{align}
and one should make no distinction at all between $+\infty$ and $-\infty$. This makes these functions continuous everywhere including $\infty$ and $c$ (the point where there is a pole).
Similarly
$$
\lim_{\theta\,\to\,\pi/2} \tan \theta = \infty
$$
and there's no $\text{"}{\pm}\text{''}$ involved, so $\tan$ is continuous everywhere in $\mathbb R/\pi$ (the reals modulo $\pi$, a space in which there is no $\infty$ that $\theta$ could approach).
My question is: What amount of agreement or disagreement about the above exists among mathematicians?  (I find this disagreed with in a comment under this question.)
Comment: *Personally*, since there are two "canonical" compactifications of $\mathbb{R}$, I prefer to be explicit and call $+\infty, -\infty$ if I intend to use the two-ended and $\infty$ if the one-point. However, in a world where $\subset$ or $\subseteq$ is not agreed upon, I don't expect it to be well-agreed upon in this case either, and I think this question may be very difficult to answer precisely.
Comment: Note also that, in this issue, there are several kinds of people who use $\infty$ etc in their notations (mathematicians, engineers, calculus students etc) and many of them have different level of knowledge. For a calculus student, writing $f(\infty)$ may be okay and he isn't even aware of any rigorous step he has to take before doing so. For another calculus student, $f(\infty)$ is a blunder. How do you unify notation used across several fields for which interpretations can vary widely, with no hopes of good understanding?
Comment: Tangentially related: http://math.stackexchange.com/questions/233855/three-point-compactifications-of-mathbbr $\qquad$
Comment: Honestly if my answer isn't what you are  looking for, I would ask you too make question clearer. I really don't get what you want to know.
Comment: @Yaddle : I posted the question and I up-voted your answer. $\qquad$
Answer: As you may know you can make $\mathbb R$ and $\mathbb C$ compact by using the Alexandroff compactification (i.e. called Riemann sphere is the case $\mathbb C$). On this compactification you can define rational/meromorphic functions. In this construction we have $+\infty = -\infty$.
Like you noticed above you get $\lim_{t\,\to\,+\infty} \frac 1 {1+e^t} \neq \lim_{t\,\to\,-\infty} \frac 1 {1+e^t}$. So how does this fit in this construction?
The answer isn't too obvious, but well known in function theory. Let $\hat{\mathbb C} = \mathbb C \cup \{\infty\}$. If a function $f: \hat{\mathbb C} \to \hat{\mathbb C}$ has a pole in $c \in \mathbb C$ it holds that $\lim_{z \to c} f(z) = \infty$ with respect to the chordal metric. But why do we still get $\lim_{t\,\to\,+\infty} \frac 1 {1+e^t} \neq \lim_{t\,\to\,-\infty} \frac 1 {1+e^t}$?
The function $f: \hat{\mathbb C} \to \hat{\mathbb C}, z \mapsto \dfrac 1 {1+e^z}$ has no pole in $\infty$. If you consider the Laurent series of $f$ you will see, that $f$ has an essential singularity in $\infty$. But what do we know about these singularities? The Casorati–Weierstrass theorem tells us that for every $c \in \hat{\mathbb C}$ there exists a sequence $(z_n)_{n\in \mathbb N}$ with $\lim_{n \to \infty} f(z_n) = c$. So you basicly just found sequences for $c = 0,1$. That is nothing to worry about, there is just no limit in $\hat{\mathbb C}$ at $\infty$.
Hope that makes sense and helps you :)
Comment: I think you missed the point of the question.
Comment: I read the question now like three times. If that isn't what he was asking for, I really don't understand the question.


What is a magic function in C/C++ (in regards to OpenMP)

Question: Currently looking at this guide to using OpenMP with C/C++ programs and wonder what they mean by creating a magic function in the quote below:

Internally, GCC implements this by creating a magic function and
  moving the associated code into that function, so that all the
  variables declared within that block become local variables of that
  function (and thus, locals to each thread). ICC, on the other hand,
  uses a mechanism resembling fork(), and does not create a magic
  function. Both implementations are, of course, valid, and semantically
  identical.
Comment: The guide is not correct. ICC also performs function outlining the same way GCC does. The Intel OpenMP runtime even contains a GCC compatibility layer and can be used with programs compiled with GCC. The PGI compiler is the one that doesn't.
Comment: See [this answer](http://stackoverflow.com/a/18789429/1374437) for some insight.
Answer: A "magic" function is a function created by the compiler - its magicness comes from the fact that you as a programmer don't need to do anything, it's "magically done for you".


Write the Taylor expansion of order $2$ at $x=0$ of $h(x)=g^{-1}(x+\sin(x))$, for $g(x)=x\ln(2+x^2)$

Question: Can anyone tell me whether I carried out properly this exercise and where are mistakes? Thank you.
Let be $g: \mathbb{R} \to \mathbb{R}$ the function defined by:
$$g(x)\,=\,x\ln(2+x^2)$$

Show that $\exists \,\, \delta\gt0$ s.t. the function $g: \,(-\delta,\delta)\to g(-\delta,\delta)$ is invertible
Write the taylor polynomial of degree $2$ centered at $x=0$ of the following function:
$$h(x)\,=\,g^{-1}(x+\sin(x))$$

About the first point, basically we have to show that $g$ is injective in a neighborhood $(-\delta,\delta)$ of $0$. So $\,\,g(0)=0$, $\,\,\,\,\,\lim_{x\to +\infty}g(x)=+\infty\,\,$ and $\,\,\,\,\lim_{x\to -\infty}=-\infty$.
Moreover $g'(x)=\frac{2x^2}{2+x^2}+\ln(2+x^2)\,\,\gt0$,$\,\,\,\,\forall x \in \mathbb{R}\,\,\,\,$ so $g$ is monotonic and strictly increasing and $g\in C^{\infty}(\mathbb{R})\,\,\,$which prove that $g$ is a diffeomorphism.
From the theory, the taylor polynomial of degree $2$ centered at $x=0$ of $g$ is $$g^{-1}(y)=g^{-1}(0)+(g^{-1})'(0)(y-0)+\frac{(g^{-1})''(0)}{2!}(y-0)^2+\mathcal{o}(y-0)^2$$
Since $g(0)=0$ we have $g^{-1}(0)=0$
$(g^{-1})'(0)=\frac{1}{g'(0)}=\frac{1}{\ln(2)}\,\,\,\,$ and
$\,\,\,(g^{-1})''(0)=-\frac{g''(0)}{(g'(0))^3}=0\,\,\,$ since$\,\,g''(x)=\frac{4x(2+x^2)-2x^2(2x)}{(2+x^2)^2}+\frac{2x}{2+x^2}$
hence, in a neighborhood of $0$: $$h(x) \simeq \left(0+\frac{1}{\ln(2)}(x-0)-0+\mathcal{o}(x-0)^2\right)\left(x+x+\mathcal{o}(x)\right)= \frac{2x}{\ln(2)}+\mathcal{o}(x)^2$$
Answer: You are almost correct, in your result there is just an extra factor $x$.  At the last step you have to consider the composition, not the multiplication
$$h(x)=\left(0+\frac{1}{\ln(2)}(2x+o(x^2))-0+o(2x+o(x^2))^2\right)\\= \frac{2x}{\ln(2)}+o(x^2).$$
This is a shorter way based on the uniqueness of the Taylor expansion:
$$g(x)=x\ln(2+x^2)=x\ln(2)+x\ln(1+x^2/2)=x\ln(2)+o(x^2).$$
Let $h(x)=a+bx+cx^2+o(x^2)$, then
$$g(h(x))=a+b(x\ln(2)+o(x^2))+c(x\ln(2)+o(x^2))^2+o(x^2)\\
=a+b\ln(2)x+cx^2\ln(2)+o(x^2)$$
On the other hand, $h(x)=g^{-1}(x+\sin(x))$ implies that
$$g(h(x))=x+\sin(x)=2x+o(x^2).$$
Therefore, by comparing the coefficients, we get $a=0$, $b=2/\ln(2)$, and $c=0$. Hence
$$h(x)=\frac{2x}{\ln(2)}+o(x^2).$$
Comment: @F.inc Well done!!
Comment: Yes, thank you! The multiplication was an oversight due to the rush


Server 2012 Internet printing - no connect button

Question: I have a Windows Server 2012 with Print Services installed and IPP (Internet Printing) enabled.
I can get to the page http://PrintServer/Printers without issue, but there is no connect button.
All of the other buttons are shown and can be clicked. I've tried IE11, Firefox, Chrome, and messed with the compatibility settings
Has anyone else run into this issue?
Also, the connection doesn't show on the server when I browse to the webpage.
Answer: If the Internet Explorer security is set to high, the Connect link on the Web management page for that printer is not displayed. This prevents users from connecting to the printer through the Web page. Please change the Internet Explorer security for test.
You also need to install the Internet Printing Client on the client machines and then restart the printer spooler service.  After that, the Connect button will show up when accessing to the IPP.
Hope this helps.
Answer: If I remember correctly, this does not work on IE11. IE10 seemed to show that button fine though. Can you try a machine with IE10 just to confirm?
Comment: Just to check - make sure that the IPP client is installed on your OS as well. By default, it should be installed under Programs and Features.
Comment: I'll try on an IE10 machine and let you know.  Also, I installed the IPP client as a feature on the server, is that what you meant ?
Comment: Something else I noticed. I currently have a Server 2008 R2 with IPP enabled and IE11 w/compatibility mode on can use it without any issues. I think this is a new issue with Server 2012.
Comment: Okay, we tried accessing the page with an IE10 client and still no connect button.


Sprite moves indefinitely in a direction or gets stuck in diagonals

Question: I am working on a gaming project with a base to help get me started. The base is overall extremely helpful, however there is a part of the code that confuses me as to how to manipulate correctly.
When this code is run, the player sprite will indefinitely move in a direction until the other key press is used. If a playerMoveY is added, it will get stuck moving in diagonals.
    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {

       if (e.KeyCode == Keys.Left)
        {
            playerMoveX = -1;
        }
        else if (e.KeyCode == Keys.Right)
        {
            playerMoveX = 1;
        }

Comment: I think a bit more code will be required to understand your issue. First, how do you use playerMoveX ? is it a delta ? if yes, are you setting it to 0 once your sprite has moved ? how do you use it ?
Comment: playerXPos = playerXPos + playerMoveX;
Answer: Without seeing your full code, it's going to be hard to say for sure, but it is probably because you don't have a KeyUp event to reset the move value.
Similarly to how you created a KeyDown event to use the Form1_KeyDown method, try something like this for KeyUp
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
   if (e.KeyCode == Keys.Left)
    {
        playerMoveX = 0;
    }
    else if (e.KeyCode == Keys.Right)
    {
        playerMoveX = 0;
    }
  }

Comment: Just keep in mind that if the player presses the left and right keys together and then releases one of them other key they will stop dead, this can happen if they are changing direction quickly from left/right etc. Movement control can be fiddly sometimes
Comment: I see this issue, especially now that I have added a Y axis and wish to move diagonally. What is the easiest way of amending this?


Properties of Lebesgue points of a function

Question: Let $F:\mathbb{R}^2 \rightarrow \mathbb{R}$ be such that for every $a,b \in \mathbb{R}$ the fuctions $F(a,\cdot), F(\cdot,b) \in L^1(\mathbb{R})$.
Consider the set $A:= \left\{a:\lim\limits_{r \rightarrow 0}\frac{1}{\mu{(B(a,r))}}\int_{B(a,r)}F(a,y) d y = F(a,a) \right\}$, where $\mu$ is the Legesgue measure on $\mathbb{R}$.
Is $\mu(\mathbb{R}/A)=0$?
P.S. By Lebesgue differentiation theorem for every $a\in \mathbb{R}$  the set of all Legesgue points of the function $F(a,\cdot)$ denoted by $A_a$ is measurable and satisfies $\mu (\mathbb{R} / A_a)=0$ .
The set $A$ defined above is also given by $A= \cup_{a\in \mathbb{R}} (A_a \cap \{a \})$.
But I am  unable to conclude the value of $\mu(\mathbb{R}/A)$
Any help would be greatly appreciated. Thanks in advance.
Comment: How is your $A_a$ defined?
Comment: Thanks. Updated the question
Answer: Try $F(x,y) = 0$ for $x\ne y$, $1$ for $x=y$.
Comment: I did not follow you. Is this a counter example?
Comment: @Veronica I think you get that $A=\emptyset$ in this example, which is why its a counter example to your statement.


LDA TopicModels producing list of numbers rather than terms

Question: Bear with me as I am extremely new to this and working on a project for a course in a certificate program.
I have .csv dataset that I obtained by retrieving bibliometric records from Pubmed and Embase databases. There are 1034 rows. There are several columns, however, I am trying to create topic models from just one column, the Abstract column and some records do not have an abstract. I've done some processing (removing stopwords, punctuation, etc.) and have been able to barplot words occurring more than 200 times as well as create a Frequent Term list by rank and can also run word associations with selected words. So, it seems r is seeing the words themselves in the Abstract field. My issue comes when I try to create topic models using the topicmodels package. Here's the bit of code I'm using.
#including 1st 3 lines for reference
options(header = FALSE, stringsAsFactors = FALSE, FileEncoding =
"latin1")
records <- read.csv("Combined.csv")
AbstractCorpus <- Corpus(VectorSource(records$Abstract))

AbstractTDM <- TermDocumentMatrix(AbstractCorpus)
library(topicmodels)
library(lda)
lda <- LDA(AbstractTDM, k = 8)
(term <- terms(lda, 6))
term <- (apply(term, MARGIN = 2, paste, collapse = ","))

However, the output of topics I get is the following.
Topic 1 Topic 2 Topic 3 Topic 4 Topic 5 Topic 6 Topic 7 Topic 8

[1,] "499"   "733"   "390"   "833"   "17"    "413"   "719"   "392"
[2,] "484"   "655"   "808"   "412"   "550"   "881"   "721"   "61"
[3,] "857"   "299"   "878"   "909"   "15"    "258"   "47"    "164"
[4,] "491"   "672"   "313"   "1028"  "126"   "55"    "375"   "987"
[5,] "734"   "430"   "405"   "102"   "13"    "193"   "83"    "588"
[6,] "403"   "52"    "489"   "10"    "598"   "52"    "933"   "980"

Why am I not seeing words here rather than numbers?
Furthermore, the following code, which I basically took from the r PDF on topicmodels, does produce values for me, but the topics are still numbers rather than words, and this is meaningless to me.
#using information from topicmodels paper
library(tm)
library(topicmodels)
library(lda)
AbstractTM <- list(VEM = LDA(AbstractTDM, k = 10, control = list(seed =
505)), VEM_fixed = LDA(AbstractTDM, k = 10, control = list(estimate.alpha
= FALSE, seed = 505)), Gibbs = LDA(AbstractTDM, k = 10, method = "Gibbs",
Control = list(seed = 505, burnin = 100, thin = 10, iter = 100)), CTM =
CTM(AbstractTDM, k = 10, control = list(seed = 505, var = list(tol =
10^-4), em = list(tol = 10^-3))))
#To compare the fitted models we first investigate the α values of the
models fitted with VEM and α estimated and with VEM and α fixed

sapply(AbstractTM[1:2], slot, "alpha")

#Find entropy
sapply(AbstractTM, function(x)mean(apply(posterior(x)$topics, 1,
function(z) - sum(z * log(z)))))

#Find estimated topics and terms
Topic <- topics(AbstractTM[["VEM"]], 1)
Topic
#find 5 most frequent terms for each topic
Terms <- terms(AbstractTM[["VEM"]], 5)
Terms[,1:5]

Any thoughts on what the issue might be?
Comment: Also some rows of the DTM will be all zeroes because some of the records don't have abstracts. These are probably represented in the Abstracts column as empty strings, and since they don't have terms all the term frequencies for these documents are zeroes. I would subset your data to remove the empty abstracts like this: `abstracts <-
 records$Abstract[records$Abstract != ""]`, then create the corpus and DTM.
Comment: Please provide [reproducible examples](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) when you're asking a question.
Comment: It's hard to tell without a reproducible example, but I suspect you are getting the documents in place of the terms. Have you tried using `DocumentTermMatrix()` instead of `TermDocumentMatrix()`?
Comment: Yes, I have tried that. For some reason, it produces a matrix with zero terms, thus I can't do anything with it. When I attempt to plot word frequencies with the TDM, I get a barplot of numbers instead of terms. What would you need for this to be reproducible? Again, I note I'm new to this so I don't fully understand. Do you mean ALL the code or more than that?
Comment: You can see more info on reproducible examples at the link Adam included, but the most important thing is a sample of the data. That way we can run the exact same code as you and see the results. Can you include the output of `dput(head(records$Abstract, 10))`, or a toy dataset that produces the same problem?
Answer: Reading the topicmodels documentation, it does appear that the LDA() function expects a DocumentTermMatrix, not a TermDocumentMatrix. Try creating the former with DocumentTermMatrix(AbstractCorpus) and see if that works.
Comment: This did work! However, I had to add a little code to get rid of empty entries in rows.