GSON not reading values correctly

Question: I'm trying to read this JSON:

And I can't seem to get it to work with GSON. I've used GSON successfully in the same project so I know how it works but I can't seem to get this JSON to work as intended. First in the class is rows, which is just an array of another class. The other class has three variables, a string named "code", a string named "name", and a array of another class called "statuses". However, I don't know how to put variables in this other class. It looks like an array but it's not. I cannot name a variable "0" in Java, so I looked that up (tried fixing it with Maps) but that did not work. How would you do this? It's weird because "statuses" always contains just that one entry, named '0', and the text is either "primary" or "secondary". Any help is appreciated.
I actually found this:

Still not really sure how to go about this.
Answer: Your Pojo design shoild be like this :-
<code>public class ResultOutPut  {

private List<Rows> rows;

// getters and setters

}

public class Rows {

private String code;

private String name;

private List<String> statuses;

// getters and setters

}
</code>
Comment: As your statuses array contains list of string so In rows List will be used. Use @SerializedName annotation on fields if your using ProGuard

GSON not reading values correctly


click and mouse event conflict in vuejs

Question: recently,i try to write a todo demo via vuejs,however,when i write the following code

                    <input type='checkbox' name='item_cbx' v-model="todo.checked" />
                    {{todo.content}}

//js
var todoList = new Vue({
    el:"#item_lists",
    data:{
        todos:[]
    },
    methods:{
        showDeleteBtn:function(index,event){
            event.stopPropagation();
            if(event.currentTarget.className!=="user_choice_item")
                return;

            var newState = Object.assign({},this.todos[index],{show:true});
            this.todos.$set(index,newState);
        },
        hideDeleteBtn:function(index,event){
            var newState = Object.assign({},this.todos[index],{show:false});
            this.todos.$set(index,newState);
        },
        deleteTodo:function(todo){

            this.todos.$remove(todo);
            return false;
        },

    }
});

it turns out that the only the mouseenter event can be triggered correctly, the click on "delete_btn" and change event on the checkbox ,the mouseleave event not triggered. however, when i remove the mouseenter event of the parent div. the child events work .i wanna know what causes this ..can anyone help me?
Answer: I think you may be working too hard at handling the event. Here's a snippet that does what I think you want it to do. The showDeleteBtn and hideDeleteBtn methods simply set the show data member of the todo item.

var todoList = new Vue({
  el: "#item_lists",
  data: {
    todos: [{
      content: 'Hi there',
      checked: true,
      show: false
    },
    {
      content: 'Another',
      checked: true,
      show: false
    }]
  },
  methods: {
    showDeleteBtn: function(index) {
      this.todos[index].show = true;
    },
    hideDeleteBtn: function(index) {
      this.todos[index].show = false;
    },
    deleteTodo: function(todo) {
      this.todos.$remove(todo);
      return false;
    }
  }
});
.delete_bt {
  background-color: lightblue;
  padding: 0.3em 1em;
}

    <input type='checkbox' name='item_cbx' v-model="todo.checked" />
    {{todo.content}}
    Delete

Comment: yes! i made it yesterday, and i found that it still works just by set the attr rather than the whole obj. however, i wanna know is there any method that can help me change some(more than one)attributes at a time?
Comment: You can change as many attributes as you want. They just need to be part of your viewmodel.

click and mouse event conflict in vuejs


Pass user_register form field values to Pardot for extra processing

Question: I need to pass the values submitted during registration to Pardot using a form handler.
How can I accomplish the task?
Answer: First you'd want to add an additional submit handler to your form...
function pardotpost_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'your_form_id_goes_here') {
    $form['#submit'][] = 'send_to_pardot';
  }
}

Then in your new submit handler you post the data to their form handler
function send_to_pardot(&$form, &$form_state) {
  $url = 'http://pardot.com/your/form/handler/url/goes/here';
  $data = $form_state['values']['submitted_tree'];
  $options = array(
    'method' => 'POST',
    'data' => http_build_query($data, '', '&'),
    'timeout' => 15,
    'headers' => array('Content-Type' => 'application/x-www-form-urlencoded'),
  );
  $result = drupal_http_request($url, $options);
}

Lastly you check $result for any errors.
Cheers
Answer: Add an additional submit callback to the form.
Answer: I have developed a module for this Pardot User Register
Advantage of using this module over adding additional submit callback is site builders / users can easily add the form handler URL in the Drupal admin interface. No coding work involved and the users can check Watchdog for any errors generated from this integration.
Please feel free to create an issue on the project page if you find any. I would be more than happy to fix or enhance the module provided it is a generic bug or suggestion.


O que é encriptação end-to-end?

Question: Ouço muito falar desse negócio de criptografia end-to-end porém eu não consigo entender muito o que seja por que ela é chamada de "opção mais segura para a privacidade". Eu possuo dúvidas e as enumerei, vejam:

O que é?
Como funciona?
Ela é inviolável?
Existe maneira de se trabalhar ela no PHP?
Suas vantagens e desvantagens
Answer: Normalmente o termo é usado fora do contexto de programação. Embora muitas vezes o que fazemos em uma aplicação, tipicamente web, tecnicamente seja parecido com a criptografia end-to-end, pela definição do termo é algo diferente. O termo é usado para indicar a segurança de tráfego de dados entre dois agentes particulares sem que tenha interferência de qualquer forma de terceiros.
Este end-to-end significa que a comunicação ocorre entre dois pontos finais. Isto é usado em e-mails e mensagens instantâneas, coisas que em geral não passam por um servidor ou se passam, apenas transitoriamente.
O termo não é usado quando um cliente se comunica com um servidor. Embora tecnicamente seja possível usar o PHP para fazer uma comunicação end-to-end, ele não costuma ser usado para isto.
Vamos dizer que você crie aplicativos que faça comunicação criptografada end-to-end passando pelo seu servidor PHP. Se a comunicação realmente é end-to-end, sua aplicação PHP nem precisa saber o conteúdo, ela lida apenas com dados genéricos. Ela não sabe se está criptografada ou não, não sabe o que tem ali. Se ela precisa e consegue saber, então você já não tem mais uma comunicação end-to-end.
E esse "consegue saber" pode ser direta ou indiretamente. Mesmo que a comunicação seja toda criptografada, se há alguma maneira de circundar isto, já estamos vendo uma falha e acho que o termo não poderia ser usado. Especialmente a troca de chaves para a criptografia pode se tornar problemática. E não vejo como resolver isto através de navegadores.
A vantagem dela é justamente não deixar intermediários interferiam no conteúdo. A desvantagem é que as duas pontas precisam garantir a comunicação segura por meios próprios e isto não é simples de fazer principalmente porque os usuários - em geral são leigos - precisam tomar providências que ele não entende e pode se equivocar.
Qualquer segurança é inviolável até que alguém viole. Como o termo é apenas um conceito e não uma tecnologia específica ele poderá ser mais ou menos inviolável de acordo com o que e como está sendo usado.
Vamos supor que você tenha uma aplicação JavaScript no seu celular e uma aplicação PHP no computador da sua casa. Ambos não estão comprometidos e possuem meios eficazes de criptografar os dados que eles trafegam entre si sem intermediários, eventualmente até por HTTPS. Acho que podemos dizer que o PHP foi usado para uma comunicação end-to-end. Tecnicamente acho que é E2E. Mas fazer isto não é típico, e nem é simples. E nem faz muito sentido, tem maneiras e tecnologias melhores para obter o mesmo ou melhor resultado.
Algumas tecnologias usadas para garantir comunicação segura end-to-end:

PGP
S/MIME
OTR
Tresorit

Todas são formas específicas de usar criptografia "tradicional". Elas trabalham na camada da aplicação. O usuário é responsável por fazê-las funcionar. Elas usam um aplicativo de um fornecedor, uma utilitário de criptografia de outro, um transporte de outro, um servidor intermediário, quando há de outro, um certificado de outro e o serviço de por tudo isto junto de mais um outro e que preferencialmente deve ser o próprio usuário. Todos eles devem ser confiáveis. Idealmente eles devem ser auditados publicamente. Um serviço como o Telegram parece resolver grande partes das dificuldades mas tem um problema, eles fornecem tudo o que é necessário. Você tem que confiar neles. Não pode ter nenhum back-door. E muitas empresas colocam, até para não ter problemas legais.
Toda a criptografia é feita entre as partes finais e mesmo que os dados criptografados passem por intermediários, até que se prove o contrário, eles não podem ter acesso aos dados planos nem por um momento mínimo para não ferir o conceito.
Duvido que seja possível com a tecnologia atual que páginas web padrões consigam fazer todo o processo por conta própria sem intermediários pelo menos para a troca de chaves.
É possível fazer aplicações para comunicação E2E usando outros protocolos ou mesmo protocolos web mas de forma diferente dos navegadores.
Provavelmente ainda precisaria de um servidor para colocar as duas pontas em contato, o que já é uma quebra de privacidade porque alguém saberá quem está contactando quem. Já pensou nisto? Privacidade e inviolabilidade E2E total é muito difícil de se obter mesmo na vida real.
Se os aplicativos nas pontas fornecerem todos os meios para fazer o resto da comunicação, trocarem chaves que podem ser autenticadas (precisa de certificado privado) sem que elas possam ser usadas para decifrar os dados trafegados por quem não é a ponta, é E2E.
Fazer um chat e garantir coisas que você não pode ou não sabe efetivamente garantir pode trazer problemas legais dependendo da forma como isto for vendido ao usuário final. Como garantir inviolabilidade sendo um intermediário? É possível mas não é simples implementar, especialmente usando tecnologias frágeis como scripts PHP e navegadores. Certamente não será confiável se for feito armazenamento no servidor de mensagens e chaves em banco de dados ou outras formas.
Não sou um especialista no assunto mas em linhas gerais é isto.
Tentando juntar todas as partes do assunto:

Transmitir informações sem passar pelo servidor
O que é criptografia end-to-end? Como aplicá-la?
Dados recebidos de HTTPS vem encriptado?
Como funciona a encriptação do Telegram
qual será a próxima? :)

