How to set up a train schedule content type in Drupal 7?

Question: I'm trying to set up a site in Drupal 7 to list train schedules.
My concept is this: create a content type to manage each train.  I'm setting up each train like an airplane flight.  Each train leaves station A at a certain time, stops at a few other stations and ends at station X.
The content type needs to be able to handle which stations it will stop at (Taxonomy terms since values will be re-used) &  what time it will stop at each station.
As I said, the station names can be Taxonomy terms but I'm having trouble with the times.  While station names can be re-used, times each train stops at each station will vary.
Is there a module that will allow me to select a taxonomy term (individual station) and then allow an additional field to be edited on-the-fly to input a time?
I'm also open to alternative suggestions for setting this up.  Thanks!
Answer: This post is pretty old at this point, so it may no longer be an issue for you, but I'll try to answer it anyway.
The type of solution I'm imagining for this is what the Double Field module sounds like it does (though I cannot be certain since I have never used it). If this module would be able to do it, you'd want a field with taxonomy with a Date field to select the stop and time of that stop (and then be able to have multiple values for this field so you can select multiple stops and their times).
Otherwise, you could use Taxonomy if the trains have set times that they arrive (like they always arrive on the hour, quarter after, etc.). Otherwise, yeah, it wouldn't be realistic to use that if they can arrive at 12:53, 3:38 - if any time is possible.


How do I get Solr back up when indexes are locked and true doesn't work?

Question: I have a Solr slave that is running in Tomcat. I added a core, so I changed solr.xml. To reload it I decided to simply restart Tomcat using the Windows Services managament console.
After restarting Tomcat I keep getting the following exception:

org.apache.lucene.store.LockObtainFailedException: Index locked for
  write for core

I decided to temporarily change the solrconfig.xml for each core to add:
<unlockOnStartup>true</unlockOnStartup>

But no luck. Locking is set to native, so I can't go and remove lock files.

How do I get Solr up and running again?
How should I restart Solr to prevent this from happening?
Answer: Delete only write.log in data/index . Where is data directory is specified in conf/solrconfig.xml.
Comment: In case you are running as SolrCloud with HDFS, then the write lock is on hdfs path, and can be found via admin UI in location -> hdfs dfs -rm /my/path/write/lock
Answer: Clear the index directory and restart solr. It will work
Comment: Where can I find index directory?
Comment: Inside your solr core folder there will be a directory named data and within that there will be a folder named index
Comment: For others...I found files in ./example/solr/collection1/data/index/write.lock
./example/solr/development-edit/data/index/write.lock
./example/solr/development-live/data/index/write.lock
Answer: Delete file write.log in folder /data/index/ for your core then restart tomcat. It worked for me.
Answer: In case the other answers don't work, check your file permissions. In my case, I had to do a
chown -R tomcat6:tomcat6 /opt/solr/corename
Answer: Just deleted write.lock file under Solr > My Core > data > Index > write.lock file and restart solr server and it's worked.
Answer: My experience as I was a bit confused by the write.log with the .log ending in some answers (I was expecting a .lock ending).
I simply followed the instruction given by Solr:

Index dir '/var/solr/data/coreName/data/index/' of core 'coreName' is already locked. The most likely cause is another Solr server (or another solr core in this server)

Then I went to the directory /var/solr/data/coreName I searched find . -iname '*lock' and then delete those files that were clearly lock files.
Restarted solr and it worked.


TextField became collapse

Question: I have scrollview on which multiple text field are there. But when my KeyBoard shown my all text field and label collapse
<code> func keyboardWillShow(sender: NSNotification) {
            scroll.frame = CGRectMake(scroll.frame.origin.x, scroll.frame.origin.y, scroll.frame.size.width, self.view.frame.size.height - 216)
        }

        func keyboardWillHide(sender: NSNotification) {

            scroll.frame = CGRectMake(scroll.frame.origin.x, scroll.frame.origin.y, scroll.frame.size.width, self.view.frame.size.height)
        }
</code>
Answer: self.view.frame.size.height - 216)
Did you notice this part in your this line
<code> scroll.frame = CGRectMake(scroll.frame.origin.x, scroll.frame.origin.y, scroll.frame.size.width, self.view.frame.size.height - 216)
</code>
When you keyboard appears at that time you are changing the height of view. And also don't check in simulator. Run on actual device.
you need to handle it in proper way. for ex : How do I scroll the UIScrollView when the keyboard appears?

TextField became collapse


arredondamentos em javascript

Question: Como posso fazer arredondamentos em JavaScript a 2 casas que arredonde para cima se o ultimo for um 5.
Por exemplo : 111.115 = 111.12.
se usar o (111.115).toFixed(2) o resultado é 111.11 que esta errado.
já tentei o Math.round mas também não funciona.
Alguém poderia ajudar?
Comment: @LeandroPaixão ele espera 111.12 e não 112, o AP deseja trabalhar com "float". RIHAB, o toFixed está correto, se fizer `(111.116).toFixed(2)` terá 111.12, porque o valor está em 6 (ultimo digito), se fizer `(111.1159).toFixed(2)` ou `(111.11590).toFixed(2)` vai notar que também irá obter o valor 111.12, isso se deve a precisão, recomendo que leia sobre *IEEE 754*.
Comment: Tenta usar o `Math.ceil(111.115)`.
Comment: isso retorna 112.
Comment: `(111.115).toFixed(20) === '111.11499999999999488409'`. Por isso.
Answer: O toFixed está correto no resultado apresentado, se fizer (111.116).toFixed(2) terá 111.12, porque o valor está em 6 (ultimo digito), se fizer (111.1159).toFixed(2) ou (111.11590).toFixed(2) vai notar que também irá obter o valor 111.12, recomendo que leia sobre IEEE 754, sugestão de leitura:

O que é IEEE 754?

Para arredondar para cima pode usar o Math.ceil, mas para isso é necessário que o valor seja um inteiro, então se você precisa que esse arredondamento seja a partir da terceira casa, você pode multiplicar por 1000, aplicar o Math.ceil para arredondar e depois dividir novamente, obtendo o resultado aproximado (que dependendo do caso poderá usar toFixed posteriormente):

console.log(Math.ceil(16.422 * 1000) / 1000);
console.log(Math.ceil(115.1 * 1000) / 1000);
console.log(Math.ceil(115.11 * 1000) / 1000);
console.log(Math.ceil(115.111 * 1000) / 1000);
console.log(Math.ceil(115.114 * 1000) / 1000);
console.log(Math.ceil(115.1149 * 1000) / 1000);
console.log(Math.ceil(115.115 * 1000) / 1000);

Se deseja apenas arredondar, ao invés do Math.ceil (arredonda para cima), use o Math.round, mas antes multiplique por 1000, isso se deseja que seja a partir a da terceira casa, exemplos:

console.log('16.422 -> ', arredondar(16.422));
console.log('115.114 -> ', arredondar(115.114));
console.log('115.1146 -> ', arredondar(115.1146));
console.log('115.1149 -> ', arredondar(115.1149));
console.log('115.115 -> ', arredondar(115.115));
console.log('115.1151 -> ', arredondar(115.1151));
console.log('115.1159 -> ', arredondar(115.1159));
console.log('115.116 -> ', arredondar(115.116));
console.log('115.1116 -> ', arredondar(115.1116));

function arredondar(valor) {
   return Math.round(valor * 1000) / 1000;
}

Note que se o valor for 115.1116 ele irá arredondar para aproximadamente 115.112, então no caso depende muito de como você deseja trabalhar (a partir de qual casa decimal)
Comment: top, é isso mesmo. muito obrigado
Comment: resolveu um problema mas estragou outro, agora se o valor for 16.422 ele arredonda para 16.43. Nao estou a perceber isto
Comment: eu preciso que ele arredonde de 0-4 para baixo e de 5 a 9 para cima. ex:

111.122 = 111.12, 111.123= 111.12 ;;; 111.125=111.13; 111.126=111.13; 111.128=111.13
Comment: ´´´´´´if(taxaIvaFormatado == "23.0000"){
    i23 = (valorFormatadoComDescontoMaisDescontoGlobalXiVA*100)/100;
     iva23 += i23;
     total23 = Math.round(iva23 * 100) / 100;
     console.log("total23 " + total23)
}´´´´

isto se o iva23 for 111.125 retorna 111.12 e eu quero que retorne 111.13
Comment: @RIHAB como expliquei na pergunta, depende de qual casa decimal você deseja o resultado, no entanto cada proposta que você apresentou aqui são variadas. Vou tentar editar mais uma vez para ver se atende a sua necessidade.
Comment: eu queria que o valor final ficasse a 2 casas decimais, e queria que se a a 3 casa fosse >=5 ele arredondasse para cima. se fosse < que 5 ele arredondasse para baixo como nos exemplos que eu dei.

ex:
111.122 = 111.12,
111.123= 111.12 ;;;
111.125=111.13;
111.126=111.13;
111.128=111.13
Comment: @RIHAB isso tudo é devido a precisão, note que `(111.1150001).toFixed(2)` vai gerar `111.12`, enquanto `(111.115).toFixed(2)` vai gerar `111.11`, geralmente com final `.15`, `.115` ou `.1150000`, ou qualquer semelhante, vai ser arredondado para baixo (como pode ver no toFixed, exemplos: `0.15.toFixed(1); 0.15000.toFixed(1)`), se fizer um `0.15.toFixed(18)` vai notar que pe exibido `0.149999999999999994`, resumindo "computadores", sabe como é, né? :) Leia o: https://pt.stackoverflow.com/q/493487/3635

arredondamentos em javascript


Admissible Empirical Bayes Examples

Question: I would like to hear about a few simple empirical bayes estimators that are admissible for high (i.e. at least 3) dimensional parameter space.
What are some textbook lollipop examples to study for beginners with easy derivations?
Comment: Efron's computer age statistical inference ( free pdf) has several chapters on empirical bayes with plenty of examples
Answer:
The question has no clear answer because the empirical Bayes
formulation does not & cannot specify how the hyperparameter is
estimated.

Take the simplest Normal mean estimation problem. When$$X\sim\mathcal N_p(\theta,I_p)\qquad\qquad\theta\sim\mathcal N_p(0,\sigma^2 I_p)$$the Bayes estimator of $\theta$ is$$\delta^\pi(x)=\frac{\sigma^2}{1+\sigma^2}x$$
If $\sigma$ is unknown, a corresponding empirical Bayes estimator is therefore$$\frac{\hat\sigma^2}{1+\hat\sigma^2}x$$where $\hat\sigma^2$ is an estimator of $\sigma^2$ based on the marginal distribution of $x$
$$m(x|\sigma)=\int f(x|\theta) \pi(\theta|\sigma)\,\text{d}\theta$$
But since there is no constraint on the choice of $\hat\sigma^2$, this estimator can be any (positive) function of $x$ and the collection of empirical Bayes estimators thus includes all shrinkage estimators and therefore all admissible generalised Bayes estimators of $\theta$ (see Strawderman and Cohen, 1971).
For instance, the admissible minimax Bayes estimators of Strawderman (1971)
$$\delta_c(x)=\left[ 1 - \frac{\int_0^1 \lambda^{p/2-c+1}e^{-\lambda|x|^2}\text{d}\lambda}{\int_0^1 \lambda^{p/2-c}e^{-\lambda|x|^2}\text{d}\lambda} \right]x\qquad \text{where}\ 3-p/2\le c\le 2$$
are shrinkage estimators that can all be interpreted as empirical Bayes estimators, whatever the constant $c$ is. The estimator $\delta_c$ is furthermore a proper Bayes estimator when $c<1$ (and $p>5$) and possibly a generalised Bayes estimator otherwise. It stems from a hierarchical prior modelling
$$\underbrace{\theta|\lambda\sim\mathcal N_p(0,\lambda^{-1}(1-\lambda) I_p)}_\text{first level}\qquad
\underbrace{\lambda\sim \pi(\lambda)\propto (c+1)\lambda^{-c}}_\text{second level}$$with the hierarchical Bayes estimator above expressed as
$$\delta_c(x)=\left( 1 - \mathbb E[\lambda|x]\right)x$$
A highly interesting if not completely connected paper by Petrone, Rousseau and Scricciolo (2012) studies the connection between empirical Bayes "posteriors" and actual Bayes posteriors, deriving approaches to asymptotically agree (in the number of parameters $n$). They first point out a relevant counterexample of Scott and Berger (2010), for variable selection in regression models.