Coloquei no GitHub para referência futura.
Comment: "desde então eu criptografo meus dados salvos e os descriptografo na hora de exibir ao usuario final" E onde você guarda a chave? Já pensou que se um atacante tem acesso ao seu servidor, ele vai ver não só as mensagens cifradas mas a chave também? A única exceção é se essa chave estiver fora do BD, em um arquivo de configurações por exemplo - SQL Injection é um ataque bem comum, bem mais do que um acesso completo ao seu sistema de arquivos. Ou seja, ajuda um pouquinho sim, mas não é nem de longe tão mais seguro do que simplesmente guardar os dados crus mesmo. Às vezes o mais simples é melhor.
Comment: O que eu posso lhe dizer é que quase ninguém entende de segurança, mesmo desenvolvedores experientes. Conheço até alguns especialistas em segurança, que está longe de ser o meu caso, que cometem vários erros sobre o assunto. Se quer garantir segurança contrate um especialista. Segurança é um tema extremamente complicado. De maneira alguma dados de um *chat* precisam ser salvos. Isto é uma forma muito ingênua de fazer isto. A não ser que queira guardar histórico da conversa tem exatamente zero motivos para salvar os dados. Dependendo do caso o servidor nem precisa existir p/ a conversa em si.
Comment: Não pode ser HTTPS, tem que usar meios próprios, com chaves próprias que os usuários possuam e que para fazer certo elas devem possuir certificados pessoais, coisa que quase ninguém tem, e nem imaginam como fazer isto funcionar. É complicado para usuários leigos e só eles podem fazer isto nos seus computadores (claro que podem pedir para um técnico, mas você como servidor não pode ajudar em nada). Isto mais ou menos eu falei na resposta. o assunto é muito extenso para caber em uma pergunta. Para entender tudo teria que fazer perguntas bem específicas.
Comment: Entenda que *end-to-end* não pode ser influenciada por intermediários. Você como servidor neste exemplo que está usando não pode ajudar os usuários terem segurança/privacidade *end-to-end*. Só eles podem fazer algo. O máximo que pode fazer é colocar um *script* que facilite um pouco a vida deles e instruções do que fazer mas o resto tem que ser com eles. Se você se intrometer tecnicamente falando já não é *end-to-end*. E mesmo este *script* já pode comprometer, porque eles teriam que confiar nele, confiar que você não errou nele, de propósito ou sem querer.
Comment: Interessante, pensei que era um algoritmo ou coisa do genero, Telegram por exemplo usa end-to-end para salvar seus dados, tenho algumas questoes, creio que possa me esclarecer, "Isto é usado em e-mails e mensagens instantâneas, coisas que em geral não passam por um servidor ou se passam, apesar transitoriamente." Como assim nao passam pelo servidor? Os dados nao tem que ser salvos em uma database por exemplo? me perdi aí..
Comment: Pois bem, eu desenvolvo um projeto e desdo principio eu achava a idéia de deixar os dados do banco de dados "cru" sem nenhum tipo de proteção um absurdo, desde então eu criptografo meus dados salvos e os descriptografo na hora de exibir ao usuario final, um exemplo disso foi um chat que desenvolvi, todos os dados do chat eram gravados na database e todos eram encriptados e na hora de listar eu os descriptografava.. A pergunta é, isso pode ser considerado criptografia end-to-end? Ou o fato dos dados passarem pelo meu servidor altera..?
Comment: Em mensagem instantâneas não costumam passar. No caso de e-mail passa mas se a criptografia foi feita entre os clientes apenas (normalmente por PGP), o servidor não participa do processo de criptografia, apesar de ele ser um agente intermediário do transporte ele não é agente da aplicação. Para o servidor são apenas dados indecifráveis. Só os clientes é que saberão o que fazer com estes dados. Que é diferente dos dados trafegados entre um navegador e um servidor PHP em condições normais. Aí o servidor participa, quem tem acesso ao servidor, pode interceptar o dado em determinado momento.
Comment: Este exemplo do *chat* não é *end-to-end*, seu servidor está participando e pode interferir no processo. Você, dono do *chat* não é num um *end* e nem o outro *end*. Só as pessoas conversando é que são. Você é intermediário e consegue saber o que se passa na conversa. E a´te mesmo outras pessoas poderiam se conseguirem acessar seu servidor. Criptografar os dados no DB não garante muita coisa. O transporte está criptografado? Está usando HTTPS, por exemplo? Quando chega ao servidor isto é descriptografado e até você criptografar para colocar no banco de dados, está desprotegido.
Comment: Realmente eu estou muito confuso no momento, pensei que estava fazendo de uma forma correta, Meu Deus será que perdi meu projeto? enfim... Mas os dados nao deveriam ser salvos? tipo, como eles exibem a conversa já trocada entao?
Comment: O que eu acho que pode ser considerado *end-to-end* se a criptografia acontecer no navegador e trafegue assim independente do protocolo e você pegue este dado já criptografado e que você não consegue fazer nada com este dado desta forma a não ser gravar e mandar para outro lugar, não consegue lê-lo ou alterá-lo. Aí só quem pode ser considerado o dono deste dado (de uma forma ou de outra) é que poderia receber e descriptografar o dado.
Comment: Agora me ficou mais claro, ou seja eu (servidor) apenas usar o dado para remeter a outra pessoa, isso ficou claro, mas como seria feita essa encriptaçao no navegador, HTTPS?
Comment: Muito obrigado irei estudar e fazer pesquisas, Obrigado!!
Comment: Andei pesquisando e nao obtive exito, existe alguma forma de enviar informaçoes do user 1 ao user 2 sem precisar de servidor (nao vejo como pois o servidor direciona os dados mas ok), para a assim conseguir o end-to-end...?
Comment: Isto já é outra pergunta mas para web padrão? Que eu saiba não. Web não é solução para todos os problemas.
Answer: A resposta do Maniero já explica o que é end-to-end, vou apenas complementar abordando suas dúvidas específicas:

Ela é inviolável?

Nada é inviolável. Apenas a título de exemplo:

Se uma computação está ocorrendo no servidor, o servidor pode se intrometer nela (não é end-to-end);
Se o servidor somente te envia o código (JavaScript, por exemplo), e toda a criptografia/descriptografia ocorre no browser, parece que está tudo bem, mas pense: se você não confia no servidor, como saber se ele está mandando o JavaScript certo? Ele poderia substituir o seu script por outro, um que passe por cima da criptografia e mande os dados originais para algum outro lugar...
Se você está usando um programa instalado no seu computador, e não uma página na web, eu pergunto: de onde você baixou esse programa? Você confia no seu fornecedor? Ele poderia ter um backdoor para acessar seus dados antes de criptografia...
Você obteve o programa em formato fonte, verificou se estava tudo certo, e compilou você mesmo. Ok, mas seu compilador é confiável? Onde você o obteve, você confia no seu fornecedor? E o computador onde esse programa está executando, ele realmente faz o que você manda fazer, não tem nenhum backdoor no sistema operacional, ou mesmo no próprio hadrware?
(Nota: esse último item é bastante extremo, mas ilustra o ponto que eu quero passar, que você sempre tem que confiar em alguém.)

Existe maneira de se trabalhar ela no PHP?

Como já explicado, se o PHP processa os dados em formato plano, já não é mais end-to-end. E se ele serve o código que vai ser usado para o end-to-end, em princípio está tudo bem, mas no fim das contas ou o usuário confia no seu sistema, ou ele não vai executar um código servido por seu sistema...

Suas vantagens e desvantagens