...consider a Bayesian approach where variable selection is based on a
  vector of inclusion $γ∈{0,1}^k$ which selects among k potential
  regressors, and the prior on $γ= (γ_1, . . . , γ_k)$ assumes that the
  $γ_i$ are independent Bernoulli with parameter $λ$. Scott and Berger
  (2010) compare this empirical Bayes approach with a hierarchical Bayes
  procedure that assigns a prior on λ. Surprisingly, they (...) show
  that the empirical Bayes posterior distribution on the set of models
  that can be degenerate on the null model ($γ= (0, . . . ,0)$) or on
  the full model ($γ= (1, . . . ,1)$).

They also produce general conditions for the empirical Bayes posterior to be consistent, which is a necessary condition for (asymptotic) admissibility. And study as an example the Normal mean problem when
$$X_i\sim\mathcal N(\theta,1)\qquad\theta|\lambda\sim\mathcal N(\mu,\tau^2)$$
with three situations

$\mu=\lambda$ and $\tau$ fixed, in which case the MLE of $\mu$ is $\bar X_n$ and the empirical Bayes posterior is consistent
$\tau=\lambda$ and $\mu$ is fixed, in which case the empirical Bayes posterior is only consistent when $\mu$ differs from the true value of the parameter, $m\ne\theta_0$
$\lambda=(\mu,\tau)$, in which case the empirical Bayes posterior is degenerate at $\bar X_n$

As noted in this other answer of mine, there may exist admissible estimators that are not Bayes or generalised Bayes estimators.

Admissible Empirical Bayes Examples


How can I tag a user in the caption of a photo uploaded using Facebook's PHP SDK?

Question: The question says it all. I followed this tutorial:
http://www.webspeaks.in/2011/12/upload-photos-to-facebook-fan-page.html
And I managed to do it. Now I want it so that whenever someone uploads a photo, the user is tagged in the caption of the photo--just in the caption, so anyone viewing my page can know who the user was that uploaded the picture. Can this be done?
Answer: I think this has already been answered here: How can I tag friends in uploaded photo using facebook php SDK
Like its stated there check the documentation for how to use tags here: https://developers.facebook.com/docs/reference/api/photo/#tags
Just doing this in my head from scratch (not tested)
<code>$photo = $facebook->api($album_id . '/photos', 'post', $args);
$argstag = array('to' => $user);
$datatag = $facebook->api('/' . $photo['id'] . '/tags', 'post', $argstag);
</code>
Comment: I found that link when I was doing research earlier. Can you please provide me with the code as I am still a newbie? Thanks.
Comment: Hi I added your above code to:

$photo = $facebook->api($album_id . '/photos', 'post', $args);
  $argstag = array('to' => $user);
  $datatag = $facebook->api('/' . $photo['id'] . '/tags', 'post', $argstag);
  if( is_array( $photo ) && !empty( $photo['id'] ) ){
   echo 'Click here to watch this photo on Facebook.';
  }
 }

and it gave the the following error:

atal error: Uncaught OAuthException: (#100) null does not resolve to a valid user ID thrown
Comment: you need to define $user with the facebook users id
Comment: Can you provide me the code please? Sorry if I am being too cheeky :-)
Comment: http://stackoverflow.com/questions/5780416/how-get-facebook-user-id-from-my-application


Regex: get subdomain or domain but not www

Question: I'm trying to create a regex that captures a subdomain, not www, or the domain.
So, it should be able to match
client.com => client
subdomain.client.com => subdomain
www.client.com => client
But I have some trouble eliminating the optional www with a lookahead.
Currently, I have this:
/((?!www)([^\.]+)\.)?([^\.]+)\.(?:(co?|nl|be|fr|de|es|it|pt|gov|org)).*/

https://regex101.com/r/d4qPNV/2
but I can't seem to eliminate the www capture. Any suggestions?
Answer: ((?!w+)([^\.]+)\.)?([^\.]+)\.(?:(co?|nl|be|fr|de|es|it|pt|gov|org)).*
If you don't care about excluding subdomains that would be "wwwwww" and the like.
or
([^w{3}+]+\.)?([^\.]+)\.(?:(co?|nl|be|fr|de|es|it|pt|gov|org)).*
If you really only want it to exclude "www".
Comment: I'm currently using

`^(?:(?!w{3})([^.]+)\.)(?:([^.]+)\.)?([^.]+)\.(?:(com?\.[a-z]{2}|[a-z]{2,3}))$`

to match
`client.mydomain.com => client`
`client.acc.mydomain.com => client`
`www.mydomain.com => mydomain`

It's not capturing the mydomain and making it optional:
`^(?:(?!w{3})([^.]+)\.)?(?:([^.]+)\.)?([^.]+)\.(?:(com?\.[a-z]{2}|[a-z]{2,3}))$`

makes it capture `www`.


Does GarageBand let me record my own vocal/instrument region as a loop?

Question: As a novice to DAWs I recently put together a recording of a song in Garageband. I wanted to record say 'chorus acoustic guitar' once and build the song structure using this multiple times.
All I could find was the ability to copy-paste it manually to each bar location - each copy was separate so if I wanted to re-record it or change the levels, I had to repeat the entire process.
Is this a feature I'm missing? I know 'loops' is a feature of GB but I have no experience with electronic music and am not sure if you can do this with custom recorded audio?
I am considering upgrading to a more serious DAW so as a side-question, do more powerful DAWs provide this?
Comment: idk Garage Band well enough, but many DAWs can use 'ghost' copies, so if the original changes, so do all the ghosts [or at least ask you keep/overwrite] See if a cmd drag or ctl or shift… changes the resulting copy.
Answer: This link explains how to make an audio or software instrument region into a loop in GB. I tested it and it works:
https://support.apple.com/kb/PH25033?locale=en_US&viewlocale=en_US
After creating one, it will appear in your library under the name you assign it.
Comment: Thanks John I had not realised you could do this. I'll investigate.
Comment: Just open the loop browser first then drag the region towards it and it'll open up the window. There's also an option to do it with a menu selection. If you click the loop box at the top the loop will tempo adjust to whichever song you import it  into.
Comment: Also, if GB does everything you need there's no reason to change for now. Logic Pro is a full featured extension of GarageBand (GB even looks like Logic with a bunch of buttons and sliders missing, lol) but do some homework, there are a lot of great DAW's available these days.


Página PHP retornando HTTP/1.1 200 OK

Question: Após consulta SQL e retorno de dados usando JSON, utilizando o navegador Firefox é escrito o seguinte na tela:
0

HTTP/1.1 200 OK
Date: Sun, 12 Jun 2016 22:52:42 GMT
Server: Apache
X-Powered-By: PHP/5.3.28
Keep-Alive: timeout=5
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: text/html

41
{"AQUI RETORNA O MEU":"JSON E ACABA"}

Utilizando o Chrome Mobile em um smartphone esses dados de HTTP não aparecem, retornando apenas o JSON como desejado.
Página de testes: www.megaprotecaoveicular.com.br/mobile/data.php
Agradeço a ajuda desde já.
Comment: Sem o código que faz o envio dessa mensagem não tem como a gente saber o que acontece.
Comment: cara que chato esse 0
Comment: jbueno, vou editar adicionando o código, mas antes funcionava normalmente com o mesmo código. E de tudo isso que ele retorna, somente o JSON é o que imprimi.
Comment: Opa! No navegador Chrome Mobile retornou somente o JSON, que era o pretendido. No Firefox para desktop continua mostrando os outros dados. Concluo então que o "erro" não é no código... Só por conhecimento, vocês fazem ideia do porquê isso acontece? '-'
Answer: Cabeçalhos do servidor e não deveriam ser apresentados no lado cliente.
HTTP / 1.1 200 OK

Significa que o servidor está respondendo utilizando o protocolo HTTP versão 1.1. 200 é o código usado quando tudo está ok.
Content-Length: 0

O tamanho do conteúdo (neste caso 0 bytes)
Keep-Alive: timeout = 5, max = 100

Quanto tempo a conexão permanecerá aberta.
Connection: Keep-Alive

Informa que a conexão permanecerá aberta
Content-Type: text/plain

Qual é o tipo MIME do conteúdo (HTML, no caso, é: text/html)
Documentação aqui (RFC 2616)
Informações mais compreensíveis com 23 links de referência: HTTP Headers
Motivo de estar aparecendo no lado cliente (navegador): versão desatualizada do Mozilla Firefox. O erro foi relatado por diversos usuários no ano de 2011 e corrigido na versão 9 do navegador, ou pelo menos parou de apresentar o problema desde então.

Página PHP retornando HTTP/1.1 200 OK


Como pegar dados do header em post PHP