A principal vantagem é a redução das oportunidades de ataque, por reduzir o número de terceiros nos quais você precisa confiar. Como já dito, não é possível eliminar o requisito de confiança, mas reduzi-lo já é um avanço.
A maior desvantagem é que a responsabilidade pela segurança cai nos ombros do usuário final. Se este não for muito bem treinado, sua experiência com o sistema ficará gravemente prejudicada. A título de exemplo, digamos que seu servidor guarde em arquivo as comunicações passadas. Num determinado momento, o usuário esquece sua senha. Normalmente você poderia resetá-la, mas se essa senha e responsável por derivar a chave de criptografia, e você não a conhece (lembrando: do contrário não seria end-to-end), ao resetá-la o usuário perde o acesso a todo o seu arquivo...
Na mesma linha, se Alice quer se comunicar com Bob é necessário que ambos troquem chaves e/ou certificados de modo a estabelecer a comunicação end-to-end. Seu servidor pode ajudar nisso? De forma alguma! Se ele participasse da troca de chaves, ele estaria na posição perfeita para executar um ataque Man-In-The-Middle... Seus usuários precisam fazer essa troca e/ou verificação de identidade por um meio seguro, por exemplo pessoalmente. Se algum deles tomar um "atalho" (digamos, mandar a chave por e-mail) ele já compromete a segurança da comunicação (vai que o provedor de e-mail substitui a chave por uma de sua posse). Etc.
No geral, eu diria que os benefícios são poucos e os custos bastante altos. A menos que você tenha uma necessidade bem específica, e esteja disposto a usar os softwares mais adequados para tal (de preferência feitos por especialistas, e não home-made; o Maniero já cita alguns, eu acrescentaria o GPG e o Enigmail - para o envio de e-mails). Na minha empresa por exemplo, usamos um e-mail comum para tudo, só quando precisamos enviar algo bem confidencial (uma senha, por exemplo) é que fazemos uso dessas ferramentas. Usar por usar, não compensa, tem de haver um bom motivo por trás...
Comment: é complicado, como voce mesmo disse tudo precisa de um ponto de confiança. Estou tentando criar uma aplicação de chat end-to-end mas pelo visto nao poderei usar esse slogan..
Comment: Andei pesquisando e nao obtive exito, existe alguma forma de enviar informações do user 1 ao user 2 sem precisar de servidor (nao vejo como pois o servidor direciona os dados mas ok), para a assim conseguir o end-to-end...?
Comment: @user3715916 A questão não é usar ou não servidor, e sim garantir que somente os usuários 1 e 2 tenham acesso ao conteúdo no formato original. Se o conteúdo estiver encriptado, e o servidor não tiver a chave, então está tudo bem. O difícil é fazer com que user 1 e user 2 troquem de chaves sem que o servidor ganhe acesso a elas. P.S. Se ainda está interessado em comunicação sem servidor, estude *peer-to-peer*. [Aqui tem um exemplo de projeto](http://blog.printf.net/articles/2013/05/17/webrtc-without-a-signaling-server/) onde os usuários se comunicam diretamente uns com os outros, sem servidor.
Comment: Obrigado pelo link e informaçoes adicionais, eu estou estudando um pouco e cheguei nesse problema que voce mesmo mencionou " O difícil é fazer com que user 1 e user 2 troquem de chaves sem que o servidor ganhe acesso a elas" existe algum artigo ou algo do genero que explique como fazer a troca de chaves sem ninguem sabe-las?
Comment: Posso sugerir [esse artigo na Wikipedia](http://en.wikipedia.org/wiki/Key_exchange) (em inglês). Não espere encontrar uma solução 100%, já que esse é um problema em aberto... Mas a partir desse artigo você poderá estudar e avaliar as principais soluções existentes ([Infraestrutura de Chaves Públicas](http://pt.wikipedia.org/wiki/Infraestrutura_de_Chaves_P%C3%BAblicas) - [PKI](http://en.wikipedia.org/wiki/Public_key_infrastructure) - e [*Web of Trust*](http://en.wikipedia.org/wiki/Web_of_trust)), bem como suas limitações.
Answer:
Um serviço como o Telegram parece resolver grande partes das dificuldades mas tem um problema, eles fornecem tudo o que é necessário. Você tem que confiar neles. Não pode ter nenhum back-door.

Só queria acrescentar que o Telegram é o melhor exemplo recente que eu vi de encriptação end-to-end, mas é isso: use os servers deles.
Porém, consultando o  código, dá para ter ideia de como é a estrutura que eles usam.
Dá para conferir aqui, nos links do GitHub que eles colocam.
Aqui eles explicam superficialmente como usam a encriptação end-to-end no secret chat:

When a secret chat is created, the participating devices exchange encryption keys using the so called Diffie-Hellman key exchange. After the secure end-to-end connection has been established, we generate a picture that visualizes the encryption key for your chat. You can then compare this image with the one your friend has — if the two images are the same, you can be sure that the secret chat is secure and no man-in-the-middle attack can possibly succeed. (Link)

O que é encriptação end-to-end?


Clean URL for custom content

Question: I have a custom content type movie. Now, when I visit any of the movie content, the url is like:
mysite/?q=node/someNumber

I want that every movie content will have url like
mysite/movie/somenumber

or,
mysite/?q=book/someNumber

How to do this?
I am using Drupal 7.
Comment: Do you have clean URLs enabled?  You shouldn't need to enable a special kind of clean URL just for custom content.
Answer: Enable Clean URL + get Pathauto module, which allows to define custom URL patterns for every type of content
If the Clean URL test fails, the web-server is not configured to support this feature. You need to configure the web-server to support Clean URL.
With Apache HTTPD as web-server, you have to enable mod_rewrite and configure the necessary rewrite rules. The rewrite rules can be found in the .htaccess file that comes with Drupal. Usually, theses rules are applied automatically, when mod_rewrite is enabled, but in some cases, the AllowOverride directive is too restrictive to allow this.
See Clean URLs in the Drupal Installation Guide for a more thorough introduction on how to get Clean URLs working in Drupal.
Comment: i cant enable the clean URL , the test fails
Comment: What kind of test? where are you enabling the clean URLs? can you paste the URL? (starting with /admin/...)
Comment: mysite.com/#overlay=%3Fq%3Dadmin/config/search/clean-urls
Comment: OK, I just wanted to know if we are talking about same admin section. Now, what was it that you tried to do on that page and what was the symptom?
Comment: When selecting Clean URL option , it asks to "run the Clean URL test", but the test fails
Comment: At my setup, the form has just a single checkbox 'Enable clean URLs' (Use URLs like example.com/user instead of example.com/?q=user.) Are you sure you don't have a module enabled that hooks up to the form and modifies it? It happened to me during extensive learning that I installed tons of modules before I got a simple solution... Worth checking,
Comment: If the test fails this is a web server configuration issue. Read the documentation in the installation guide carefully and make sure you have have your server correctly set up before proceeding.
Answer: Enable Clean URL, then install and enable the Pathauto module, which allows to define custom URL patterns for custom content.
If the "Clean URL test" fails, you need to enable Apache's mod_rewrite.
Usually, it is suffiscient to put this in .htaccess:
RewriteEngine on
RewriteRule ^en/(.*)$ $1

If the above two line don't fix the problem, your web server is not set up to allow rewrite rules. In that case, it is necessary to enable an extension to the Apache web-server known as mod_rewrite. You do this with the following shell command:
sudo a2enmod rewrite

Then navigate to /etc/apache2/sites-available and edit the file named default. Locate the following block of text:
<Directory /var/www>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride None
    Order allow,deny
    allow from all
</Directory>

And change the AllowOverride directive to:
<Directory /var/www>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride All
    Order allow,deny
    allow from all
</Directory>

When done, restart Apache.
sudo service apache2 restart

(The above example is assuming you're running a standard Apache configuration on Ubuntu ver. 12. YMMV, and you may have to dig out the documentation for your system to see how to do something similar.)

Clean URL for custom content


Approximate accordance between variables

Question: I have a dataset with lots of doublettes in it. I'd like to search for an approximate accordance between the variables that are double, because they don't have exactly the same names. I'd like to compare them so I can decide which one I have to delete. The variables are pre- and lastnames that are very similar to each other and differ just in a few letters, or sometimes just a comma or a space. For instance, I have a case with the name "Smith" and the next case is named "Smithh", but the cases are the same person. How can I merge them?
Thanks for help in advance!
Answer: What you are looking for is probabilistic record linkage, also known as probabilistic matching. As opposed to deterministic record linkage, as provided by the MATCH FILES command. Probabilistic record linkage is not a standard feature of SPSS, but requires additional software.


Augmented chords and chord substitution?

Question: Say we are in C major; how do we use chords like the Augmented chords, other diminished chords outside the scale (minor to major substitution, dominant 7th substitution, altered chords, chord substitution or added chords in a regular diatonic scale) ?
Some of these chord tones are chromatic. What's the best way to use these chords and have it support the melody I need, as much as tips as possible?
And what are some other chromatic chords that work well in diatonic scales and how do you use them?
Answer: There are many ways to utilize chords outside the key and many ways to approach how to use of each individual chord you list.  Like always, you would want your melody and harmony to be compatible in that if you have a melody the harmony you create should reflect that and vice versa. Even though there are many ways to approach using these chromatic chord and others like it, they typically fall into one of the three categories below.
Passing
The point of these chords are just to get from one chord to another in a chromatic fashion typically with one or more notes chromatically moving up or down. The augmented chord is a good example of this where in the key of C we can use the chord progressions:

    C -> C+ -> Am

In this progression the C and E are common in all chords and the notes G-G#-A chromatically ascend. The melody could outline the either the common tones or the chromatic line. Both have different effects and I recommend try both to see the effects.
Borrowed
In this case we're just temporarily borrowing a chord from a neighboring key or mode and continuing in our key like we normally would after the borrowed chord. In the example below, we are in the key of C major and we're borrowing Fm from C minor.

    C -> Fm -> Dm -> G7

Again pay attention to common tones and there is still a chromatic ascending line you could take advantage of when writing a melody for the progression.
Another way to borrow chords from other keys which have a secondary function. The most common chords of this type are secondary dominants and in the example below we are using the dominant of the key of G major in the key of C.

    C -> D7 -> G7

Pivot (move to a new key)
In this case we'll use a chord outside the key to move to a different key. Dominant chords like a dominant 7th or a fully diminished 7th are very effect for doing this especially when the new key is far away, but other chords outside the key could be used to start the pivot away from the old key and into a new key. In C, a very simple example would be:

    G7 -> Bo7(D#o7) -> E

In this we're starting with the typical dominant chord in the key of C, G7, and we turn it into a fully diminished chord by raising the G to a G#. One of the properties of a fully diminished chord is

There are many ways to use the same chords to get different effects and you'll need to experiment and take note of what progressions, substitution, and chromatitizim works in what scenarios, but they will mostly likely be fall into one of the categories above.
Answer: Any major chord can be converted to an augmented by raising its 5th. On the same fashion, every minor chord can be converted to a diminished by flattening its 5th. Since both chords are dissonant they provide tension which tends to be resolved either to their "parent" chords (from which they became ex. C-E-G becomes C-E-G# and then the tension is resolved back to C-E-G) or to a different chord which shares some common tones (ex. C-E-G becomes C-E-G# then the tension is resolved to C-E-A which is an Am).
One heavily used example of the diminished chord (apart from the VII degree of the harmonic minor scale) is the diminished chord built upon the raised 6th degree of the minor scale. For example, in the A minor scale, one can substitute the Am (A-C-E) chord with an F#dim (F#-A-C) or combine them to create an Am6 chord (A-C-E-F#).
Although both chords tend to give a sense of departure from tonality only the diminished chord is widely used.
Comment: The C-E-G# becomes E-G#-B# - an augmented E to move on to Am.
Comment: Yes, that would be the correct way to present the augmented chord as an V with #5 going to the new tonic, the Am.
Comment: "Yes, that would be the correct way to present the augmented chord as an V with #5 going to the new tonic, the Am." what do you mean by that? the tonic changes? explain please
Comment: This is called modulation. It is when in a composition, a new tonic is introduced, most of the times by a chord which is altered in a way to resemble a V that resolves to the new I. You can find information about modulation in any harmony textbook.
Comment: so using E-G#-B# will in modulate to Am , what scale would you use the EG#B# to modulaute in to Am? can you show me a short example of the first scale then Am. do you have an email ? so any place i can message you? thank you for responding


Binding multiple textbox controls to database rows

Question: I´m trying to store some parameters for my application on a database table. The table contains multiple rows which contains a Key -> Value relationships. On my windows forms program (written in C#) I have multiple controls that should allow the user to interact with the stored configuration on the database.
For example, my database table looks like the following:
id option_name               option_value
1  serial_port_baudrate      9600
2  serial_port_stopbits      one

On my form I have controls that allow to change those values. After some research I've obtained the expected results using the bindingSource class and the filter property. But I have to create a bindingSource object for each textbox using the visual editor. Can you please help me to archieve this with multiple textboxes and controls without using the visual editor?
I dont know if it´s possible but I would like to code a solution where I could just name the textboxes on my form with the same name of the Key that holds the value in the database and then they would get the correct values when the application runs. I would appreciate any information or hints you could provide.
Thanks in advance.
Comment: I'm sorry, I forgot to specify. I'm working on Windows application using C# Visual Studio 2005 and SQL 2005.
Answer: Well, you could name all the text boxes the same as the database fields, then loop through all the textbox controls on the form.  Use the name of the form as a parameter as in the below code:
 DataTable table = new DataTable();

            //Populate datatable
    TextBox txt = new TextBox();
          foreach(DataRow row in table.Rows)
        {
            String controlID = row["option_name"].ToString();

              txt.ID = controlID;

              (new TextBox()).ID = controlID;

              txt.Text = table.Rows[table.Rows.IndexOf(row)][controlID].ToString();
        }

Answer: This is what I use for my Options table:
    void loadOptions(Control parent)
    {
        foreach (Control c in parent.Controls)
        {
            DataRow[] res = options.Select("option='" + c.Name + "'");
            if (c is GroupBox)
            {
                loadOptions(c);
                continue;
            }
            if (res.Length < 1) continue;
            DataRow row = (DataRow)res.GetValue(0);
            String value = row["value"].ToString();
            if (c is TextBox)
            {
                c.Text = value;
            }
            else if (c is CheckBox)
            {
                ((CheckBox)c).Checked = Convert.ToBoolean(value);
            }
            else if (c is NumericUpDown)
            {
                ((NumericUpDown)c).Value = int.Parse(value);
            }
        }
    }

I'm not sure if this is the best solution, but it works. I'm always looking for a better way if anybody has one.


Time series $MA(2)$ projection $X_t$ onto $H_{t-1}$

Question: I have an $MA(2)$ process $X_t = Z_t - Z_{t-1} + 0.25Z_{t-2}$ where $Z_t \sim WN(0, \sigma^2)$ and I need to find a projection of $X_t$ onto space $H_{t-1}(X_t)$, but how to do that?
I guess my projection will be a linear combination $P_{H_{t-1}}X_t = \sum\limits_1^{\infty}a_iX_{t-i}$ but how to do it legitimately? Or maybe it is easier to find a projection onto $Z_t$ (as $X_t$ is both causal and invertible)?
Could anyone explain me what to do in these kind of problems (also when I am projecting onto, for instance, $sp(X_1,...X_t)$). Thanks in advance!
EDIT:
I got $Z_t = \sum\limits_{i=0}^{\infty}0.5^i(i+1)X_{t-i}$. I know that my process is both causal and invertible, so basically a projection onto $H(X)$ is the same as onto $H(Z)$. So is my projection just $\sum\limits_{i=1}^{\infty}0.5^i(i+1)X_{t-i}$? Please notice that I changed $i$ from $0$ to $1$ as I am cutting off $X_t$ as it is not included in a subspace I'm projecting onto.
Comment: Hi: that's not an AR(2) as written. It could be viewed as an MA(2) if you add $Z_t$ and $Z_{t-1}$ and call it $Z^{*}_t$.
Comment: With regard to my comment above, note that $Z^{*}_{t}$ will be a normal RV with twice the variance as the other MA term.
Comment: @mlofton you are absolutely correct, it was a typo, that's $MA(2)$
Comment: No problem. Usually MA models are estimated using a likellhood approach with a constraint to ensure uniqueness. I'm not familar with projection approaches unless maximizing the likelihood can be thought of as a projection. Hopefully someone else can be more helpful.
Comment: @mlofton could you please take a look at solution that I've added?
Answer: Hi Amal: I'm just putting this into answer for room but it's not really an answer.
We have: $X_t = \epsilon_t - \epsilon_{t-1} + 0.25 \epsilon_{t-2}$.
( I changed $Z_{t}$ to $\epsilon_t$ since I'm more used to that noation).
So, using the lag operator gives:
$X_t = (1 - L + 0.25 L^2) \epsilon_t$
But I'm not clear on how you went from there to what you obtained ?
I'm not sure that it can be considered a projection, but the MLE for the MA
is generally obtained in the following way:
We know that each $X_t$ is normally distributed with mean $E(\epsilon_t - \epsilon_{t-1} + \epsilon_{t-2}) = 0$ and variance (2 + $\frac{1}{16})\sigma^2$.
So, the first step is to initialize by setting  the  estimates of $\epsilon_{0}$ and $\epsilon_{1}$ to $0$ since they are not directly obtainable.
Then, from the model,  $\hat{\epsilon_{2}} = X_{2} + \hat{\epsilon_{1}} - 0.25 \hat{\epsilon}_{0}$
$\hat{\epsilon_{3}} = X_{3} + \hat{\epsilon_{2}} - 0.25 \hat{\epsilon}_{1}$
$\hat{\epsilon_{4}} = X_{4} + \hat{\epsilon_{3}} - 0.25 \hat{\epsilon}_{2}$
and so on and so forth until the $\epsilon_t$ are obtained $\forall ~ t$.
And you keep obtaining them recursively in that manner. Then, once you
have them, you minimize the sum of their squares because this is equivalent to maximizing the density of the likelihood since its normal.  This approach possibly can be viewed as a projection but I'm not sure. Also, their are better methods for initializion of the first two $\hat{\epsilon}$. The intitialization issue is mostly likely discussed in Box-Jenkins and Reinsel. Also, note that your projection approach might be equivalent. I just don't follow how you obtained it.


Matlab 2D-array indexing contradiction between for loop and vectorised version

Question: I know there's been lots of indexing question on here, but this one seems puzzling to me, hope someone's got a quick answer for me, will understand if this one gets deleted though. I've got a 2D a-by-b array x and want to get from another array y this :
for i=1:b
x(:,i) = y( (i-1) * k+1 : (i-1) * k+a )
end

without a for loop, like this :
x(:,1:b) = y( (0:b-1) * k+1 : (0:b-1) * k+a )

but to no avail, I get
"Subscripted assignment dimension mismatch."
Any ideas? Thank you in advance.
Comment: What does `k` correspond to?
Comment: it can be anything suitable, say a positive integer, 2 for example
Answer: You can't just litteraly translate a for loop in a vectorisation
When you do
vector : n

In fact, MATLAB do
vector(1):n

That's where your vectorisation is wrong.
Comment: sorry but I don't get you, where do you see me doing that?
Comment: @user3374479 by `vector` he means `(0:b-1)`
Comment: how should I proceed instead?
Answer: It seems you can just use bsxfun to create those linear indices and index into y to get the desired output like so -
x = y(bsxfun(@plus,[1:a]',[0:b-1]*k))

Comment: thanks. And what if I want to multiply element by element with another vector of length a? Could I integrate that in bsfxfun?
Comment: @user3374479 `bsxfun(@times,x,another_vector(:))`?
Answer: say b=10, and assuming 'a' can be a scalar, (k*a) = 3;
x(:,1:10) = y( (0:10-1) * 3 : (0:10-1) * 3);

no matter what 'y' equals, the right side of the equation is a scalar, and since you aren't looping through you would simply be replacing the first 10 values of 'x' by the same number:
for example, x(:,1:10) = 116   116   116   116   116   116   116   116   116   116
you cannot index iteratively without looping
Comment: thank you for your explanation,
@Divakar's bsxfun line did the trick :)


What is the flash midi player used by musipedia?

Question: Musipedia.org has a flash piano midi player on its site. What is the origin of this player? Is this something they created themselves or is a standard player available from elsewhere?
I ask because most midi players I use have absolutely terrible sound, but the Musipedia player sounds like, well, a piano.
Answer: The player says at the bottom in red "Flash Created By "My Music" Developers in partnership with Musipedia".
This links to http://joshkoo.comp.nus.edu.sg/mymusic/ which is no longer available, but I would guess that's supposed to link to a page indicating "Josh Koo" is the guy that created the player.
The reason it sounds like a piano is probably that it doesn't use your computer's midi patches (which could be very good by the way), but it's using sampled sounds (or generating its sounds without using your computer's midi patches).  Quite likely if most midi players you use sound terrible.
There is also a link on the page "If you have an external MIDI piano connected to your computer, please click here to use it".  This opens a Java based midi player, although that's not actually working on my browser.


How to find the $n$th term of a repeating pattern

Question: What is the nth term of following sequence
 $1,2,3,4,5,6,1,2,3,4,5,6,\ldots$
$(n, n+1, n+2, n+3,\ldots,$ $,n+p, n, n+1, n+2, n+3,$ $n+4, n+5,$ $\ldots,$ $n+p,$ $n,$ $n+1,$ $\ldots)$
Actually, I am trying to solve the following puzzle
 $6$ girls pick a captain by forming a circle then eliminating every $m$th girl. The 2nd girl in the counting order can choose $m$. If she wants to be captain what's the smallest $m$ she should pick?
Comment: For general related problems, please see the [Josephus Problem.](http://en.wikipedia.org/wiki/Josephus_problem)
Comment: What is the question ?
Answer: The $n$th term of the repeating sequence $1,2,3,4,5,6,1,2,3,4,5,6,\ldots$ can be written
$$n-6\lfloor{n-1\over6}\rfloor$$
where $\lfloor x\rfloor$ is the greatest integer function.
The OP's real question, about the would-be captain, strikes me as a nice new take on the classic Josephus Problem, which André Nicolas recommended in comments.  That problem is to predict the survivor as a function of the starting number $n$ and the "skip count" $m$.  The OP here is, in effect, asking about the inverse of that function.  I.e., if $S(m,n)$ is the usual "Survivor" function, we can ask about the set $M(n,s)=\{m:s=S(m,n)\}$; the OP wants the smallest member of the set $M(6,2)$.
I'm with the answer given by Michael:  I can't think of any way to find the smallest (or any) element of $M(6,2)$ except by trial and error.  In fact I'll go further:  It's not obvious to me that the set $M(6,2)$ has any elements at all.  Am I missing some elementary reason that the sets $M(n,s)$ are necessarily non-empty?
Added later:  For completeness, here are the results of trial and error:
$$\begin{align}
m&\quad\text{order of elimination}\\
1&\quad123456\\
2&\quad246315\\
3&\quad364251\\
4&\quad421365\\
5&\quad543216\\
6&\quad613254\\
7&\quad136245\\
8&\quad254163\\
9&\quad312645\\
10&\quad436152\\
\end{align}$$
So it is obvious to me now that the set $M(6,2)$ is non-empty, but only because I was able to find its smallest element with a finite amount of computation:  The answer to the OP's question is $m=10$, that being the smallest number for which $s=2$ is the last number "eliminated."
Actually, it's fairly clear that for any given $n$, the sets $M(n,s)$ for $1\lt s\lt n$ can be determined by a finite computation.  That's because the list of permutations that specify the order of elimination, as illustrated above for $n=6$, is periodic with period $\text{lcm}(1,2,\ldots,n)$ (or a divisor thereof).  For $n=6$, the lcm is $60$.  Lucky for me I didn't have to list all $60$.  I doubt I could have done so without making at least one mistake.  (For that matter, I won't guarantee the list I did compute is mistake-free.  I did doublecheck the order of elimination for $m=10$, though, so at the very least the smallest member of $M(6,2)$ is no greater than $10$.)
Answer: With your notation, $u_k = n-1+\pmod{(k,p)}$, where $\pmod{(k,p)}$ is the smallest positive integer $m$ that verifies $p|(k-m)$.
Answer: If $m=1$, then 1,2,3,4,5 are eliminated, so 6 is captain.
If $m=2$, then 2,4,6 are eliminated, skip 1, eliminate 3, skip 5, eliminate 1, so 5 is captain.
Repeat for $m=3$, $m=4$, and so on.
I don't know how to calculate it in advance though.
Answer: The $n$-th term of sequence $1,2,3,4,5,6,1,2,3,4,5,6,\ldots$ is given by $a_n=1+(n-1 \bmod 6)$.


Java Reader, read method for text file

Question: I have a text file called test.txt with the word hello. I am trying to read it using Reader.read() method and print the contents to console. However when I run it I am just getting the number 104 printed on console and nothing else (I get the same number printed even if I change the text to more/less characters). Any ideas why it is behaving this way and how can I modify this existing code to print the contents of test.txt as a string on console? Here is my code:
public static void spellCheck(Reader r) throws IOException{
    Reader newReader = r;
    System.out.println(newReader.read());
}

and my main method I am using to test the above:
public static void main (String[] args)throws IOException{
    Reader test = new BufferedReader(new FileReader("test.txt"));
    spellCheck(test);
}

Comment: @peter.murray.rust: no, it's returning a char as an int, or -1, as every Reader.
Comment: You're reading one character and you're printing one character. The code is working as designed. What's the question?
Answer: read() is doing exactly what it's supposed to:

Reads a single character. This method will block until a character is available, an I/O error occurs, or the end of the stream is reached.

(emphasis added)
Instead, you can call BufferedReader.readLine() in a loop.
Comment: Thanks for the link, the answer was staring right at me. Unfortunately I could only select one as the answer, but your help and prompt reply is appreciated.
Answer: As the javadoc indicates, the read() method reads a single char, and returns it as an int (in order to be able to return -1 to indicate the end of the stream). To print the int as a char, just cast it:
int c = reader.read();
if (c != -1) {
    System.out.println((char) c);
}
else {
    System.out.println("end of the stream");
}

To read everything, loop until you get -1, or read line by line until you get null.
Comment: How do I read line by line? My method is taking (Reader r) as a parameter, and I do not want to change that. Then I cannot say `BufferedReader newReader = r` as that gives me incompatible type. But as far as I can tell from the docs, Reader does not have a readLine() method.
Comment: BufferedReader is the class allowing to read line by line. So if that's what you want to do, wrap the Reader into a BufferedReader in your method. But you don't need to read line by line to read everything. You can simply use [this read method](http://docs.oracle.com/javase/6/docs/api/java/io/BufferedReader.html#read%28char[],%20int,%20int%29) (for better performance) until it returns -1.

Java Reader, read method for text file


Erro de Java.lang.String cannot be cast to , quando capturo os dados no Jcomobox para salvar

Question:
Tenho o evento do botão salva, quando eu clico para salvar, aparece a seguinte : Java.lang.String cannot be cast to org.nomedopacote.modelo.Funcionario

cbNomeUsuario - É nome da Jcomobox que estão pegando uma List Funcionario .
    usuario.setFuncionario((Funcionario) cbNomeUsuario.getSelectedItem());

Um erro de cast, alguém pode me ajudar ?
Quero pegar o retorno ou seja o ID do funcionario para guardar no banco.
Salvar no banco normal :
objeto.getFuncionario().getId();
Comment: Se você mostrar sua classe `Funcionário` fica mais fácil te ajudar.
Answer: Sua chamada (Funcionario) cbNomeUsuario.getSelectedItem() está tentando converter para o tipo Funcionario um objeto do tipo String, que está sendo retornado por cbNomeUsuario.getSelectedItem(). São tipos incompatíveis.
De fato, seu código sugere que você está querendo guardar um objeto do tipo Funcionario retornado por um método que retorna somente o nome do usuário (cbNomeUsuario.getSelectedItem()).
Corrija o método getSelectedItem(), ou então poste o código do mesmo na sua pergunta para tentarmos entender o que pode estar acontecendo.
Answer: Não vi a declaração e inicialização da sua ComboBox mas a classe JComboBox é parametrizada. Logo você pode declarar algo do tipo: JComboBox<Funcionario> combo = new JComboBox<Funcionario>(); ou JComboBox<Funcionario> combo = new JComboBox<>();
E fazer a inserção dos itens normalmente: combo.addItem(...); utilizando os objetos da classe Funcionario sem precisar converter para String.
Caso não possa mudar isso, você pode usar o método getSelectedIndex() e acessar o objeto de sua coleção.
E Assim como o Piovezan disse, você está realizando um cast de Funcionario em um objeto do tipo String. O que gera o erro detectado.


Two men run at $5$km/hr and $3$km/hr around a $6$km circular track. After how much time will they meet?

Question: I am working on this problem.

Two men, A and B run in the same direction around a circular track, starting at the same time from the same point. The speed of A is 5 km/hr and that of B is 3 km/hr. If the track has a perimeter of 6 km, after how much time will the two meet?

How to solve this question without using the concept of the relativity?
I believe the answer is 3.
Comment: Why do you want to avoid relativity? If you use relativity, you get that $B$ sits still and $A$ goes at $2$ km/hr and the problem reduces to how long does it take $A$ moving at $2$ km/hr to traverse $6$ kilometers.
Comment: @JohnDouma I needed proof of correctness for relativity method?
Answer: It is approachable using simple modular arithmetic. We just wish to find the minimal positive solution $t$ of:
$$3t \equiv 5t \pmod 6$$
Which is solved when $3t - 5t = 6z$ for $z \in \mathbb{Z}$. It follows:
$3t - 5t = -2t = 6z \rightarrow t = -3z$ for $z \in \mathbb{Z}$.
We consequently have the first nontrivial positive solution is 3.
Note: if you are unfamiliar with "mod", it is akin to the remainder under integer division. What is occurring mathematically here then is essentially a "reset" when one makes a lap around the track, allowing us to evaluate the problem without relativity.
Comment: Yes, thank you, amended.
Comment: Welcome to Mathematics Stack Exchange.  Did you mean $3t-5t=\color{red}-2t$?
Answer: To determine when the two men, A and B, will meet, we need to consider their relative speeds and the distance they need to cover to meet.
The relative speed between A and B is the difference in their speeds, which is $5 km/hr - 3 km/hr = 2 km/hr$. To find the time it takes for them to meet, we need to calculate the time it takes to cover the total distance of $6 km$ at a relative speed of $2 km/hr$.
$Time = Distance / Speed$
$Time = 6 km / 2 km/hr$
$Time = 3 hours$
Therefore, the two men will meet after $3$ hours of running.
Comment: This is the way I would solve this problem as well but the question was how to do this without relativity.


Incorporating Images into XSL+XML

Question: I'm working on a project for one of my classes where I need to display film information generated from an XML document. While looking up other questions that may relate to mine, I didn't really understand the answers and the solutions didn't change anything. What I want to happen is for me to make reference to the images once and have it instantiate for each instance of my "movie" element the way it works for the titles and other attributes and elements. Here's an example "movie" element from my XML code:
<movie>
        <title title="L'Ile aux chiens" year="2018" language="English, Japanese" genre="Animation, Adventure, Comedy" imdb="tt5104604"/>
        <poster src="isle of dogs.png"/>
        <director>Wes Anderson</director>
        <writers names="Wes Anderson, Roman Coppola, Jason Schwartzman, Kunichi Nomura"/>
        <actors names="Bryan Cranston, Koyu Rankin, Edward Norton, Bob Balaban"/>
        <plot>Set in Japan, Isle of Dogs follows a boy's odyssey in search of his lost dog.</plot>
    </movie>

Here's the code I have so far for my XSL:
     <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" version="4.0" indent="yes"/>
    <xsl:template match="/">

                <link rel="stylesheet" type="text/css" href="film_css.css"/>
                <title>Discography of Wes Anderson</title>

Discography of Wes Anderson

                <xsl:for-each select="//movie">

<xsl:value-of select="title/@title"/>

                    <xsl:value-of select="//poster"/>

Year: <xsl:value-of select="title/@year"/>

Writers: <xsl:value-of select="writers/@names"/>

Actors: <xsl:value-of select="actors/@names"/>

Plot: <xsl:value-of select="plot"/>

                </xsl:for-each>

    </xsl:template>
</xsl:stylesheet>

I'm still kind of new to all this coding stuff (I just started in September at the beginning of my master degree, I'm from a linguistics background), so it'd be much appreciated if any responses were kind of dumb-downed for me! (Not much, but you know how it is as a beginner.)
Answer: src is not a child element of movie you need to give proper path upto @src like:

Comment: Thank you!! Worked perfectly
Answer: instead of
<xsl:value-of select="//poster"/>

use

You just have to apply the same logic as what you have already done for Year, Writers, Actors, and Plot.
Comment: Thank you!! Worked perfectly

Incorporating Images into XSL+XML


Is it possible to display user's first login (activation) date in a view?

Question: All the users are imported (only admin can create accounts), they receive an activation email to connect with a one-time login.
What I would like to know is how to display the date when they actually came at first (first login) and/or activate their account with the account process (password changing and save)?
Apart from the basic profile augmented with a few fields, my users have a native role that is dropped when they activate their account just to unlock automatically a function. So if there is a lead on "when the role was removed or changed" that I can't figure out right now, I might work with that.
I didn't put https://www.drupal.org/project/login_history yet unfortunately.
Answer: There is no field that stores this information in the database.
The only thing you have by default are user account creation date, last login date and last access time.
Once a user has logged in for a second time those values are no use to you.
There are also not user revisions by default so you can't see when the first time a user changes their username/password/etc. you can only see the data the most recent change was made.
The only way is to use something like login history or user revisions, however that only helps you from now on, not for existing users.
Off the top of my head I can't think of any way you can get reliable data for this for existing users.
[EDIT]
Actually, the drupal watchdog log stores user login events.
When a user logs in this watchdog call happens:
<code>watchdog('user', 'Session opened for %name.', array('%name' => $user->name));
</code>
So if you check your drupal logs for "Session opened for" you can find all user logins.
This will only help you if you have a record of all your watchdog logs since the beginning of your site (probably not likely).
If you only use the dblog module that logs to the drupal watchdog table it is likely you don't have all logs because old ones will usually be purged to keep the database table size under control.
If you use the syslog module to that logs to your web server's file system it is possible that you could have backups of all logs for the whole life of your site, however that also isn't guaranteed.
It's probable that old logs are also purged in this case too.
Comment: I thought I actually scheduled a daily watchdog backup just in case. Now I can't find it. The idea is pretty good otherwise. I am still looking into it for a little while before giving up...


Laravel: Check if time + 4 hours has passed

Question: I store in my database a date format like this:
2017-02-22 16:55:40

I added it to my database like this:
Carbon::now();

I need to check if 4 hours passed since this date.
How I can do this? I couldn't figure out how I can convert this format into Carbon or timestamp.
Comment: Ok but it's related to an entity right? Just add the date field as a date in `$dates` array of the specific model and you can use carbon automatically
Comment: Is this date tied to a model ?
Comment: The date added manually
Comment: Thansk @ClaudioLudovicoPanetta!
Answer: If you are using Laravel and the date is a Carbon instance from a Model you have access to the whole Carbon API.
You can use the Difference API of Carbon for this specific purpose.
echo $model->thedate->diffInHours($now, false);

If your model does not threat the date as a carbon instance you can cast it by adding the date to the dates array of the current model like so
 protected $dates = [
    'field_name',
];

Check out Date casting for more information
Update with an explicit example
$user = User::first();
// This will return the difference in hours
$user->created_at->diffInHours(Carbon\Carbon::now(), false);

Answer: You can convert it to a Carbon object with:
Carbon::parse('2017-02-22 16:55:40');


Facing error again in minikube renew certificate

Question: When I run  kubectl command getting error is certificate expired
How to debug minikube errors?
kubectl get pods
Unable to connect to the server: x509: certificate has expired or is not yet valid
Answer: It seems issue is related to an expired certificate
A Temporary workaround is to removes several files from the /var/lib/minikube/ directory, then reset the Kubernetes cluster and replace keys on the host. Refer to this gitlink which can be helpful to resolve your issue
If the issue is not yet resolved try running the command minikube delete and then delete the local Kubernetes cluster.
Comment: @Paul Did you have time to check my answer? It helped you to solve your issue? If not, I am happy to assist further
Comment: Restarts helped me!


Compile a C project to DLL file in windows

Question: I downloaded libnova library from here.
Following the README, I can create .a and .so libraries. But I need the .dll file for a Qt program on Windows. Can you tell me how to generate a .dll file ? I'm very familiar with Linux but a newbie regarding Windows.
Any reply is appreciated.
Comment: Googling "mingw build dll" may help. The first hit is [HOWTO Create and Deploy a Sample DLL using MinGW](http://www.mingw.org/wiki/sampledll)
Comment: Please edit your post and include the tag for the compiler you are using. Otherwise it is impossible to answer the question.
Comment: Thanks. I use gcc in mingw
Answer: This Method is for Static Library here
Go and Refer here... this is for windows dynamic linking...
Thanks & Regards...
Answer: Use following command in console window:
 g++ -shared -o example_dll.dll example_dll.o -W

note: GCC need to be installed before do this.


Problem with enabling JavaScript with HtmlUnit

Question: I'm a newbie to HtmlUnit, and I'm writing a demo script to load the source HTML of a webpage and write it to a txt file.
public static void main(String[] args) throws IOException {
    try (final WebClient wc = new WebClient(BrowserVersion.BEST_SUPPORTED)) {
        wc.getOptions().setThrowExceptionOnScriptError(false);

        final HtmlPage page = wc.getPage("https://www.sainsburys.co.uk/gol-ui/SearchResults/biscuits");
        WebResponse res = page.getWebResponse();
        String html = res.getContentAsString();

        FileWriter fw = new FileWriter(dir + "/pageHtml.txt");
        fw.write(html);
        fw.close();
    }
}

However, it returns the HTML for disabled JavaScript. To try and fix this, I added this line to ensure JS is enabled on the WebClient:
        wc.getOptions().setJavaScriptEnabled(true);

Despite that, nothing changes. Am I being an idiot, or is there something more subtle that needs to change?
Thanks for any help! ^_^
Comment: What _do_ you get? Are you confirming that you're waiting for asynchronous things to happen? (I suggest considering Geb as a DSL on top of Selenium, as it makes sorting these things out easier.)
Comment: Hi! I do get some HTML back, but it's essentially a plain HTML page telling me that I need to enable JavaScript. I tried to see if this was recreatable with a different page (this time the page for ASDA - it's for a uni project), and this time it tells me my browser is out of date. Kinda stuck here for ideas what to do. The context behind this is for web scraping for an android app, but Jsoup doesn't support JS I believe. I'll try the solution you provided!
Answer: WebResponse res = page.getWebResponse();
String html = res.getContentAsString();

This is the response (code) you got from the server. If you like to have the current DOM (the one after the js processing is done you can do something like
HtmlPage page = webClient.getPage(url);
webClient.waitForBackgroundJavaScript(60_000);

System.out.println(page.asXml());

or
System.out.println(page.asNormalizedText());


Alebgraic curve and Riemann surfaces

Question: How do we prove that any smooth complex algebraic curve $C\subset\mathbb{P}^2$ is a Riemann surface?
Does there exist a complex version of the implicit function theorem?
Comment: I believe you mean $ C \subseteq \mathbb{CP}^{2} $.
Comment: Also, it's important to distinguish between (i) the Zariski topology on $ \mathbb{CP}^{2} $ and (ii) the analytic topology on $ \mathbb{CP}^{2} $, which is the finest topology on $ \mathbb{CP}^{2} $ that makes the obvious projection mapping $ q: \mathbb{C}^{3} \to \mathbb{CP}^{2} $ continuous. When showing that $ C $ is a Riemann surface, you want to consider only the analytic topology and equip $ C $ with an atlas in that topology that is analytic.
Answer: Take $(x:y:z)$ as the homogeneous co-ordinates on the projective plane. Then the subset of the curve where $x\ne0$ being open in  $C$ is again smooth. But this subset is embeddable as closed set in  $\mathbf{C}^2$: dehomogenize the equation taking $y/x, z/x$ as affine co-ordinates. This gives a co-ordinate patch. Similarly do for the other co-ordinates. Verification that transition between the patches are analytic follows from the fact these transition functions are rational functions with denominators not vanishing on the intersections.

Alebgraic curve and Riemann surfaces


Tr of matrix in Kullback-Leibler divergence PRML2.13

Question: I've learned PRML recently but get stuck in a math problem.
this exercise is to calculate $KL$ divergience of $2$ multi Gaussian
$$  N(\mu,\Sigma)\ \ \  and\ \ \  N(m,L)$$
but I do not know how to derive the Tr part

the $\operatorname{Tr}$ term is derived from
$$\int e^{\{-1/2 (x-\mu)^T\Sigma^{-1}(x-\mu)\}}{(x-m)^TL^{-1}(x-m)}dx$$
what formulation dose it use?
Thanks!!!
Answer: Note that $$(x-m)^TL^{-1}(x-m)$$ is a quadratic form, so it's scalar. We know that the trace of a scalar is the scalar itself, so $$(x-m)^TL^{-1}(x-m)=Tr((x-m)^TL^{-1}(x-m)).$$ Further, the trace of a product is invariant under cyclic permutations, so we can write $$Tr((x-m)^TL^{-1}(x-m))=Tr(L^{-1}(x-m)(x-m)^T).$$
Comment: thx,it's a clear explanation~


Simple Word Problem about Balls and Algebra

Question: You, 4 other people, and a dog are in a room. You have a bunch of tennis balls in the center of the room. When no one is looking except for the dog, you give one tennis ball to the dog and then you divide the remaining tennis balls into 5 equal piles. You take one of the piles and hide it somewhere else in the room. Each of the 4 other people in the room do this to the remaining stash of tennis balls in the center (1 for the dog, 1/5 of the remaining for them). You again give one tennis ball to the dog after all four people have done the same and divide the remaining tennis balls evenly among all 4 people and you. There are no more balls left. What is the minimum number of tennis balls that could have been in the center of the room at the beginning?
Comment: See https://thewinnower.com/papers/5214-a-needlessly-complicated-and-unhelpful-solution-to-ben-ames-williams-famous-coconuts-problem
Comment: See also: https://math.stackexchange.com/q/20782/215011
Answer: The (in)famous solution due to Dirac
We have $-4$ balls in a room. (We, the company, owe the next door pimp $4$ balls.)
1 You give one ball to the dog. (You borrow one more ball so that you can give it to the dog.) There remains $-5$ balls in the room. (The company owes the next door pimp $5$ balls now.) You divide the balls into $5$ equal groups, and take away one group containing exactly $-1$ balls. (You agree with the pimp that you will take care of the fifth ball borrowed.)  There remain $4$ such groups. Then you merge these groups and there remains again $-4$ balls. (The company owes the next door pimp $4$ balls.)
2 ... 4
The company still has $-4$ balls. (The company still owes the next door pimp $4$ balls.)
You give one ball to the dog and each of you takes away $-1$ balls. (Each of you agrees with the pimp to take care of one ball personally.)
There remains $0$ ball. (No further common liability to the next door pimp.)
So, if the question would have been about the minimal absolute value of the number of balls to start with then the answer would have been $$4.$$
Comment: O! cruel, cruel Exchange wherein I can upvote this but once.


Ultimo registro de cada objeto django

Question: Estou desenvolvendo um aplicativo web em Python, Django e Sqlite. Tenho dois models, um para "Vendedor" e outro para "Pedidos". Preciso pegar o ultimo pedido de cada vendedor e não estou conseguindo fazer isso com o Django. Segue meus models abaixo:
class Vendedor(models.Model):
    nome = models.CharField(verbose_name='Nome', max_length=100)
    nascimento = models.DateField(verbose_name='Data Nascimento:',
                                  help_text='Informe a data')
    endereco = models.TextField(verbose_name='Endereço:')

class Pedidos(models.Model):
    vendedor = models.ForeignKey('Vendedor', verbose_name='Vendedor:',
                                  related_name='vend', on_delete=models.SET_NULL,
                                  null=True)

    data = models.DateField(verbose_name='Data Pedido:', help_text='Informe a data')

    LISTA_TIPO = (('Of', 'Oficina'),('Pd', 'Produto'),('Sr', 'Serviço'),)

    tipo = models.CharField(verbose_name='Tipo:', max_length=50,
                            choices=LISTA_TIPO, blank=True,
                            help_text='Informe qual o tipo', default='')

Cada vendedor tem vários pedidos. Preciso pegar o ultimo pedido de cada vendedor. Alguém poderia me ajudar
Comment: Depois da edição, a sua pergunta se tornou totalmente desfigurada e abrangente demais sugiro que leia com atenção [esse link](https://pt.stackoverflow.com/help/how-to-ask), aqui no SOpt
Comment: Ok, agora sim, tente implementar minha resposta na linha de comando, se não conseguir, acresente na pergunta ou aqui nos comentarios o que deu errado, se conseguir e continuar com problemas em outro topico então provavelmente vc deve elaborar outra pergunta.
Comment: Obrigado pela ajuda. Segui sua lógica e deu certo, muito obrigado!!
Answer: Como em django existem varios contextos, vou tentar explicar com seu proprio exemplo mas em uma console django, se quiser experimentar, entre em um console python (no ambiente e diretorio do seu projeto) e execute o codigo abaixo (As explicacoes estão como comentários no próprio código):
Criando os objetos:
# Importação dos pacotes necessários
from datetime import date
from core.models import Vendedor, Pedidos

# Criando 2 vendedores
>>> Vendedor.objects.create(nome='foo', nascimento='1991-01-01', endereco='Rua que sobe e desce, 166')
>>> Vendedor.objects.create(nome='bar', nascimento='1992-02-02', endereco='Rua que sobe e desce, 777')

# Listando a queryset dos objetos vendedores
>>> Vendedor.objects.all()
<QuerySet [<Vendedor: Vendedor object (1)>, <Vendedor: Vendedor object (2)>]>

# Adicionando 2 pedidos para o vendedor 1
Pedidos.objects.create(vendedor=Vendedor.objects.get(pk=1),data=date.today(), tipo='of')
<Pedidos: Pedidos object (1)>
Pedidos.objects.create(vendedor=Vendedor.objects.get(pk=1),data=date.today(), tipo='Pd')
<Pedidos: Pedidos object (2)>

# Adicionando 2 pedidos para o vendedor 2
Pedidos.objects.create(vendedor=Vendedor.objects.get(pk=2),data=date.today(), tipo='Pd')
<Pedidos: Pedidos object (3)>
Pedidos.objects.create(vendedor=Vendedor.objects.get(pk=2),data=date.today(), tipo='Sr')
<Pedidos: Pedidos object (4)>

# Listando todos os pedidos (QuerySet)
print(Pedidos.objects.all())
<QuerySet [<Pedidos: Pedidos object (1)>, <Pedidos: Pedidos object (2)>,
           <Pedidos: Pedidos object (3)>, <Pedidos: Pedidos object (4)>]>

Trabalhando com Objects.last():
# Apresentando o ultimo pedido feito:
print(Pedidos.objects.last())
Pedidos object (4)

Trabalhando com objects.filter():
# Apresentando o ultimo pedido do vendedor 1
Pedidos.objects.filter(vendedor=1).last()
<Pedidos: Pedidos object (2)>

# Apresentando o ultimo pedido do vendedor 2
Pedidos.objects.filter(vendedor=2).last()
<Pedidos: Pedidos object (4)>

Trabalhando com related_name:
# Apresentando o ultimo pdido do vendedor 1 via related name
>>> vendedor1 = Vendedor.objects.get(pk=1)
>>> vendedor1.vend.last()
<Pedidos: Pedidos object (2)>

Apresentando o último pedido de cada vendedor em um pandas.DataFrame():
>>> data = []
>>> vendedores = Vendedor.objects.all()
>>> for v in vendedores:
        ultimo_pedido = v.vend.last()
        data.append([v.nome, ultimo_pedido.id, ultimo_pedido.data, ultimo_pedido.tipo])

>>> ultimos_pedidos = pd.DataFrame(data, columns=['Vendedor', 'Id Pedido','Data',
                                                  'Tipo'])
>>> print(ultimos_pedidos)
    Vendedor  Id Pedido        Data Tipo
 0      foo           2  2019-04-18   Pd
 1      bar           4  2019-04-18   Sr

Comment: Gostaria de agradecer a ajuda. Segui a sua logica e deu certo. Já implementei no meu programa e funcionou!!
Comment: Primeiro muito obrigado pela ótima explicação. Estou iniciando na programação e não consegui replicar seu código em meu programa. aparece o seguinte erro:
Exception Type: AttributeError
Exception Value: 'NoneType' object has no attribute 'semana'
Vou postar aqui meu código original para ver se pode me dizer como corrigir meu erro.
Comment: Veja que meu codigo é um exemplo em um terminal python, não é para colocar em seu programa, vc pode ate acionar um terminal reproduzir "ipsis litteris"  o meu exemplo desde que esteja no diretorio do seu projeto e no mesmo ambiente. Sugiro que retire os comentarios feitos na pergunta, pois atrapalharia alguem que tivesse o mesmo problema, faça os comentários aqui, ou podemos ir para a área de chat.

Ultimo registro de cada objeto django


Integral of distribution followed by Bernoulli

Question: I am new to learning probability theory. Here I got confused but I had a sense of feeling it's correct. This is what I saw from the lecture notes.
Let $P\sim Bern(p), Q\sim Bern(q)$. Then is the integration making any sense?
$$\displaystyle\int \dfrac{(dP-dQ)^2}{2(dP+dQ)}= \dfrac{(p-q)^2}{2(p+q)}+\dfrac{(1+p-(1-q))^2}{2(1-p+1-q)}$$
and
$$\displaystyle\int dP = p+(1-p)=1$$
If they are correct, can anyone give me any explanation of some reference I can read? I tried to search it but didn't find anything related.
Comment: Xi'an's answer below is an excellent answer to the mathematics of the question.  One thing to note here is that if you are new to probability, it is a bad idea to try to learn it through measure theory/infinitesimals.  Start with a more basic text on probability theory first and then move to the above approach later.
Answer: The Bernoulli distribution is a finite support distribution with support $\{0,1\}$. The notation $\text{d}P$ and the concept of an integral are thus delicate in such a finite setting.
If $\mu$ denotes the counting measure on $\{0,1\}$, with
$$\int_A \text{d}\mu = \mathbb I_A(0) + \mathbb I_A(1)$$
the density of $P$ with respect to $\mu$ is
$$\frac{\text{d} P}{\text{d} \mu}(x)= p^x(1-p)^{1-x}\mathbb I_{\{0,1\}}(x)$$
and in particular
$$\int \text{d} P = \int \frac{\text{d} P}{\text{d} \mu}(x) {\text{d} \mu} = p+(1-p)=1$$
Hence
$$\dfrac{(\text{d} P-\text{d} Q)^2}{(\text{d} P+\text{d} Q)}=
\dfrac{(\frac{\text{d} P}{\text{d} \mu}-\frac{\text{d} Q}{\text{d} \mu})^2}{(\frac{\text{d} P}{\text{d} \mu}+\frac{\text{d} Q}{\text{d} \mu})}\text{d} \mu$$
and
\begin{align}\dfrac{(\frac{\text{d} P}{\text{d} \mu}-\frac{\text{d} Q}{\text{d} \mu})^2}{(\frac{\text{d} P}{\text{d} \mu}+\frac{\text{d} Q}{\text{d} \mu})}(x)&=
\dfrac{(p^x(1-p)^{1-x}-q^x(1-q)^{1-x})^2}{p^x(1-p)^{1-x}+q^x(1-q)^{1-x}}\mathbb I_{\{0,1\}}(x)\\
&=\dfrac{(p-q)^2}{p+q}\mathbb I_{1}(x)+\dfrac{((1-p)-(1-q))^2}{(1-p)+(1-q)}\mathbb I_{0}(x)\end{align}
This implies
\begin{align}\int\dfrac{(\text{d} P-\text{d} Q)^2}{(\text{d} P+\text{d} Q)}
&=\int \dfrac{(p-q)^2}{p+q}\mathbb I_{1}(x)\text{d}\mu+\int\dfrac{((1-p)-(1-q))^2}{(1-p)+(1-q)}\mathbb I_{0}(x)\text{d}\mu\\
&=\dfrac{(p-q)^2}{p+q}+\dfrac{(p-q)^2}{2-p-q}\end{align}
Comment: That's a great answer. Thanks a lot! Very appreciate it.


Difference between LHD and RHD of $f(x)$ and LHL and RHL of $f'(x)$

Question: Say, $f(x)$ =
$\left\{
 \begin{array}{ll}
  x^2 \sin(\frac{1}{x})  & \mbox{if } x \neq 0 \\
  0 & \mbox{if } x=0
 \end{array}
\right.$
Isn't LHD and RHD of $f(x)$ and LHL and RHL of $f'(x)$ same? Say at $x = 0.$
Thanks.
Comment: The question [Continuity of differentiable function $x^2\sin(1/x)$](https://math.stackexchange.com/questions/2212011/continuity-of-differentiable-function-x2-sin1-x) demonstrates that the LHD,RHD of $f(x)$ are in fact $0$ at $x=0$, but the LHL and RHL of $f'(x)$  at $0$ do not exist (the answer only shows that the limit doesn't exist using certain subsequences, but the general statement sort of follows once you see that $\sin , \cos \frac 1x$ oscillates too heavily)
Answer: For $x\in\mathbb R\setminus\{0\}$, $\lim_{a\to x^-} f(a)=f(x)=\lim_{a\to x^+} f(a)$  and $f'(x^-)=f'(x^+)$
At $x=0$ $\lim_{x\to 0^-} f(x)=0=\lim_{x\to 0^+} f(x)$
However, $f'(0^-)$ and $f'(0^+)$ don't exist, since $f'(x)= (2x)\sin{\frac{1}{x}}- \cos{\frac{1}{x}}$ when $x\neq0$.
For $f'(x)$ to be continuous at $x=0$, first it should exist at $x=0$ but it doesn't. So $f'(x)$ is not continuous at $x=0$.
$\mathbf {Edit:}$
No LHL of $f'(x)$ at $x=a$ and $f'(a^-)$ are not same.
$\mathbf {Reason:}$
LHD of $f(x)$ at $x=a$ is $$f'(a^-)=\lim_{h\to 0} \frac{f(a-h)-f(a)}{-h}$$
LHL of $f'(x)$ at $x=a$ is $$\lim_{x\to a^-} f'(x) = \lim_{x\to a^-} (\lim_{h\to 0} \frac{f(x-h)-f(x)}{-h})$$
You can notice the difference yourself.
Comment: @RajeshMarndi For a function to be continuous at some point, not only its left hand limit and right hand limit need to be equal at that point but the limit must also be equal to the value of function at that point.
Comment: $f'(x)=2x\sin(\frac{1}{x})-\cos(\frac{1}{x})$
Comment: f'(x) = $2x\  sin \frac{1}{x}\ - cos\frac{1}{x}$ ,

I mean LHD and RHD of f(x) decide the continuity of f'(x) at say x=0. That is, if LHD and RHD of f(x) are same at x=0 then f'(x) = $2x\  sin \frac{1}{x}\ - cos\frac{1}{x}$
 is continuous at x=0?


efficient collection lookup and index creation in mongodb

Question: I have a very high volume of data coming in to my database, up to 1,000 documents per second. And when I receive each one I am trying to efficiently check if there is already a collection for that type of document based on a field in the document and then if not I want to create a few indexes on that collection. Basically I am wondering how long it takes to create an index on an empty collection and if there is any faster way to check if there is a collection with a specified name.
def insert_new_doc(json_doc):
  collection_name = json_doc["collection_name"]
  coll = tlm_db_connection[collection_name]

  # create indexes in background if the collection doesn't exist
  if tlm_db_connection.system.namespaces.find( { name : collection_name } ) == None:
      coll.ensure_index([('time_stamp', pymongo.DESCENDING)], background = True)
      coll.ensure_index([('raw_value', pymongo.DESCENDING)], background = True)
      coll.ensure_index([('time_stamp', pymongo.DESCENDING), ('raw_value', pymongo.DESCENDING)], background = True)

  coll.insert(json_doc)

So that is the function I have. If I have ensure_index set to background = True any idea how long it blocks this thread calling that function?
Comment: They should not block at all, just receive acknowledgement from the server. The shell blocks for some silly reason I can't remember. The pymongo driver is not aync so technically it all blocks, but not for the duration of the index build. Which MongoDB version are you using at the server?
Comment: Okay that makes sense. I'm running 2.6.7.
Comment: So what are you asking then? How long does this take? Or how long does it "block" for? The possible ambiguity here was "does the call wait until the background build completes" which would have been a more succinct question. BTW The first index statement there is made redundant by the third index. You're just wasting space doing that since  queries that could use the first can also use the third index.
Comment: Yeah I see it was slightly ambiguous. The question was how long does the actual call to begin that index creation take. At the rate the data is coming in and how often this function is going to get called I am worried about it taking too long and dropping messages off the queue so I want to make it as fast as possible.
Answer: Creating new index on empty collection is quite fast, you can measure it by running following test
function howLong(){

    var t0 = new Date().valueOf();
    db.myCollection.ensureIndex({name: 1});
    var t1 = new Date().valueOf();

    return t1 - t0;
}

EnsureIndex will block until index is created. On my old laptop is says 0 :)
The same technique might be used to get approx "background" creation time of an index in mongoshell.

Background indexing operations run in the background so that other
  database operations can run while creating the index. However, the
  mongo shell session or connection where you are creating the index
  will block until the index build is complete.

http://docs.mongodb.org/manual/core/index-creation/#behavior
If you call ensureIndex early enough it will be quick, i.e. indexing 100 000 items on my machine (indexing by name of users collection) takes approx 350ms.
Subsequent calls to ensureIndex  (after it has been created ) will exit straightaway (with appropriate message) but I would not do it if i could. (i.e. the database is controlled by me and not shared with others) I would do the dedicated thread for index creation.
Since your collection will grow quite fast and you will create an index, make sure it fits into RAM see here so it might be worth to pre-aggregate the data while inserting.
Regarding checking the existence of collection, assuming your application is the only one writing to the db, you can list all the collection at the start-up and keep this information in memory.
There is interesting project from 10gen-Labs that seems to  addresses similar problems (java code though) Might be worth having look High Volume Data Feed
Comment: Great thanks for the response. Any idea if it is slower if I build the index in the background? And I was going to do that but I'm worried about multiple instances and my class not getting updated synchronously between instances.


How to use nginx with coreos docker containers and fleet

Question: I have three  docker containers configured..

ghost - a custom docker container which runs my ghost blog
ghost-data - docker container which holds all the persistent data.. content/* config.js, newrelic.js
jwilder/nginx-proxy - a docker container with nginx which sits in front of the ghost container

Using a single server I get how to link the nginx to the ghost container and get stuff served up through nginx.
However I want to start learning about coreos and migrate to a fleet of coreos servers. I know that in order to do this i need to write up service files for two of the containers (ghost, ghost-data) and make sure that ghost, and ghost-data are on the same host and nginx isn't.
As far as I understand, the whole point of fleet/clustering in coreos is uptime. containers will move from node to node as needed. The problem is, each of these nodes have their own IPs to the world. How do I get my DNS to know of these IPs and which IP has the nginx server on it?
The way I see it, something running like this..

node1 - runs nginx-proxy, public ip of 188.8.131.52
node2 - runs ghost, ghost-data, public ip of 126.96.36.199
node3 - idle node, public ip of 22.214.171.124

DNS is pointing example.com to 126.96.36.199
What happens when coreos decide to move nginx-proxy to node3 126.96.36.199?
How can i get the DNS to follow this? I'm sure in the service file there is a way to force nginx to stay on the same node, but that completely defeats the purpose doesn't it?
Answer: You have three main options:

Use a specific host for routing

This would be similar to your set up described above, but I'd make sure your unit file stays on that host with MachineID=abc123.... It's not super HA however, since you have a single point of failure.

Use a Cloud Load Balancer

If you're on a cloud provider, use a LB and set up a health check on port 80. Only the machine running on 80 will be given traffic. You'll have a bit of downtime (seconds to minutes) if the LB doesn't detect your failure quickly enough.

Two Layered Routing

Something similar to https://github.com/robszumski/varnish_etcd, but you can do it with varnish/nginx/haproxy and confd, or vulcand. Basically, you have a routing layer on each machine, that redirects to the backend's location dynamically.
Comment: Thank you, would you mind providing a few examples of Cloud Load Balancer services available? Ive checked with Google Cloud and it seems they only allow internal LB.


Questions concerning using regex in python

Question: I currently am reading in a string that starts with a number up to the next delimeter and testing if the string read in is a float. Now I have a few questions here as I believe my regex works I just think I am not using the proper method once it tries to do it.
my particular float will be in the format of
d+(.d+)?(E(+|-)?d+)?
r'(\d+(\.\d+)?([E][+|-]?\d+)?'

Above is the regular expression I'm using and it is correct for the specifications I have set up, but my issue is that I will be reading in bad values and I want to print an error that either prints the whole string as bad or prints the part that passed followed by an error with the incorrect part printing. When I try I get the error print
  print "ERROR: %s" % m.groups()
  TypeError: not all arguments converted during string formatting

I feel like I am missing something simple but I cannot figure out what.
So in summary I am trying to use the above regular expression to compare a read in number string to see if it is in the float form. If the whole string conforms I want to print it and if there is a bad part I want to print the whole string as an error or print the good part follow by printing the bad part out with an error message.
p = re.compile(r'(\d+)(\.\d+)?(([E][+-])?\d+)?')

def is_float(str):
m = p.match(str)
if m:
    print  (m.groups())
    return True

I have provided the piece of code I am working with perhaps there is an error there
Some sample inputs are:
3@33 //should print 3 then an error with @33 printed
3.435E-10 // should print the whole thing
0.45654 //should print the whole thing
4E-2 //should print the whole thing

Comment: `m.groups()` is an array, try `m.groups()[0]` (or just print `m.groups()`)
Answer: m.groups() is an array. NOT a string, m.groups(0) is the entire match, m.groups(1) is the 1st set of capturing brackets in your regex and so forth.
Try:
print(m.groups())

To see the different values at play

First thing
You're missing a closing bracket. It should be:
(\d+(\.\d+)?([E][+|-]?\d+)?)

Notice the one at the end after the final ?
I then tested it here:
https://regex101.com/r/jF1jX2/1 and it worked.
Comment: doing print(m.groups()) returns the same thing were it prints the first match but for some reason doesn't take the whole number. Just to be sure my regex is correct I am using 3.435E-10 but it is only printing out 3
Comment: That's a different error @bobHarding you need to share more of your code and more of the output for me to help.
Comment: I have added the code above. The string passed in is just read from a file that all I know about is if the first value in the string is a number. (So the task is to read the string in and test to see if the whole thing is a float. If it is return the float, if it isn't print the good part followed by a error message with the remaining part that is bad.
Comment: @bobHarding good! One more thing I need - can you give me some sample input? Then I can finally test your Regex and so forth
Comment: I have added some sample inputs. I know there is something wrong I am unsure of how to check to see if the whole thing matches or if a piece doesn't so that is also part of the problem. I really appreciate your help by the way!
Comment: @bobHarding that isn't how Regex works, error correcting is SIGNIFICANTLY harder to do, as is error detection. The absence of a match should tell you it is wrong. It looks like it should match the 3. let me check
Comment: Ok so if I do the match and then compare the length of the first match with the original string that will tell me if the whole string matched correct? because I could work around it using that.
Comment: see edits @bobHarding - note that `3@33` WILL match the `3` and stop. If you need start and end use `^yourregexhere$` the ^ means 'start of input' and '$' means end
Comment: @bobHarding loving the swastika avatar BTW! Don't forget to tick?
Comment: I see that and thank you for correcting it, upon testing it in regex101 I agree it does work, but when I run it I am still only printing 3 for the number 3.435E-10 when it should print the whole thing correct? I tried printing m.groups() and m.group(0) but neither produced the whole number
Comment: @bobHarding are you 100% sure about that? REGEX is greedy by default and it should match 3.435E-10 - in python. Did you try the ^ and $ I mentioned?
Comment: I go it working. I had commented out a piece of code for testing and that was producing the error thank you so much for your help!
Comment: Please don't forget to tick if this solved it @bobHarding
Answer: I have to say, I'd not bother with a regex at all. Given a string that is supposed to represent a float, I'd do
def is_float(str):
    try:
       f = float(str)
       return True
    except ValueError:
       return False

(BTW if the next step was going to be to convert an acceptable str to float,
just put the try .. except inline, use f if no exception is thrown and do whatever is appropriate when the exception is caught )
Also there's a mistake in your regex, in that it doesn't handle a leading "-" for a negative number (or a "+" for a positive one). Try ... except handles anything that you can throw at Python, using Python's rules.
Comment: There is no mistake the scenario I am using does not take negative numbers thus there is no leading + or - symbol ( I though I said that in the original post but I guess I lef it out my mistake). Will the f = float(str) account for a number like 3.453E-10?
Comment: Yes. Any string representing a python float constant gets converted.


How can I survey anonymous users before they can read content?

Question: I want to do a survey for all non-logged in users (a webform or something similar) before they can read a certain piece of content. I want authenticated users to not be bothered with it. These surveys will only be for selected pieces of content.
I have been looking around. I can't find a solution for Drupal 7. I'd like to use webform, but I am open to learning about different options.
Comment: you could probably use the rules module to achieve what you want.
Comment: Thanks, just generally looking at it it could be just what I need.
Comment: Are you looking to show a survey on every bit of protected content? Or just once before they sign up?
Comment: Custom module, cookie based. You will store the cookie when the survey gets done, and allow access to resource if authenticated or if cookie present. If cookie not present redirect to survey page.
Answer: Thanks for the help.
I ended up using the rules module along with rules url argument module.
I used the rules module to watch out for anonymous users, and query strings of "?surveycomplete=yes". I did this check for all nodes of my desired type that did not have a node reference to a webform.
If a user was anonymous and did not have the query string, then I redirected to the webform that the node was associated with.
To make the webform redirect appropriately when it was completed I changed the redirect location to the original node with the query string appended.
The downfalls with this approach is that every node that there is a 1 to 1 relationship for content to webforms when a many to 1 would be nice. Also, anyone could technically by pass the survey via appending the query string.


In F1, which tyre to start on if the "fastest time"-tyre is damaged?

Question: During Q3, if the driver loses a tyre due to a puncture, which tyre would he start with in the race the next day?
Secondly, if the pole sitter tries to improve his lap time in Q3 and while doing so loses the tyre due to a puncture in the final sector, which tyre would the driver start with in the main race?
I am not sure if P10 (former case) and P1 (latter case) drivers would be governed by the same rules.
Answer: Drivers who make it through to Q3 start the race on the set of tyres that they used to set their fastest time in Q2.
All other divers have free choice of tyre compound to start the race on.
Formula 1 - Sporting Regulations - 2021

24.4 m) At each Event where a sprint qualifying session is not scheduled, with the exception of any cars that are required to start the race from the pitlane, at the start of the race each car which qualified for Q3 must be fitted with the tyres with which the driver set his fastest time during Q2.
This will only be necessary for these cars if dry-weather tyres were used
to set the fastest time in Q2 and if dry-weather tyres are used at the start of the race.
Any such tyres damaged during Q2 will be inspected by the Technical Delegate who will decide, at his absolute discretion, whether any may be replaced and, if so, which tyres they should be replaced with.
A penalty under Article 47.3d) will be imposed on any driver whose car is not fitted with the tyres with which he set his fastest time in Q2 (except if damaged tyres have been replaced with the approval of the Technical Delegate).


Colunas invisíveis no Listview

Question: Tenho um listview com uma série de colunas, mas gostaria de ocultar algumas, como faço isso?
Comment: WPF? Win Forms? Web Forms?
Comment: Ana, resolveu seu problema ?
Comment: Olá @RovannLinhalis sim consegui! Obrigada a todos pela ajuda :)
Answer: Ao que me parece o ListView trabalha de forma semelhante ao TabControl, onde não é possível definir uma propriedade Visible.
Entretanto quando você adiciona uma coluna ao ListView, ela também é um objeto dentro do seu Form, que pode ser acessado pelo nome definido a ela.
No exemplo, utilizei um listView e adicionei 3 colunas, em seguida eu removo e adiciono a coluna de nome columnHeader2:
//Removendo
if (listView1.Columns.Contains(columnHeader2))
    listView1.Columns.Remove(columnHeader2);

//Adicionando
if (!listView1.Columns.Contains(columnHeader2))
{
    listView1.Columns.Add(columnHeader2);
    //Defino a posição dela novamente, caso contrário ela estará na última coluna.
    columnHeader2.DisplayIndex = 1;
}

Answer: Acho que só definindo a coluna como Width igual a 0, o que vai ocultá-la.
seuListView.Columns[indiceDaColuna].Width = 0;

Colunas invisíveis no Listview


Web development: how to show all errors (make errors verbose)?

Question: For example in Django:
S = request.POST.get("NonexistentField") # There is no error, it fails silently

How to show all errors in html, javascript, django?
Comment: make sure that `debug = True` in your settings file.  A good python tutorial would be indispensable.
Answer: Why should there be an error there? In Python, dict.get('key') is specifically designed not to raise an exception if the key doesn't exist. If you want to cause an exception, do dict['key'] directly.
Answer: try firebug for firefox, it can help debugging
Answer: If you want to see the errors just for development purposes, you might want to take a look at Django debug toolbar. It is a great tool that show you data about http headers, sql queries,etc.
https://github.com/django-debug-toolbar/django-debug-toolbar


JQueryUI Dialog Size

Question: I'm new to JQueryUI, and though I have a dialog working, it doesn't open at the size I think I'm specifying.  Why does setting the width and height when the dialog is defined not affect the initial size of the dialog?  How do I make it 600px by 500 px?
Here is the div that defines the dialog:

  <form> . . . </form>

Here is the JavaScript that makes a dialog of it:
$(function() {
    $("#dialog-form").dialog({
        autoOpen: false,
        maxWidth:600,
        maxHeight: 500,
        width: 600,
        height: 500,
        modal: true,
        buttons: {
            "Create": function() {
                $(this).dialog("close");
            },
            Cancel: function() {
                $(this).dialog("close");
            }
        },
        close: function() {
        }
    });

And the JavaScript that defines the button to open it:
$("#create-appt")
    .button()
    .click(function() {
        $("#dialog-form").dialog("open");
    });
});

Edit:
I see the problem now: this would have worked fine, except I was running it in Google Chrome using the --app=... command-line option, so it was not reloading the whole application.
Answer: Question: Why does setting the width and height when the dialog is defined not affect the initial size of the dialog?
Answer: It does...     what browser are you using and version of jQuery.
I cut/pasted your code from above into a small sample and it worked perfectly... I pasted the full sample below you can try it on your end.

        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
        <title>jQuery UI Example Page</title>
        <link type="text/css" href="css/ui-lightness/jquery-ui-1.8.11.custom.css"      rel="stylesheet" />

test

 this is my test

    <input type="button" id="create-appt" value="test"/>

Comment: Just so: it was working.  See my edit above for the reason I couldn't see it.
Answer: I don't know exactly what it's happening, but you can change a little bit your code and it'll produce the result you expect:
Instead of use autoOpen you can set these options on the onclick event:
$("#create-appt")
    .button()
    .click(function() {
        $("#dialog-form").dialog({width: 600,height:500});
    });

I hope this helps
best regards,
Marcelo Vismari
Comment: I tried it that way earlier, and it did the same thing; see my latest edit for the reason.

JQueryUI Dialog Size


USBView/ Device manager in python

Question: How can I access Device Manager in python, so that i can get the usb device's serial number/other info through python?
Answer: Instead of using the Device Manager (A graphical application), you can programmatically access information about USB devices via PyUSB:
import usb.core
allDevs = usb.core.find(find_all=True)

Now, iterate over allDevs to get information about connected devices.

USBView/ Device manager in python


Finding $3$ distinct prime numbers $a| (bc+b+c)$, $b|(ac+a+c)$, $c|(ab+a+b)$

Question: How to find $3$ prime numbers $a,b$ and $c$ such that:
$$a| (bc+b+c)$$
$$b|(ac+a+c)$$
$$c|(ab+a+b)$$
Comment: Do you want distinct primes? Else $a=b=c=\text{prime}$ will do the job.
Comment: 3 distinct prime numbers
Answer: There are no such primes:
Without loss of generality assume $a<b<c$. Clearly 2 cannot be one of the primes, so $a\geq 3$ , $b\geq 5$ and $c\geq 7$.
Now $abc+ab+bc+ca+a+b+c$ is divisible by $a$, by $b$ and by $c$ so it is also divisible by $abc$,
but this is impossible since
$1<\frac{abc+ab+bc+ca+a+b+c}{abc}<\frac{a+1}{a}\frac{b+1}{b}\frac{c+1}{c}\leq\frac{4}{3}\frac{6}{5}\frac{8}{7}<2$