Question: Galera, estou tendo uma dificuldade em pegar um dado especifico do header enviado pela Pagar.me.
Ao enviar um postback para o servidor do site, preciso usar a assinatura enviada no Header, no caso a X-Hub-Signature que contém sha1=435634896597u46y34t5gfds2891374.
Porém não sei como fazer para pegar o conteúdo do X-Hub-Signature.
Tentei usar o getallheaders() com um foreach para tentar buscar, mas sem sucesso.
Também tentei pegar pelo json, já que eles possuem uma api com essa opção também, que também fica la, porém não consegui pegar o conteúdo.
Abaixo, vou colocar o código em json também para vocês verem.
[{"object":"postback","status":"success","model":"transaction","model_id":"8887765","headers":"{\"Content-Type\":\"application/x-www-form-urlencoded\",\"X-PagarMe-Event\":\"transaction_status_changed\",\"X-Hub-Signature\":\"sha1=435634896597u46y34t5gfds2891374\",\"User-Agent\":\"PagarMe-Hookshot/1.0\"}....

Espero que consigam me ajudar.
Answer: Eu faria algo assim no frontend com javascript:
 var TRANSACTION_TYPE = 'boleto',
     ENCRYPTION_KEY = 'SUA_ENCRYPTION_KEY',
     URL_POST_BACK = 'url-retorno-que-marca-pago',
     URL_PAGAMENTO = 'url-pagamento',
     PAYMENT_PRICE = 20.00,
     ID_PRODUTO = '123',
     TITULO_PRODUTO = 'Produto XYZ',
     DISPLAY_SUCCESS = { /* variável para mostrar layout
                            de sucesso para a forma de pagamento
                           (no caso do boleto, mostraria o botão do boleto)
                      */
        is_boleto:false,
        is_credit_card:false
        };

      var registerPayment = function(data) {
                if (data.transaction_type == 'credit_card') {
                    DISPLAY_SUCCESS.is_credit_card = true;
                }
         var xhttp = new XMLHttpRequest();
             xhttp.onreadystatechange = function() {
              if (this.readyState == 4 && this.status == 200) {
                      var rtn = JSON.parse(this.responseText);
                      if (data.transaction_type == 'credit_card') {
                           if (rtn.status_payment == 'paid') {
                               alert('Pagamento foi efetuado com sucesso');
                                DISPLAY_SUCCESS.is_credit_card = true;

                             } else if(rtn.status_payment == 'authorized') {
                                 postBackCaptureResultCreditCard(data);
                             } else {
                                 //entra num loop até concluir o pagamento (caso haja um retorno diferente de pago que não seja um erro)...
                                 postBackCaptureResultCreditCard(data);
                             }

                        } else {
                            //boleto
                            if (rtn.status_payment == 'paid') {
                               alert('Pagamento foi efetudo com sucesso');
                             } else {
                               DISPLAY_SUCCESS.is_boleto = true;
                               $scope.form.boleto_url = rtn.boleto_url;
                               $scope.form.boleto_code = rtn.boleto_barcode;
                             }
                        }
               }
             xhttp.open("POST",URL_PAGAMENTO, true);
             xhttp.send();
    };

    function paymentAction() {

           var checkout = new PagarMeCheckout.Checkout({
              encryption_key: ENCRYPTION_KEY,
              success: function(data) {

               var saveData = {
                         post_back_url: URL_POST_BACK,
                         transaction_token: data.token,
                         price:PAYMENT_PRICE,
                         transaction_type:TRANSACTION_TYPE,
                         api_payment:URL_PAGAMENTO,
               }
               registerPayment(saveData);
           },
           error: function(err) {
             console.log(err);
           },
           close: function() {
            console.log('Fecha janela modal de pagamento');
           });

          var amount = Number(
              parseFloat(PAYMENT_PRICE)
              .toFixed(2)
              .replace('.', '')
         );

        // Obs.: é necessário passar os valores boolean como string
        checkout.open({
                       amount: amount,
                       buttonText: 'Pagar',
                       buttonClass: 'botao-pagamento',
                       customerData: 'true',
                       createToken: 'true',
                       maxInstallments: 10,
                       freeInstallments: 10,
                       defaultInstallment: 1,
                       uiColor:'#1E90FF',
                       paymentMethods: 'credit_card,boleto',
                       postback_url:URL_POST_BACK,
                       items: [
                                  {
                                     id: ID_PRODUTO,
                                     title: TITULO_PRODUTO,
                                     unit_price: amount,
                                     quantity: 1,
                                     tangible: true
                                  }
                      ]

        });

    }

E no backend na camada do Model:
    namespace App\Http\Services;

        use PagarMe;
        use App\EntidadeBancoDados;

        class PagarmeServices
        {

            protected $pagarme;

            public function __construct()
            {
                $api_key = getenv('PAGARME_API_KEY');
                $this->pagarme = new PagarMe\Client($api_key);

            }

            public function transaction($data)
            {
                $data_pagarme = false;
                $return["status"] = false;

                EntidadeBancoDados::insertTransaction($data);

                $data_pagarme = $this->getTransactionById($data['transaction_id']);
                if($data_pagarme->status == 'authorized'){
                    $data_pagarme = $this->pagarme->transactions()->capture([
                        'id' => $data['transaction_id'],
                        'amount' => $data['amount']
                    ]);
                }

                if ($data_pagarme) {

       EntidadeBancoDados::updateTypeTransactionAndBillet($data['id'], $data_pagarme->status ,$data_pagarme->tid, $data_pagarme->boleto_url);
                    $return["status"] = true;
                    $return["status_payment"] = $data_pagarme->status;
                    $return["payment_method"] = $data_pagarme->payment_method;
                    $return["boleto_url"] = $data_pagarme->boleto_url;
                    $return["boleto_barcode"] = $data_pagarme->boleto_barcode;

                }

                return $return;

            }

            public function postback($data)
            {

                $id = isset($data['id']) ? $data['id'] : false;
                $current_status = isset($data['current_status']) ? $data['current_status'] : false;

                if ($id && $current_status) {

 EntidadeBancoDados::updateTypeTransaction($id,$current_status);
                }
            }

            public function getTransactionById($id){
                try{

                    $transaction = $this->pagarme->transactions()->get([
                        'id' => $id
                    ]);

                    return $transaction;
                } catch (\Throwable $th) {
                    return false;
                }

            }

        }

Answer: Para conseguir solucionar, tentei usar $_SERVER['X-Hub-Signature'] acabou dando certo.

Como pegar dados do header em post PHP


Fazer delete via php

Question: Estou programando uma página em php e estou com a seguinte duvida fiz um insert no meu banco de dados e criei uma
 a dentro dele estão sendo exibidos meus dados esse seria o código:

                    id
                    Produto
                    valor
                    data
                    apagar

                <?php
                    include ('conection/config.php');

                    $conn = mysqli_connect ($varBDhostname,$varBDusername,$varBDpassword,$varBDdatabase);

                    $result = mysqli_query($conn,'SELECT *FROM tbl_produtos') or die(mysqli_error());
                    while ($row = mysqli_fetch_assoc($result)){
                 ?>

                    <?php echo $row["id"]?>
                    <?php echo $row["nome"]?>
                    <?php echo $row["valor"]?>
                    <?php echo $row["dh"]?>

                <?php } ?>

minhas conexões estão funcionando normalmente porem precisaria colocar uma coluna que contenha um botão de deletar só que minha duvida e a seguinte deverei fazer uma nova conexão pois eu percebi que minha tag
 está dentro do while que faz o select logo não sei onde ficaria a do delete sendo que deveria aproveitar a mesma tabela pelo menos é oque eu acho como poderia fazer esses deletes
Fiz esse delete e aqui:

        <form action="conection/inserir.php" method="post" id="form">

Inserir Produtos

            <input type="text" name="nome" id="produto" placeholder="Produto" maxlength="30" required/>
            <input type="number" name="valor" id="valor" placeholder="valor" maxlength="10" required/>

            <input type="submit" value="cadastrar" name="cadastro">
        </form>

        <?
            include ('conection/config.php');
            $conn = mysqli_connect ($varBDhostname,$varBDusername,$varBDpassword,$varBDdatabase);

            if(isset($_GET['deletar'])):
                $id = $_GET['deletar'];
                $delete = mysqli_query($conn,'DELETE FROM tbl_produtos WHERE id = {$id}') or die(mysqli_error());

                    if($delete):
                        echo "Registro removido";
                        endif;
            endif;

            ?>

                    id
                    Produto
                    valor
                    data
                    apagar

                <?php

                    $result = mysqli_query($conn,'SELECT *FROM tbl_produtos') or die(mysqli_error());
                    while ($row = mysqli_fetch_assoc($result)){
                 ?>

                    <?php echo $row["id"]?>
                    <?php echo $row["nome"]?>
                    <?php echo $row["valor"]?>
                    <?php echo $row["dh"]?>
                    <a href="?deletar=<?php echo $row["id"]?>">Deletar

                <?php } ?>

E deu esses erros aqui:
Comment: Conexão se faz uma vez só no topo da página.
Não precisa chamar de novo o arquivo.
Coloque uma outra coluna `td` com o LINK para deletar.
Comment: quando voce fala link sera um href
Comment: Exatamente. ` Deletar `
Comment: @Kirito Postei uma resposta. Note que inseri a conexão no topo do arquivo e elaborei um href para que consigas buscar o Id do registro e faça a exclusão conforme o id passado.
Answer: Você pode criar dessa forma:
<?
include ('conection/config.php');
$conn = mysqli_connect ($varBDhostname,$varBDusername,$varBDpassword,$varBDdatabase);

if(isset($_GET['deletar'])):
    $id = $_GET['deletar'];
    $delete = mysqli_query($conn,'DELETE FROM tbl_produtos WHERE id = {$id}') or die(mysqli_error());

        if($delete):
            echo "Registro removido";
            endif;
endif;

?>

            id
            Produto
            valor
            data
            apagar

        <?php

            $result = mysqli_query($conn,'SELECT *FROM tbl_produtos') or die(mysqli_error());
            while ($row = mysqli_fetch_assoc($result)){
         ?>

            <?php echo $row["id"]?>
            <?php echo $row["nome"]?>
            <?php echo $row["valor"]?>
            <?php echo $row["dh"]?>
            <a href="?deletar=<?php echo $row["id"]?>">Deletar Registro

        <?php } ?>

A não ser que você tenha alguma função de deletar ou esteja trabalhando com algum framework, mas na base, seria isso...
Creio que deverá solucionar sua questão e dúvida.
Comment: na segunda linha, tente fazer o seguinte: if($conn){ echo "conectado"; } else { echo "sem conexao"; }
Comment: amigo editei a minha pergunt e adicionei oque vc disse mais da um erro da uma olhadinha
Comment: vc diz na sugunda linha onde vc tem aquela condicao  if(isset($_GET['deletar'])): ou  $conn = mysqli_connect ($varBDhostname,$varBDusername,$varBDpassword,$varBDdatabase);
Comment: pode colocar antes desse if(isset($_GET['deletar'])): , coloque: if($conn){ echo "conectado"; } else { echo "sem conexao"; } –
Comment: coloquei e nada amigo
Comment: Mas aparece conectado?
Comment: nao aparece nao amigo olhei bem aqui e nao aparece
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/26813/discussion-between-andre-baill-and-kirito).
Comment: ok amigo ja tou logado la no chat[

Fazer delete via php


/var/log/squid/access.log is empty when I use proxy from remote computers

Question: I have configured squid to work as NAT using
apt-get install squid
iptables -t nat -A PREROUTING -i eth1 -p tcp -m tcp --dport 80 -j DNAT --to-destination 192.168.0.1:3128
iptables -t nat -A PREROUTING -i eth0 -p tcp -m tcp --dport 80 -j REDIRECT --to-ports 3128

Have added to /etc/squid/squid.conf
acl internal_network src 192.168.0.0/24
http_access allow internal_network

access_log /var/log/squid/access.log squid

Problem: /var/log/squid/access.log is empty when I use proxy from remote computers.
When I make telnet localhost 3128 then it does write to log:
1308144959.810      0 127.0.0.1 TCP_DENIED/400 1693 NONE NONE:// - NONE/- text/html
So the problem is that logging is somehow turned off for remote proxy use.
Permissions:

/var/log/squid/ - 0777
/var/log/squid/* - 0666

cat /var/log/squid/cache.log | grep access
gives
logfileOpen: opening log /var/log/squid/access.log
without any errors.
Answer: My network interface was br0, not eth0 or eth1
iptables -t nat -A PREROUTING -i br0 -p tcp -m tcp --dport 80 -j DNAT --to-destination 192.168.0.1:3128
fixed the problem.


Laravel get array in blade with such 'bns:OrderId' names in it?

Question: I get a array from a external company to handle in my laravel application
The incoming json has names like 'bns:OrderId' in it ?
blade give a error when i try to access     {{ $order->bns:OrderId }}
How can i handle this??
Controller :
    public function getBolOrders()
{
    // or live API: https://plazaapi.bol.com
    $url = 'https://test-plazaapi.bol.com';
    $uri = '/services/rest/orders/v1/open';

    // your public key
    $public_key = '<public key>';

    //your private key
    $private_key = '<private key>';

    $port = 443;
    $contenttype = 'application/xml';
    $date = gmdate('D, d M Y H:i:s T');
    $httpmethod = 'GET';

    $signature_string = $httpmethod . "\n\n";
    $signature_string .= $contenttype . "\n";
    $signature_string .= $date."\n";
    $signature_string .= "x-bol-date:" . $date . "\n";
    $signature_string .= $uri;
    $signature = $public_key.':'.base64_encode(hash_hmac('SHA256', $signature_string, $private_key, true));

    // Setup CURL (One can also opt to use sockets or http libraries, but CURL is a versatile, widespread solution)
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: ".$contenttype, "X-BOL-Date:".$date, "X-BOL-Authorization: ".$signature));
    curl_setopt($ch, CURLOPT_URL, $url.$uri);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_PORT, $port);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

    $result = curl_exec($ch);
    $orders = fopen("orders.xml", "w");
    fwrite($orders, $result);
    fclose($orders);
    if(curl_errno($ch)) {
       print_r(curl_errno($ch), true);
    }
// Clean up after ourselves
    curl_close($ch);
// Convert XML TO JSON
    $xmlNode = simplexml_load_file('orders.xml');
    $arrayData = xmlToArray($xmlNode);
    $OpenOrder = $arrayData['OpenOrders']['bns:OpenOrder'];
//    dd($OpenOrder);
// Goto view
    return view('bol.open-orders', compact('OpenOrder'));
}

dd from array :
array:2 [▼
  0 => array:6 [▼
   "bns:OrderId" => "123"
   "bns:DateTimeCustomer" => "2016-11-07T15:20:08.904"
   "bns:DateTimeDropShipper" => "2016-11-07T15:20:08.904"
   "bns:Paid" => "true"
   "bns:Buyer" => array:2 [▶]
   "bns:OpenOrderItems" => array:1 [▶]
 ]
 1 => array:6 [▼
   "bns:OrderId" => "321"
   "bns:DateTimeCustomer" => "2016-11-07T15:20:08.904"
   "bns:DateTimeDropShipper" => "2016-11-07T15:20:08.904"
   "bns:Paid" => "false"
   "bns:Buyer" => array:2 [▶]
   "bns:OpenOrderItems" => array:1 [▶]
   ]
]

Example blade template :
@foreach ($OpenOrder as $order)
    {{ $order->bns:OrderId }}
@endforeach

Comment: provide your controller and full query. show me the `dd($OpenOrder);` data.
Comment: Changed the question text
Comment: please don't share your credentials, ex: public and privat key in public area.. :)
Answer: This query returns the collection of arrays values not an Object. use this {{ $order["bns:OrderId"] }} instead of this {{ $order->bns:OrderId }}.
Try this:
@foreach ($OpenOrder as $order)
    {{ $order["bns:OrderId"] }}
@endforeach

Comment: @RudiWerner Happy to help :)


DropDownListFor como usar?

Question: Estou com uma dúvida em como popular e depois pegar o item selecionado de um DropDownListFor, sendo que estou utilizando arquitetura DDD e Entity Framework.
No caso aqui minha classe ServiceProviderViewModel tem que ter relacionamento com outras classes. Gostaria de saber como fazer para popular esse Helper na View de Create.
Segue códigos:
public class ServiceProviderViewModel
{
    [Key]
    public int ServiceProviderId { get; set; }

    [Required(ErrorMessage = "Por favor, informe o nome do colaborador.")]
    [Display(Name = "Nome:")]
    public string Name { get; set; }

    [Display(Name = "Nome da Mãe:")]
    public string MotherName { get; set; }

    [Display(Name = "Nome do Pai:")]
    public string FatherName { get; set; }

    [Display(Name = "E-mail:")]
    [EmailAddress(ErrorMessage = "Por favor, informe um formato de e-mail válido.")]
    public string Email { get; set; }

    [Display(Name = "Nascimento:")]
    public DateTime Birth { get; set; }

    [ScaffoldColumn(false)]
    public DateTime DateRegister { get; set; }

    [ScaffoldColumn(false)]
    public DateTime DateModified { get; set; }

    [Required(ErrorMessage = "Por favor, informe o departamento para o colocaborador.")]
    [Display(Name = "Departamento:")]
    public int DepartamentId { get; set; }

    [Required(ErrorMessage = "Por favor, informe o departamento para o colocaborador.")]
    [Display(Name = "Cargo/Função:")]
    public int PositionId { get; set; }

    public virtual DepartamentViewModel Departaments { get; set; }
    public virtual PositionViewModel Positions { get; set; }

    public virtual IEnumerable<ServiceProviderAddressViewModel> ServiceProviderAddress { get; set; }
    public virtual IEnumerable<ServiceProviderPhoneViewModel> ServiceProviderPhone { get; set; }
    public virtual IEnumerable<ServiceProviderInfoViewModel> ServiceProviderInfo { get; set; }
    public virtual IEnumerable<InfoBankViewModel> InfoBank { get; set; }
}

No Controller:
 public class ServiceProviderController : Controller
{
    private readonly IServiceProviderAppService _serviceProviderApp;

    public ServiceProviderController(IServiceProviderAppService serviceProviderApp)
    {
        _serviceProviderApp = serviceProviderApp;
    }

    // GET: ServiceProvider
    public ActionResult Index()
    {
        var serviceProviderViewModel = Mapper.Map<IEnumerable<ServiceProvider>, IEnumerable<ServiceProviderViewModel>>(_serviceProviderApp.GetAll());
        return View(serviceProviderViewModel);
    }

    // GET: ServiceProvider/Create
    public ActionResult Create()
    {
        return View();
    }

    // POST: ServiceProvider/Create
    [HttpPost]
    public ActionResult Create(ServiceProviderViewModel serviceProvider)
    {
        if (ModelState.IsValid)
        {
            var serviceProviderDomain = Mapper.Map<ServiceProviderViewModel, ServiceProvider>(serviceProvider);
            _serviceProviderApp.Add(serviceProviderDomain);
            _serviceProviderApp.Save();

            return RedirectToAction("Index");
        }

        return View(serviceProvider);
    }

...

Para cada classe que ServiceProvider se relaciona tenho os models específicos para realização do CRUD. Só não sei como devo fazer para funcionar essa mistura de models entre as views e controllers.
Answer: Código levando em consideração que o PositionId deveria ser uma combo:
Na Action Get:
Obs: Você deve passar a ViewBag.Position
public ActionResult Create()
{
    ViewBag.Position = new SelectList(_serviceProviderApp.SeuMetodoDeObterPositions(), "PositionId", "SeuCampoDescricao");

    return View();
}

Na view:
Obs: Esse Código coloca a primeira opção em branco e depois os dados vindo da ViewBag.
@Html.DropDownList("PositionId", (IEnumerable<SelectListItem>)ViewBag.Position, String.Empty, new { @class = "form-control" })

Comment: Mas, como a classe Position é um outro model, devo fazer uma chamada do mesmo dentro do controller de ServiceProvider? A idéia não é exatamente criar controllers distintos para cada model?
Comment: @UitanMaciel, eu falei Position somente como ilustração. No lugar de Position coloque a model referente a sua combo.
Comment: Está funcionando bem. Está populando o DropDownListFor. No entanto está dando erro: An exception of type 'System.InvalidOperationException' occurred in System.Web.Mvc.dll but was not handled in user code

Additional information: The ViewData item that has the key 'DepartamentId' is of type 'System.Int32' but must be of type 'IEnumerable'. Está com problema em converter o tipo.
Comment: Talvez eu precise ver seu código, mas entenda que o método ObterPositions (ou seja lá qual for o nome do seu método precisa retornar algo do tipo IEnumerable, com a classe Position tendo uma propriedade PositionId como chave e uma propriedade Descricao que devem ser iguais aos dois últimos  parâmetros passados para o New SelectList.
Comment: olha o código abaixo:
Comment: @UitanMaciel, olhei o código que você postou e me parece ok. Complicado saber exatamente qual é o problema agora. Provavelmente você deixou passar algum detalhe, tente debugar, veja em que linha ocorre o problema, veja a innerexception. Cheque a implementação da classe Departament e do repositório. Parece que o problema está ao fazer o Get e não o Post, já que no post você não usa ViewBag.
Answer: @uitan, essa exception está mascarando o real problema que deve ser apenas validação do seu form.
Você deve carregar as ViewBags do ação post como fez na ação Get.
seu post deve ficar assim:
// POST: ServiceProvider/Create
[HttpPost]
public ActionResult Create(ServiceProviderViewModel serviceProvider)
{
    if (ModelState.IsValid)
    {
        var serviceProviderDomain = Mapper.Map<ServiceProviderViewModel, ServiceProvider>(serviceProvider);
        _serviceProviderApp.Add(serviceProviderDomain);
        _serviceProviderApp.Save();

        return RedirectToAction("Index");
    }

    //FALTAM ESSAS LINHAS:
    ViewBag.Position = new SelectList(_positionApp.GetAll(), "PositionId", "Description");
    ViewBag.Departament = new SelectList(_departamentApp.GetAll(), "DepartamentId", "Description");

    return View(serviceProvider);
}

Marque como resolvido se funcionar. :)
Comment: vlw. Funcionou!
Answer: No Domain:
 public class ServiceProvider
{
    #region Attributs
    public int ServiceProviderId { get; set; }
    public string Name { get; set; }
    public string MotherName { get; set; }
    public string FatherName { get; set; }
    public string Email { get; set; }
    public DateTime Birth{ get; set; }
    public DateTime DateRegister { get; set; }
    public DateTime DateModified { get; set; }
    #endregion
    #region Foreingkeys
    public int DepartamentId { get; set; }
    public int PositionId { get; set; }
    #endregion
    #region Properties Navigations
    public virtual Departament Departaments { get; set; }
    public virtual Position Positions { get; set; }
    #endregion
}

public class Position
{
    #region Attributs
    public int PositionId { get; set; }
    public string Description { get; set; }
    public DateTime DateRegister { get; set; }
    public DateTime DateModified { get; set; }
    #endregion
    #region Relationships Other Class
    public virtual IEnumerable<ServiceProvider> ServiceProviders { get; set; }
    #endregion
}

 public class Departament
{
    #region Attributs
    public int DepartamentId { get; set; }
    public string Description { get; set; }
    public DateTime DateRegister { get; set; }
    public DateTime DateModified { get; set; }
    #endregion
    #region Relationships Other Class
    public virtual IEnumerable<ServiceProvider> ServiceProviders { get; set; }
    #endregion
}

Na ViewModel (Camada de Apresentação)
public class ServiceProviderController : Controller
{
    private readonly IServiceProviderAppService _serviceProviderApp;
    private readonly IPositionAppService _positionApp;
    private readonly IDepartamentAppService _departamentApp;

    public ServiceProviderController(IServiceProviderAppService serviceProviderApp, IPositionAppService positionApp, IDepartamentAppService departamentApp)
    {
        _serviceProviderApp = serviceProviderApp;
        _positionApp = positionApp;
        _departamentApp = departamentApp;
    }

    // GET: ServiceProvider
    public ActionResult Index()
    {
        var serviceProviderViewModel = Mapper.Map<IEnumerable<ServiceProvider>, IEnumerable<ServiceProviderViewModel>>(_serviceProviderApp.GetAll());
        return View(serviceProviderViewModel);
    }

    // GET: ServiceProvider/Details/5
    public ActionResult Details(int id)
    {
        return View();
    }

    // GET: ServiceProvider/Create
    public ActionResult Create()
    {
        ViewBag.Position = new SelectList(_positionApp.GetAll(), "PositionId", "Description");
        ViewBag.Departament = new SelectList(_departamentApp.GetAll(), "DepartamentId", "Description");
        return View();
    }

    // POST: ServiceProvider/Create
    [HttpPost]
    public ActionResult Create(ServiceProviderViewModel serviceProvider)
    {
        if (ModelState.IsValid)
        {
            var serviceProviderDomain = Mapper.Map<ServiceProviderViewModel, ServiceProvider>(serviceProvider);
            _serviceProviderApp.Add(serviceProviderDomain);
            _serviceProviderApp.Save();

            return RedirectToAction("Index");
        }

        return View(serviceProvider);
    }
}

Na View:

            @Html.LabelFor(model => model.DepartamentId, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.DropDownListFor(model => model.DepartamentId, (IEnumerable<SelectListItem>)ViewBag.Departament, string.Empty)
                @Html.ValidationMessageFor(model => model.DepartamentId, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.PositionId, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.DropDownListFor(model => model.PositionId, (IEnumerable<SelectListItem>)ViewBag.Position, string.Empty)
                @Html.ValidationMessageFor(model => model.PositionId, "", new { @class = "text-danger" })

Os métodos GetAll() e os de CRUD são chamados por repositórios genéricos. O problema está exatamente quando tento submeter o formulário. Apresenta o erro que comentei anteriormente.
Comment: acabei de ajudar um amigo que teve esse problema, no caso dele a ViewModel estava inválida.
Coloque um breakpoint na linha:
`if (ModelState.IsValid)`
e veja que campo está com erro.
Comment: @ViniciusGrund extamente, o (ModelState.IsValid) não está válido. E o erro que apresenta é An exception of type 'System.InvalidOperationException' occurred in System.Web.Mvc.dll but was not handled in user code

Additional information: The ViewData item that has the key 'DepartamentId' is of type 'System.Int32' but must be of type 'IEnumerable'.
Comment: @ViniciusGrund olha abaixo a img do Model

DropDownListFor como usar?


Confusion about React componentDidMount

Question: componentDidMount() is invoked immediately after a component is mounted (inserted into the tree).
if i append a blue div in componentDidMount, i would see original react component at first, then i see the blue div. but i see the blue div directly even not a blink.
Why? Is the browser is too fast and my eyes too insensitive?

  .blue {
     position:absolute;
     top:0
     height:100px;
     width:100vw;
     background:blue
    }
***

classclass App extends Component {
  constructor(){
    super();
  }
  componentDidMount() {
    const div=document.createElement('div');
    div.className='blue';
    document.body.appendChild(div)
  }
  render(){
   return (

hello world

   )
  }
}

Comment: Any specific reason you are directly modifying DOM inside of React?.
Comment: Check it using a countdowntimer!!!
Answer: It is working as desired. It first renders red then it adds a blue div. It's happening because there are no function calls that need to wait. Also, the rendering that you are doing is so light that it executes effortlessly with minimal time.
You can verify your execution behaviour using two ways

Inspect the dom tree
Use debugger and stop execution at render().

For example
    render() { debugger; return (

);}. It'll halt your execution, and then you can proceed step by step using browser debugging capabilities.

If you're using Chrome, by navigating to the Sources tab and marking a breakpoint on your desired file.
Answer: As an alternative answer to @Aseem Upadhyay's good debugging one here is one more with avoiding manipulating the DOM directly and using React's state.

    class App extends React.Component {
      state = {
        style: {
          position: "absolute",
          top: "0",
          height: "100px",
          width: "100vw",
          background: "red",
        }
      }

      componentDidMount() {
        setTimeout(() => this.setState( prevState => ({
          style: {
            ...prevState.style, background: "blue"
          }
        })), 2000 );

      }
      render(){
        return (

hello world

        )
      }
    }

    ReactDOM.render(
      <App />,
      document.getElementById("app")
    );

Also you can use React Developer Tools and inspect the DOM and state changes easily if you write your app with the React way.
Answer: This has nothing to do with your eyes. Any logic you place inside of componentDidMount() will execute the instant your application boots up.
That means that if I define a function inside of my class, underneath the constructor() but above the render() method. If I define a method called componentDidMount(), this function will be automatically called one time, when the component first gets rendered onto the screen.
After the componentDidMount() method gets called our component will sit around and wait for an update which will come in the form of calling a setState() method. Anytime we call setState() and update our state, the component will re render or update itself. When that happens, another component called componentDidUpdate() will be called automatically.
To better understand this, inside of your component try this:
.blue {
     position:absolute;
     top:0
     height:100px;
     width:100vw;
     background:blue
    }
***

class App extends Component {
  constructor(props){
    super(props);
  }
  componentDidMount() {
    console.log('My component was rendered to the screen');
  }
  render(){
   return (

hello world

   )
  }
}

You will immediately see the string logged to your browsers console anytime your component shows up on the screen.
Also, you have declared class keyword twice, you must be getting an error about that, remove one of them and last but certainly not least, notice how I have passed props to both constructor() method and super()?
When we define the constructor() method, it will automatically be called with the props object. Once we use the constructor() we have to also add super(props) as well. You must be getting on error on this as well, fix it.

Confusion about React componentDidMount


node-webkit won't run project file

Question: I started experimenting with nwjs ( node-webkit ) .
But i seem to be doing something wrong i have 2 file in a folder :
index.html
<!DOCTYPE html>

<title>Hello Node Webkit</title>

Hello Node Webkit

package.json
{
  "name": "myapp.helloworldapp",
  "version": "1.0.0",
  "description": "A test app",
  "main": "index.html",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "MIT"
}

i zip up both files at ones ( i don't zip the folder ) and i rename the extention from .zip to .nw but nothing happens when i try to open it with the nwjs app .
i'm working from a mac if that could have something to do with it ?
Comment: For me it works with node 0.9.1 but not works with 0.11
Comment: It work with older version of node-webkit, but doesn't work with new node-webkit including nwjs 0.12
Comment: Confirmed 0.9.1 does show my .nw file .
Answer: I would follow the steps outlined in their docs.
From the command line:

Go to your project directory a la cd ~/Projects/my_app
Run zip -r ../${PWD##*/}.nw *
Your fully-prepared .nw file shall be located
right outside of your project directory
Cake!

node-webkit won't run project file


meaning of Solr query

Question: I am a newbie to solr and i am trying to understand the different way of querying.
I saw a code example as below:
'some search text'::type:value1:type:value2

Can anybody help me understand what the above string does?
I know if it is only type:value1 searches the field type with the value value1
Another question as how can I search a value in multiple fields? basically I want to do OR on fields.
Eg:type:value1 OR name:value1
Any link to the beginners tutorial or help is greatly appreciated.
Answer: Which version of solr are you using, please? The query support has changed between e.g. solr 4 and solr 5.
For your second query, if you are e.g. using solr 5 and you are browsing the appropriate core from the browse URL then you should be able to type in type:blue OR name:blue and you'll get the expected results. However, more likely you'll want to watch your case-sensitivity here, and you want e.g. type:blue OR name:Blue This will get rendered as /solr/core/browse?q=type%3Ablue+OR+name%3Blueetc.

meaning of Solr query


existing file gives 404 due to a RewriteCond rule in .htaccess

Question: To redirect a specific domain name to a folder in my public dir, www/, I edited .htaccess to the following:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^(.+)?domain.com$
RewriteRule ^(/)?$ domain.com/$1 [L]

Pointing my browser to http://domain.com gives me the following error:
Not Found

The requested URL /[...]/htdocs/www/domain.com/ was not found on this server.

However in my shell I can see this:
$ ls -al /[...]/htdocs/www/domain.com/
total 4
drwxr-xr-x+ 2 user group 3 2012-11-30 12:04 .
drwxr-xr-x+ 8 user group 9 2012-11-30 12:03 ..
-rw-r--r--+ 1 user group 4 2012-11-30 12:04 index.php

Editing .htaccess to point directly to index.php gives the result. An empty .htaccess file points correctly to the root directory.
What am I missing?
Answer: Via this link I found the proper rules:
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} !^/subdirectory/
RewriteCond %{HTTP_HOST} ^(www\.)?name\.
RewriteRule ^(.*)$ subdirectory/$1 [L]

Please see the link itself for a full explanation on proper usage.


With Maven2, how would I specify a custom directory to which a dependency should be copied?

Question: Basically, I have a multi-module project consisting of 5 different modules. One of the modules is kind of the parent module to the other 4, meaning the other 4 need to be built before the 5th, so you could say that each of the 4 modules is a dependency of the 5th. Thus, I've made dependency entries for each of the modules in the 5th module's pom.xml.
However, when I build the project, I don't want those 4 dependencies copied to the "lib" directory of the 5th module. I'd like to specify the directory into which each of them should be placed explicitly.
Is there any way to do this with Maven2?
Thanks for your help,
B.J.
Comment: How do you copy the dependencies into the lib folder? Do you have a multi module build (this would make it simple to define the reactor order)?
Answer: I'm not sure I understood everything (from where does this lib directory come from, when do you want the copy to happen exactly?) but the Maven Dependency Plugin might help, its dependency:copy goal takes an outputDirectory per dependency. Below the sample taken from the Usage page:
<project>
  [...]
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-dependency-plugin</artifactId>
        <executions>
          <execution>
            <id>copy</id>
            <phase>package</phase>
            <goals>
              <goal>copy</goal>
            </goals>
            <configuration>
              <artifactItems>
                <artifactItem>
                  <groupId>[ groupId ]</groupId>
                  <artifactId>[ artifactId ]</artifactId>
                  <version>[ version ]</version>
                  <type>[ packaging ]</type>
                  <classifier> [classifier - optional] </classifier>
                  <overWrite>[ true or false ]</overWrite>
                  <outputDirectory>[ output directory ]</outputDirectory>
                  <destFileName>[ filename ]</destFileName>
                </artifactItem>
              </artifactItems>

            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
  [...]
</project>

Change the lifecycle phase binding according to your needs.
But as I said, this answer is more an hint, maybe using a custom assembly would be more appropriate. If it doesn't help, please provide more details.
Comment: This works, but you may be right that a custom assembly would be the better solution, at least as far as good practices go. Thanks again for the help.


Probability that a 40% shooter is better than a 30% shooter given 20 shots?

Question: I'm working through the Regression and Other Stories (ROS) textbook and it's not clear to me how Gelman etal. would like a reader to answer question 4.3 (which I summarize below):

Two basketball shooters. Shooter A has an accuracy of 30% while shooter B has an accuracy of 40%. They each take 20 shots. What is the probability that shooter B makes more shots?

Now, I'm aware of the following question and it all makes sense. What confuses me however, is that at no point in the textbook (unless I missed it) does Gelman etal. demonstrate that approach. Therefore, I wonder if there is another way to answer the question using a "Gelman" method?
So far I have the following R code:
N = 20
p_a = 0.3  # shooter A has a 30% accuracy
se_a = sqrt(p_a * (1 - p_a) / N)
p_b = 0.4  # shooter B has a 40% accuracy
se_b = sqrt(p_b * (1 - p_b) / N)

# The probability that shooter B makes more shots than B with mean and s.e. of:
p_diff = p_b - p_a
se_diff = sqrt(se_a**2 + se_b**2)

My intuition tells me that the difference in their ability is described by a (Gaussian?) distribution with mean p_diff (0.1) and standard error of se_diff (0.15). Given that p_diff = p_b - p_a, positive values of p_diff account for instances when B "beats" A while negative values are the opposite. See below:

Therefore, the probability of B beating A is the area under the graph to the right of the red line. Which can be calculated in r with:
# p_diff is 0.1
# se_diff is 0.15
p_b_beats_a = 1 - pnorm(0, p_diff, se_diff)

Which gives the incorrect value of ~0.75 (see link above for correct value).
What step/intuition have I missed? Given that at no point in ROS has Gelman etal. mentioned continuity correction (as the above link does), I'm assuming there is some other "Gelman" method/intuition that I've missed ...
Alternatively, how does one go from the method as described in the link to the "Gelman" approach?
I'd appreciate both the maths/code but also an intuitive explanation.
Comment: This isn't a question about statistics or inference: it's about computing Binomial probabilities.  The thread you reference explains this and shows how to approximate these probabilities with Normal distributions.
Answer: Since the referenced thread only includes a direct approach in a comment, here goes.
You can directly evaluate the probability of the discrete events when shooter A makes more shots than shooter B and sum them together rather than approximating a normal distribution. If $A \sim Bin(20, 0.3)$ and $B \sim Bin(20, 0.4)$ then you are looking for $P(A < B)$, which is the same as $\Sigma_{n=0}^{20} P(A < n, B = n)$
We can probably assume the shots are independent, so
$$
P(A<B) = \Sigma_{n=0}^{20} P(A \le n-1)P(B = n)$:
$$
p <- 0
for (n in 0:20) {
  p <- p + dbinom(n, 20, 0.4) * pbinom(n-1, 20, 0.3)
}

If you want to approximate the Binomial distribution by a Normal one and $A \sim Bin(n,p)$, you need $np$ to be large: it might be large enough here, but it, but given that you have to do the whole continuity correction thing, it might be more hassle than its worth!
A quick search shows evaluating the Binomial distribution comes up in ROS in Ex. 3.5, but there doesn't appear to be a solid section on probability theory.
I hope this demonstrates another approach. I made the mistake of getting A and B the wrong way around initially, hopefully I haven't missed any less than/equals signs!
Comment: +1.  It's hard to see how the "continuity correction" would be a hassle: it's just a matter of characterizing the event $A\lt B$ as $A-B\le-1/2.$  The `R` calculation is `pnorm(-1/2, 20*(0.3 - 0.4), sqrt(20*0.3*(1 - 0.3) + 20*0.4*(1 - 0.4)))` and it agrees with your calculation almost to the third decimal place.  You don't need $np$ to be large here, because (a) you are subtracting one skewed variable from another, yielding an almost symmetrical difference; and (b) you are not computing a probability way out in one tail.  Even with $20$ replaced by $2$ the Normal approximation is excellent(!).
Comment: @user1182556 I think I might have spotted the problem: you have put down `se_a = sqrt(p_a * (1 - p_a) / N)`, but I think you might mean `sqrt(p_a * (1- p_a) * N)` (check at the bottom of page 43 of ROS). The missing piece of understanding here is that standard errors and standard deviations are very different things! Here we are interested in approximating the population variance, so we want standard deviation, whereas the standard error comes in when you are looking at the **sampling distribution** of the mean
Comment: @Geoffrey Liddell: Thank you for that explanation. I think I'm almost there with regards to the "intuition" however, can how you went from $ \Sigma_{n=0}^{20} P(A < n, B = n) $ to $ P(A<B) = \Sigma_{n=0}^{20} P(A \le n-1)P(B = n) $?
Comment: @whuber: Your comment is, I think, what I had in mind. However, in "my maths" my threshold is 0 and mu/se are 0.1/0.15 whereas your threshold is -0.5 and mu/se are -2/3. Is there a way to get the correct answer using "my maths"? (Specifically, by NOT multiplying in the N).

P.S. I agree your threshold of -0.5 is correct. How do I convert that to "my maths"? i.e. `pnorm(???, (0.3-0.4), sqrt(0.3*(1-0.3) + 0.4*(1-0.4))`
Comment: You might be overthinking this: $-1/2$ for the continuity correction will work well.  Concerning your first comment: the inequality $A\lt n$ is equivalent to the inequality $A\le n-1$ when $A$ is integral.  Then use the fact that $A$ and $B$ are independent.
Answer: All credit must go to @Geoffrey Liddell and @whuber for their help. I post the below for completeness.
As pointed out by @Geoffrey Liddell, I was confusing standard deviations and standard errors. The solution I was looking for (as guided by @whuber) looks something like:
N = 20
p_a = 0.3  # Shooter A has a 30% shooting accuracy
mu_a = N * p_a
std_a = sqrt(N * p_a * (1 - p_a))
p_b = 0.4  # Shooter B has a 40% shooting accuracy
mu_b = N * p_b
std_b = sqrt(N * p_b * (1 - p_b))

# determine coefficients of the Gaussian that describes the difference between
# B and A:
mu_diff = mu_b - mu_a
std_diff = sqrt(std_a**2 + std_b**2)

x = seq(-20, 20, 0.001)
y = dnorm(x, mu_diff, std_diff)
threshold = 0.5  # Positive threshold because of "B - A"
{
  plot(x, y, 'l', )
  abline(v=threshold, col='red')
  text(-10, 0.06, 'A wins')
  text(10, 0.06, 'B wins')
}

p_b_beats_a = 1 - pnorm(threshold, mu_diff, std_diff)

Where p_b_beats_a is ~0.69 which is the correct answer.
Thanks again to @Geoffrey Liddell and @whuber.
ADDENDUM: In conjunction with confusing standard deviations vs standard errors, I think another issue that was confusing me was working in "proportion space" vs "actual value space".
For example, originally I had p_diff = p_b - p_a. That meant I had to convert my threshold of 0.5 in "actual value space" to a value in "proportion space" (which I still didn't know how to do - assuming it's even possible?). However, by working with actual values i.e mu_diff = mu_b - mu_a, the threshold of 0.5 is now intuitive and the maths follows.


Customising a dynamic layout at runtime based on control visibility

Question: I have a multi-purpose CDialog that supports resizing. It can display content in 3 variations.
Variation 1:

Variation 2:

Variation 3:

The dialogue controls are using the dynamic layout settings from the resource editor.
Variation 1 is fine and need no changes.
Variation 2 does not display the combo and date button. As a result I would like the "Text will ..." label to be down at the bottom and the "edit" box to be taller.
Variation 3 has a similar issue where the date button should move to the bottom and the edit box be taller.
Can this be achieved by changing the dynamic layout in code?
Update
I tried this in OnInitDialog:
if (!m_bShowWeekCombo)
{
    CRect rctCombo;
    m_cbWeek.GetWindowRect(rctCombo);
    ScreenToClient(rctCombo);

    CRect rctNote;
    m_staticInfo.GetWindowRect(rctNote);
    ScreenToClient(rctNote);

    m_staticInfo.MoveWindow(rctCombo.left, rctCombo.top, rctNote.Width(), rctNote.Height());
}

At first I thought it was working:

The note is now at the bottom. But as soon as I resize the window:

The note has reverted to the original position.
I know I have this answer to a similar issue but do I really have to re-build the whole layout?
Update 2
if (!m_bShowWeekCombo)
{
    CRect rctEdit;
    m_editText.GetWindowRect(rctEdit);
    ScreenToClient(rctEdit);

    CRect rctCombo;
    m_cbWeek.GetWindowRect(rctCombo);
    ScreenToClient(rctCombo);

    CRect rctNote;
    m_staticInfo.GetWindowRect(rctNote);
    ScreenToClient(rctNote);

    //m_staticInfo.MoveWindow(rctCombo.left, rctCombo.top, rctNote.Width(), rctNote.Height());
    m_staticInfo.SetWindowPos(NULL, rctCombo.left, rctCombo.top, 0, 0,
        SWP_NOSIZE | SWP_NOZORDER);
    m_editText.SetWindowPos(NULL, 0, 0, rctEdit.Width(), rctEdit.Height() + (rctCombo.top - rctNote.top),
        SWP_NOMOVE | SWP_NOZORDER);

    if (m_pDynamicLayout)
    {
        if (!m_pDynamicLayout->HasItem(m_staticInfo.m_hWnd))
        {
            m_pDynamicLayout->AddItem(m_staticInfo.m_hWnd,
                CMFCDynamicLayout::MoveVertical(100), CMFCDynamicLayout::SizeHorizontal(100));
        }
        else
        {
            TRACE(L"item already has dynamic move/size\n");
        }
        if (!m_pDynamicLayout->HasItem(m_editText.m_hWnd))
        {
            m_pDynamicLayout->AddItem(m_editText.m_hWnd,
                CMFCDynamicLayout::MoveNone(), CMFCDynamicLayout::SizeHorizontalAndVertical(100, 100));
        }
        else
        {
            TRACE(L"item already has dynamic move/size\n");
        }

    }
}

When I try the above the control width is the original width, even though the dialog had restored to wider dialog width.
Answer: CMFCDynamicLayout reads the dialog resource, it stores the coordinates for the child controls as well as their dynamic resize/move properties.
This is all done in CDialog::OnInitDialog. If you move the child control, example, m_staticInfo then CMFCDynamicLayout doesn't know you moved/resized the control. So upon the next dialog resize request, CMFCDynamicLayout uses the old values.
You can add dynamic resize/move for all controls expcept m_staticInfo and other controls which you intend to move manually. Then add m_staticInfo separately:
BOOL CMyDialog::OnInitDialog()
{
    CDialog::OnInitDialog();

    CRect rctCombo;
    m_cbWeek.GetWindowRect(rctCombo);
    ScreenToClient(rctCombo);
    m_staticInfo.SetWindowPos(NULL, rctCombo.left, rctCombo.top, 0, 0,
        SWP_NOSIZE | SWP_NOZORDER);

    if(m_pDynamicLayout)
    {
        if(!m_pDynamicLayout->HasItem(m_staticInfo.m_hWnd))
        {
            m_pDynamicLayout->AddItem(m_staticInfo.m_hWnd,
                CMFCDynamicLayout::MoveVertical(100), CMFCDynamicLayout::SizeNone());
        }
        else
        {
            TRACE(L"item already has dynamic move/size\n");
            AfxDebugBreak(0);
        }
    }

    return 1;
}

Internally, MFC calls LoadDynamicLayoutResource(m_lpszTemplateName) to initialize dynamic size/move. But documentation says not to use this method directly.
Clarification
If you are using a dialog that supports resizing then you must remember to calculate the new width and height when you move the control to the new position. You would then use one of the appropriate Size calls. For example:
// The EDIT control height now needs increasing
iNewEditHeight = rctButton.top - iTextMarginY - rctEdit.top;
m_editText.SetWindowPos(nullptr, 0, 0, iNewWidth, iNewEditHeight, SWP_NOMOVE | SWP_NOZORDER);

It is up to you to workout how you want your control initially re-sized.
Then, in OnInitDialog I called a new method:
void CEditTextDlg::SetupDynamicLayout()
{
    if (m_pDynamicLayout != nullptr)
    {
        m_pDynamicLayout->AddItem(IDC_BUTTON_INSERT_DATE,
            CMFCDynamicLayout::MoveHorizontalAndVertical(100, 100), CMFCDynamicLayout::SizeNone());
        m_pDynamicLayout->AddItem(IDC_STATIC_INFO,
            CMFCDynamicLayout::MoveVertical(100), CMFCDynamicLayout::SizeHorizontal(100));
        m_pDynamicLayout->AddItem(IDC_EDIT_TEXT,
            CMFCDynamicLayout::MoveNone(), CMFCDynamicLayout::SizeHorizontalAndVertical(100, 100));
    }
}

If you don't set the width correctly when using SetWindowPos and only use SizeNone() it will not resize correctly.
Comment: I made tweak to your answer.
Comment: Thanks for this. What I had to do was re-compute the default size of the controls (since the dialog was resized) before I added them to the layout. Sorted.
Comment: I am not sure what solutions you came up with. I think you decided to move/resize all child controls manually!
Comment: No. Only the controls that I needed to resize. I just had to actually "resize" them properly first. EG: I had to change the width correctly when "moving" it to the right place. All the others are left as default via IDE resource properties.
Comment: Notice in your sample code you have SizeNone. That is no good. My controls are stretching either in width or height. But i had to change the base dimensions of the control first. So I had to re-compute the correct sizes.


Volume of region in $\mathbb{R}^n$ defined by $\binom{n}2$ linear constraints

Question: What is the volume of the region in $\mathbb{R}^n$ defined by $0 \le x_i \le 1$ for all $1 \le i \le n$ and $x_i +x_j \ge 1$ for all pairs $1\le i<j \le n$?
For example for $n=2$, this is just the upper triangle of the unit square which is $1/2$.
Alternatively, if $n$ iid uniform random variables are drawn in $[0,1]$, what is the probability that every pair of them add to at least $1$?
Comment: For what it matters, the probabilistic interpretation leads directly to $\mathbb{P}[U_{(1)} + U_{(2)} \geq 1]$, where $U_{(i)}$ is the $i$th order statistic from a sample of $n$ standard uniform random variables.  We know [a lot about these, including their joint distribution,](https://en.wikipedia.org/w/index.php?title=Order_statistic&oldid=1194980969#Probability_distributions_of_order_statistics) so we can solve it using that route (as mentioned in a previous comment, it does give $2^{1-n}$)
Comment: Take $n=2$. This means we want the portion of the unit square that satisfies $x+y \ge 1$ which has probability $1/2$. For $n=3$, we want the volume of the unit cube that satisfies $x+y \ge 1, x+z \ge 1, z+y \ge 1$. This is $1/4$.
Comment: I probably didn't fully understand your challenge. But it seems to me that for $n=3$ the volume of the specified region is equal to $1-1/6$. In the general case the formula $1-1/n!$ is obtained. Or is it?
Comment: I agree, I see where I was going astray. It's a very interesting question.
Comment: The answer is $\color{red}{2^{1-n}}$, but I didn't find a proof yet.
Answer: I realized Brian Moehring's observation directly gives the answer (without the need for any fancy formulas). If we let $U_{(1)}$ and $U_{(2)}$ be the smallest and second smallest values out of the $n$ uniformly random numbers, then we just want $P(U_{(1)} + U_{(2)} \ge 1)$. But this is a straightforward calculation.
We know $n(1-t)^{n-1}$ is the density function of $U_{(1)}$. Furthermore, given $U_{(1)}$, the rest of the variables are just iid uniform in $[U_{(1)}, 1]$. Thus, given $U_{(1)}$, the probability that $U_{(2)}$ is at least $1-U_{(1)}$ is just the probability that all of the $n-1$ draws land in the interval $[1-U_{(1)}, 1]$, which has relative length $U_{(1)}/(1-U_{(1)})$. However, we have to be slightly careful because once $U_{(1)} \ge 1/2$, the event always holds.
$$Pr(U_{(1)} + U_{(2)} \ge 1) = n\int_0^{1/2} (1-t)^{n-1} \cdot \left( \frac{t}{1-t}\right)^{n-1} \ dt + P(U_{(1)} \ge 1/2).$$
Both of these terms are $2^{-n}$ so the final answer is $2^{-n+1}$.


Mapping points and polygons

Question: I am a R beginner handling for the first time both with R and spatial data. So I hope I make myself clear.
I have a shapefile of an italian region, divided into several census divisions.
On the other hand I have got a csv file with a cases list and addresses for each case.
I would like to map points and the shapefile and to get the count of how many points are in each census division.
Here what I have done since now:
#get cases file
cases <- read.csv("cases.csv", sep =';', header = TRUE)
names(cases)
[1] "name"    "address"

#geocode addresses from Google Maps
library(GISTools)
library(rgeos)
library(ggmap)
geolocalize <- geocode(as.character(cases$address))

# bind latitude and longitude to the previous cases data frame
cases <- data.frame(cases, geolocalize)
names(cases)
[1] "name"    "address" "lon"     "lat"

#make cases a SpatialPointDataFrame
#since addresses were retrieved using GoogleMaps, I set proj4string as follows
cases.points <- SpatialPointsDataFrame(cases[,3:4], cases, proj4string = CRS("+init=EPSG:3857"))

#get the shapefile
region <- readOGR("R02_11_WGS84.shp")

Now, I am able to plot cases.points and shapefile separately, but not to add them in the same plot. Along with that, as I said, I would like to count how many points lie in each polygon (i.e. census division of "region").
I must admit I'm not very keen on geography. I had the doubt that different coordinates and/or projection reference systems could be the problem, thus I've checked.
head(coordinates(region))
[,1]    [,2]
0 364509.0 5065900
1 363916.3 5056629
2 372585.0 5068078
3 360692.3 5048321
4 356029.7 5062399
5 360012.1 5065663

coordinates(cases)
lon      lat
[1,] 7.323667 45.73664

proj4string(region)
[1] "+proj=utm +zone=32 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0"

proj4string(cases.points)
[1] "+init=EPSG:3857 +proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs"

Is it likely that the shapefile coordinates are in degrees while the cases coordinates are in decimal? If so, how to convert them?
Thanks,
Saro
Comment: What are the names of the columns in your shapefile ? Or do they have no name ?
Comment: Can't try it right now, so I won't answer, but have a look at `sp::spTransform`.
Answer: You have two different projections - your "region" shapefile is projected in UTM zone 32 and you told R to use Web Mercator for "cases". However, if you just downloaded the cases data as lat/long from Google, then you don't want to tell R their projection is Web Mercator, because it isn't - it's unprojected WGS 84, so you'd want EPSG 4326. Web Mercator is what Google uses to display maps, but if you download lat/long, that's just unprojected coordinates. To get your lat/long data read in correctly, use:
library(sp)
cases.points <- SpatialPointsDataFrame(cases[,3:4], cases,
                                   proj4string = CRS("+init=EPSG:4326"))

Then for the projection, you want spTransform - try:
cases.points.utm32 <- spTransform(cases.points, CRS(proj4string(region)))

Using inappropriate or non-matching projections can create a lot of problems, and they're not always noticeable right away.
EDIT:
For selecting points within a polygon, you want the over() function, also from the sp package (this is kind of a separate question). Do read up on the basic functions of the sp package and how the sp classes work - below is basically copied from the help section for over().
region$pointCount <- sapply(over(region, geometry(cases.points),
                             returnList = TRUE), length)

Comment: Great! If it answered your questions, please consider "accepting" the answer.

Mapping points and polygons


Inserting Array from Scandir() into PHP Calendar Script

Question: Background: Looking to put local marine radio cruisers net online. Net being received via SDR piped to sox for encoding as mp3 file. File uploaded to server in dedicated directory (/data), naming convention (YY)(MM)(DD).mp3 At this time the project is in test mode, and files are not always recorded or uploaded daily
Goal: Server side (PHP) calendar script which will parse the /data directory for an array and recolor the calendar cells background for dates matching the files naming convention. Clicking on a highlighted cell will open the associated file.
Status: Have very simple (but adequate?) calendar script with no exterior libraries or css (code follows). Php experience limited and rusty. Unsure how and where to integrate scandir() function and other required bits to achieve goal. Assistance appreciated.

  <title>Boot Key Calendar Test</title>

<?php
    $monthNames = Array(
        "January",
        "February",
        "March",
        "April",
        "May",
        "June",
        "July",
        "August",
        "September",
        "October",
        "November",
        "December"
    );

    if (!isset($_REQUEST["month"]))
        $_REQUEST["month"] = date("n");
    if (!isset($_REQUEST["year"]))
        $_REQUEST["year"] = date("Y");

    $cMonth = $_REQUEST["month"];
    $cYear  = $_REQUEST["year"];

    $prev_year  = $cYear;
    $next_year  = $cYear;
    $prev_month = $cMonth - 1;
    $next_month = $cMonth + 1;

    if ($prev_month == 0)
      {
        $prev_month = 12;
        $prev_year  = $cYear - 1;
      }
    if ($next_month == 13)
      {
        $next_month = 1;
        $next_year  = $cYear + 1;
      }
?>

  <a href="<?php
    echo $_SERVER["PHP_SELF"] . "?month=" . $prev_month . "&year=" .        $prev_year;
?>" style="color:#FFFFFF">Previous
<a href="<?php
        echo $_SERVER["PHP_SELF"] . "?month=" . $next_month . "&year=" .     $next_year;
?>" style="color:#FFFFFF">Next

<?php
    echo $monthNames[$cMonth - 1] . ' ' . $cYear;
?>

  S
 M
T
W
T
F
F

<?php
    $timestamp = mktime(0, 0, 0, $cMonth, 1, $cYear);
    $maxday    = date("t", $timestamp);
    $thismonth = getdate($timestamp);
    $startday  = $thismonth['wday'];
    for ($i = 0; $i < ($maxday + $startday); $i++)
      {
        if (($i % 7) == 0)
            echo "
";
        if ($i < $startday)
            echo "	";
        else
            echo "" .     ($i - $startday + 1) . "	";
        if (($i % 7) == 6)
            echo "
";
      }
?>

Working example at http://bootkeycruisers.net/calendar.php
Answer: This works:
    <?php
    $monthNames = Array(
        "January",
        "February",
        "March",
        "April",
        "May",
        "June",
        "July",
        "August",
        "September",
        "October",
        "November",
        "December"
    );
    if (!isset($_REQUEST["month"])) $_REQUEST["month"] = date("n");
    if (!isset($_REQUEST["year"])) $_REQUEST["year"] = date("Y");
    $cMonth = $_REQUEST["month"];
    $cYear = $_REQUEST["year"];
    $prev_year = $cYear;
    $next_year = $cYear;
    $prev_month = $cMonth - 1;
    $next_month = $cMonth + 1;
    if ($prev_month == 0)
      {
        $prev_month = 12;
        $prev_year = $cYear - 1;
      }
    if ($next_month == 13)
      {
        $next_month = 1;
        $next_year = $cYear + 1;
      }
    ?>

      <a href="<?php
    echo $_SERVER["PHP_SELF"] . "?month=" . $prev_month . "&year=" . $prev_year; ?>" style="color:#FFFFFF">Previous
    <a href="<?php
    echo $_SERVER["PHP_SELF"] . "?month=" . $next_month . "&year=" . $next_year; ?>" style="color:#FFFFFF">Next

    <?php
    echo $monthNames[$cMonth - 1] . ' ' . $cYear; ?>

    S
    M
    T
    W
    T
    F
    S

    <?php
    $timestamp = mktime(0, 0, 0, $cMonth, 1, $cYear);
    $maxday = date("t", $timestamp);
    $thismonth = getdate($timestamp);
    $startday = $thismonth['wday'];
    for ($i = 0; $i < ($maxday + $startday); $i++)
      {
        if (($i % 7) == 0) echo "
";
        if ($i < $startday) echo "	";
        else
          {
        $class = 'inactive';
        $display = ($i - $startday + 1);
        $month = str_pad($cMonth, 2, 0, STR_PAD_LEFT);
        $day = str_pad(($i - $startday + 1) , 2, 0, STR_PAD_LEFT);
        $date = $cYear . $month . $day;
        if (is_file("data/$date.mp3"))
          {
            $class = 'active';
            $display = "" . ($i - $startday + 1) . "";
          }
        echo "$display	";
          }
      }
    ?>

    <?php
    if (isset($_GET['d']))
      {
        if (is_file("data/{$_GET['d']}.mp3"))
          {
    ?>

    <audio controls autoplay>
    <source src="data/<?php
        echo htmlentities($_GET['d']); ?>.mp3" type="audio/mpeg">
        Your browser does not support the audio element.
    </audio>
    </center
    <?php
          }
      }

    ?>


Can we prioritize devices connected to a Router

Question: If a number of devices are connected to a router, can we prioritize them (PC - 1, Mobile - 2, Laptops - 3) by giving their MAC addresses.
That way if everybody is working, depending upon their priority, overall speed is divided and priority 1 will get the maximum speed in scenario where simultaneously all devices are downloading something
Here are the Specs_--
network device -- Tp-link td-W8901N
Comment: What kind of "router"? Router are layer 3, Mac addresses are layer 2...
Answer: There are several different ways of doing this. I will try to give you some ideas:

you can tag your IP traffic with QoS attributes based on MAC address and apply traffic shaping on your router. This has to be done by the switch but you need a managed switch for this.
put your clients on different subnets and apply traffic shaping policies on your router.
you could put your client on different VLANs based on their MAC addresses and apply traffic shaping policies to different VLANs on the router.

Note, that it all depends on what switches/routers you have. You may not be able to do it at all if your hardware is not adequate.
Comment: Depending on the router, he also might do policy routing and QoS based on the MAC address of the station. Although this is violating the OSI model layer isolation premise, certain implementations (e.g. netfilter-ebtables setting MARKs along with `tc` QoS policies sorting market packets into a given flow) allow this to be done. But it arguably would be much easier to hand out different ranges of IP addresses by the DHCP server and do create QoS rules for the respective IP range.
Comment: Yes, DHCP is another option. Good point.


How to add weight to the total weight of the order witn Commerce Shipping with rules?

Question: I want to add a constant weight to the total weight of the orders in my shopping cart to account for packing materials in the weight calculation.
I'm also using Commerce Shipping Postal Code Code Weight. The Postal code weights work brilliantly.Shipping Postal Code Weights
What I want to do is add a 6oz to the total weight of my order.
Comment: Related: [Help with hook_commerce_physical_order_weight_alter](http://drupal.stackexchange.com/q/184917/1908)
Answer: You should implement this hook in a custom module:
<code>/**
 * Allows modules to alter the weight that has been determined for an order.
 *
 * @param &$weight
 *   The weight field value array representing the weight of the order or NULL
 *   if no weight has yet been determined.
 * @param $order
 *   The order object whose weight is being determined.
 * @param $unit
 *   The unit of measurement to use for the returned weight of the order.
 *
 * @see commerce_physical_order_weight()
 */
function hook_commerce_physical_order_weight_alter(&$weight, $order, $unit) {
  // No example.
}
</code>
Comment: so the hook would have to grab 1) the physical_order_weight value, 2) check conditions (like the order weight does not = 0). take the physical order weight and add 6. How would this look?
Comment: Because, there isn't an example, I'm a little lost. I created a module, and I tried this little bit of code function add_ship_weight_commerce_physical_order_weight_alter(&$weight, $order, $unit) { dpm(&$weight);.} but this doesn't return anything with the devel module.
Comment: You do not need the ampersand sign in dpm, it means the variable is a reference and can be redefined. Alle you need to add is the following code: $weight = ; The other provided variables are for more difficult calculations.


On higher dimension, does rotation matrix product some vector match reflection matrix product the vector?

Question: When you reflect a vector with reflection matrix on 2 dimensional space, and 3 dimensional space, intuitively we know there's rotation matrix can make same result.
But is it possible on higher dimension(4, 5, 6...)?
I know rotation matrix can be represented through reflection matrix product reflection matrix, not vice versa.
Comment: What makes you think your first statement is true?
Comment: Since I am not good at math, I can't prove it. but on 2,3-dimensional space, we can draw some pictures.
Answer: If you have two vectors $u$ and $v$ with $|u|=|v|$, you can construct both a reflection and a rotation in any dimension that will transfer $u\to v$.
For reflection: take hyperplane with normal $u-v$.
For rotation: rotate in plane $(u,v)$ by angle $\arccos(u\cdot v)$ and by any other angles in orthogonal planes.
However, the result of this transformation will be the same only for vector $u$ because in general reflection is not the same as rotation.
Comment: I really appreciated your answer. It bugs me out for days. It was so long time I studied Linear algebra.

But, I don't understand what you said that "the result of this transformation will be the same only for vector u".

you just imply that it works for vector, but it doesn't work for matrix?


At least 3 points on the convex hull

Question: It's almost obvious that for any point set that contains at least 3 points on the Euclidean plane the boundary of its convex hull must contain at least 3 of the points. I worke out a proof (not sure whether it's right), but it relies so much on the concept of "rotation", or "angles" (if someone wants to see the proof please tell me, I'll add that). I wonder if there's a more general proof, or even only using the axioms, as there the concept of "angles" in higher dimensions is quite different.
To simplify: for any point set that contains at least 3 points on the Euclidean plane the boundary of its convex hull must contain at least 3 of the points; is it possible to prove this without using the concept of "angles"?

EDIT. Due to the answer of Theo Bendit a counterexample do exists. Therefore I'm restricting the point set to discrete point set.
Comment: Not if the points lie on a single straight line. More generally, see [Carathéodory's theorem](https://en.wikipedia.org/wiki/Carathéodory%27s_theorem_(convex_hull)).
Comment: @lhf This is set in the plane. If the points are colinear, then the entire convex hull will be boundary.
Answer: Not in general, I'm afraid. Suppose you have the set
$$\{(x, 0) : |x| < 1\} \cup \{(0, y) : |y| < 1\},$$
i.e. the $x$ and $y$-axes intersected with the open unit disc centred at $0$ (which forms a $+$ sign without the tips),
and compute its convex hull. Then you will get an open diamond (the unit ball of the $1$-norm):
$$\{(x, y) : |x| + |y| < 1\}.$$
This set is open, and contains none of its boundary points, let alone any of the points used to generate the set.
Here's another example: consider the set convex hull of the set:
$$\{(x,1/x) : x > 0\} \cup \{(-x, 1/x) : x > 0\},$$
i.e. the graph of the function $|x|^{-1}$. Then the convex hull will be the entire open upper half-plane, i.e. everything above (but not including) the $x$-axis. Once again, no boundary means no points from the original set in the boundary.
There are ways to rectify this. The big, over-the-top, sledghammer-to-kill-a-fly tool here is the Krein-Milman theorem, and Milman's converse to the Krein-Milman theorem. The Krein-Milman theorem states:

Suppose $X$ is a Hausdorff locally convex topological vector space (or $\Bbb{R}^n$ will do fine), and $K$ is a compact, convex subset of $X$. Then $X$ is the closed convex hull of its extreme points.

Milman's converse helps bring it home:

Suppose $X$ is a Hausdorff locally convex topological vector space (or $\Bbb{R}^n$), $T \subseteq X$ is such that the closed, convex hull of $T$ is compact. Then, every extreme point belongs to the closure of $T$.

So, if we can guarantee that our closed, convex hull is compact, and our generating set is closed (which is the case if it's compact, at least in normed linear spaces), then we can reduce our generating set to just the extreme points. If there are two extreme points or fewer, then the set would have to be contained in a line segment, and embedded in a space of $2$ (or more) dimensions, every point would be on the boundary. Otherwise, there are at least $3$ extreme points, all of which must be on the boundary of the closed convex hull.
Note: the assumption that the closed convex hull cannot be dispensed with. In my second example, the set given is closed, but its closed convex hull contains no extreme points, and (once again) the boundary contains none of the original points. This does fix the first example though: if you take the closure (replace the $<$ with $\le$), then the closed convex hull will be compact, and the four extreme points $(\pm 1, 0), (0, \pm 1)$ all lie within the original set.
Comment: @SketchySketch If you restrict my second counterexample to $x$ where either $x$ or $1/x$ is an integer, then you'll get much the same result, only with discrete sets. If the sets are finite, then they are compact, and the convex hull will be compact (by Caratheodory's Theorem, in finite-dimensions, see lhf's comment, though Caratheodory is not necessary for finite sets!), and so everything will be fine. Infinite, discrete sets will pose a problem; maybe the result will hold, maybe it won't.
Comment: Clever counterexample! I haven't thought of that before. I realized I forgot the restriction of "discrete" point set; but thanks for your answer!

At least 3 points on the convex hull


Display more numbers in NumberPicker

Question: I have two issues, first one is removing the divider in the NumberPicker and I'm extending the NumberPicker in Android to solve this issue, like this:
import android.content.Context;
import android.content.res.Resources;
import android.util.AttributeSet;
import android.widget.NumberPicker;

import java.lang.reflect.Field;

public class ExtendedNumberPicker extends NumberPicker {

    public ExtendedNumberPicker(Context context, AttributeSet attrs) {
        super(context, attrs);

        Class<?> numberPickerClass = null;
        try {
            numberPickerClass = Class.forName("android.widget.NumberPicker");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        Field selectionDivider = null;
        try {
            selectionDivider = numberPickerClass.getDeclaredField("mSelectionDivider");
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }

        try {
            selectionDivider.setAccessible(true);
            selectionDivider.set(this, null);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (Resources.NotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}

My other issue is that I didn't find any way to display more than 3 elements like the below UI:
Answer: Set Removing divider lines
<NumberPicker
   ...
   android:theme="@style/DefaultNumberPickerTheme" />

style.xml

For the other part : Checkout this question
Hope this helps !

Display more numbers in NumberPicker


Is it true that a smooth, harmonic functions with compactly supported gradient is trivial?

Question: Let $u \in C^{\infty}(\mathbb{R}^n)$ be such that $\nabla u \in C^{\infty}_c(\mathbb{R}^3; \mathbb{R}^3)$ and $\Delta u=0$. I wish to prove or disprove that $u = c$ for some $c \in \mathbb{R}^n$; note the statement would be true with $c=0$ (by Liouville classical theorem) if $u$ itself is compactly supported.
I had the idea of exploiting a representation formula like:
$$ u(x) = \frac{1}{n \omega_n} \int_{\mathbb{R}^3} \nabla u(y) \cdot \frac{x-y}{|x-y|^n} dy $$
together with an integration by parts in order to get the Laplacian. Unfortunately, the latter is only valid if $u \in W^{1,1}(\mathbb{R}^n)$ and here we don't have the hypothesis $u \in L^1(\mathbb{R}^n)$. I am stuck here, but at same time I cannot produce a counterexample.
Comment: What about constant functions? Like $u=1$, this is harmonic and the gradient vanishes.
Comment: You are right, thank you, the idea was to exclude them. I edit the post
Comment: This is in fact the only thing that could happen. Note that the gradient has compact support, thus $u$ is constant outside a compact set. Hence, there exists a constant $c$ such that $v:=u-c$ has compact support. But $v$ is harmonic and thus vanishes. This implies that $u$ is constant.
Answer: Note that the gradient has compact support, thus $u$ is constant outside a compact set. Hence, there exists a constant $c$ such that $v:=u-c$ has compact support. But $v$ is harmonic and thus vanishes. This implies that $u$ is constant.
Answer: I think that you can prove that the function is constant, but not necessarily zero: since $\nabla u$ has compact support, there exists $R>0$ such that $\nabla u \equiv 0$ in $\mathbb{R}^{n} \setminus \overline{B(0;R)}$, and then $u \equiv c$ ($c \in \mathbb{R}$ is a constant) in $\mathbb{R}^{n} \setminus \overline{B(0;R)}$. From this,
$$ |u(x)| \leq \max \left \lbrace c, \Bigg| \max_{x \in \overline{B(0,R)}}u \Bigg|\right \rbrace, $$
that is, $u$ is bounded. By Liouville theorem, you obtain that $u$ is constant.
Answer: Differentiating the equation we note
$$0=\partial_i\Delta u = \Delta \partial_i u$$ which means that the components of $\nabla u$ are themselves harmonic. Since they are compactly supported, they vanish identically, and so $u$ is constant.


Form #redirect not working?

Question: I'm trying to make the user creation form redirect back to the home page when you submit it. I'm using Content Profiles so it is two forms sharing a submit button. Even if I set #redirect = '/' on both forms the form always redirects back to itself. It works and everything, but won't redirect how I want.
Any ideas?
Code:
function mymodule_form_alter(&$form, $form_state, $form_id) {
      switch ($form_id) {
        case 'user_register':
        $form['#redirect'] = '/';
        break;
        case 'coordinator_node_form':
        $form['#redirect'] = '/';
    }
}

Comment: Can we see the code you're using?
Comment: There ya go. Hopefully you spot something.
Answer: There are two facts to keep in consideration about $form['#redirect']:

$form_state['#redirect'], set in a form submission handler, takes the precedence over $form['#redirect'].
$form['#redirect'] and $form_state['#redirect'] are ignored for forms where "#action" has been set by a module. That is what happen with the user login form.
$form['#redirect'] and $form_state['#redirect'] are ignored when $_REQUEST['destination'] is set; its value is instead used.

If you want to redirect a form, and be sure it gets redirected to the path you set, you should implement hook_form_alter() to add a form submission handler that alters $form_state['#redirect']. The module implementing that hook should be executed after other modules that alter $form_state['#redirect'] for that module.
This doesn't have any effect, though, in the last two cases I listed before.
Comment: So is there any downside to my solution? Unsetting destination in hook_form_alter seems to work, but are there situations in which it won't work?
Comment: The "downside" is that you cannot be sure the user is effectively redirected to the page you want; it's enough another module adds a submission handler, and it sets `$form_state['#redirect']`.
Comment: So how do I redirect a form that has the action set?
Comment: You unset `$form['#action']`.
Comment: @kiamlaluno, thanks for the insight but where is all this information present in the FAPI documentation at Drupal site?
Comment: Part of what I wrote is understandable from the code of [drupal_redirect_form()](http://api.drupal.org/api/drupal/includes--form.inc/function/drupal_redirect_form/6). I don't remember in which function is evident the Drupal's behavior for forms setting `$form['#action']`, but I remember that is the Drupal's behavior.
Answer: Ok after much digging I found the answer here: http://drupal.org/node/934664
Apparently destination overwrites #redirect so I just unset destination and it works.

Form #redirect not working?