Groovy wslite client not working for SOAP based java web service

Question: I am using Grails 2.2.3.
    I am not able to call a SOAP based JAVA web service with parameters from Grails. I am using wslite. We are able to call a SOAP based web service but when we are passing the parameter, at the server end always receiving as NULL.
My Groovy Code snippet is as follows:

package poc.service
@Grab(group='com.github.groovy-wslite', module='groovy-wslite', version='0.8.0')
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;

import wslite.soap.SOAPClient
import wslite.http.HTTPRequest
import wslite.http.HTTPResponse

class LoginService {
    static def checkUserData(def _userName12) {

       def client = new SOAPClient('http://192.168.14.147:9090/SOAPServiceDemo/authenticate')
        def userNameValue = _userName12

        def response = client.send(SOAPAction:'\"http://example.service.com/checkUser\"'){
            header{
            }
            body {
                 checkUser(xmlns:'http://example.service.com/') {
                     userName12(_userName12)
                 }
            }
        }
        println "User Name = " + response.checkUserResponse.return
    }

    static main(args){
       def status =  checkUserData('123')
       println status
    }
}

Below is another example which is working fine. It is copied from google.

package poc.service

import wslite.soap.SOAPClient
import wslite.http.HTTPRequest
import wslite.http.HTTPResponse

class MothersDay {
    static def checkMotherData(String _userName12) {

       def client = new SOAPClient('http://www.holidaywebservice.com/Holidays/US/Dates/USHolidayDates.asmx')
       def response = client.send(SOAPAction:'http://www.27seconds.com/Holidays/US/Dates/GetMothersDay') {
           body {
               GetMothersDay('xmlns':'http://www.27seconds.com/Holidays/US/Dates/') {
                   year(_userName12)
               }
           }
       }
       println "Result = " + response.GetMothersDayResponse.GetMothersDayResult.toString()
    }

    static main(args){
       def status =  checkMotherData("2018")
    }
}

Please let me know if you have any idea where I am lacking.

Thanks
Ravi

Answer: Use SOAPAction as
client.send(SOAPAction:'http://example.service.com/checkUser')

without trying to escape " which should not be part of the url.
Answer: This may be a little late for you, but for anyone else who had this problem it seems to be around how WSLite is setting the namespace for the method call.  You can see the actual soap message that gets passed in by looking at how the SOAPClient generates the envelope using the SOAPMessageBuilder object (OpenSource is your friend).  Anyway, to cut to the point, you need to add your namespace as part of the envelope attributes and then manually force your method to use that namespace instead of passing it is an argument to your method (which seems to only work for .NET web services).  So it should look like this:
def response = client.send(SOAPAction:'http://example.service.com/checkUser') {
    envelopeAttributes "xmlns:ex":"http://example.service.com/"
    body {
         'ex:checkUser'() {
             userName12(_userName12)
         }
    }
}

Hope that helps for anyone else with this problem.


Transformar maiúscula em minúscula em string

Question: Preciso fazer uma função que receba duas strings, e troque ambas de lugares. Mas se tiver uma letra maiúscula na primeira, na hora de converter precisa ir para minúscula. Eu tentei fazer, só que acho que está errado dentro do meu while. O que posso fazer?
Nota: não posso usar funções da 'string.h'.
void str_troca(char origem[], char minusc[])
{
 char aux[MAX];
    int i=0;
    int a=1;
    int b=0;

    while(origem[i]!='\0')
    {
        if(origem[i]>64 && origem[i]<91)
        {
            origem[i]-32;
        }
        i++;
    }

    aux[i]=origem[i];
    origem[i]=minusc[i];
    minusc[i]=aux[i];

    printf("%s\n",minusc );
    printf("%s\n",origem );

}

Answer: Você quase acertou, só cometeu um pequeno erro bobo. No lugar disso:
        origem[i]-32;

Use isso:
        origem[i]+=32;

Ou seja, era para usar mais ao invés de menos e faltou o sinal de igual.
Dito isso, pode-se fazer mais algumas sugestões. Para que o código seja legível, substitua >64 por >= 'A' e substitua <91 por <= 'Z'. Assim, fica bem claro que você está olhando para letras maiúsculas e não precisa ficar decorando ou consultando a tabela ASCII com números arbitrários e arcanos. Da mesma forma, você pode usar origem[i] += 'a' - 'A'; - isso pode, de uma certa forma, ser lido como "coloque (+) a minúscula e tire (-) a maiúscula".
Comment: nossa, erro besta kkkk. Vlw mano, ajudou mto kkk
Comment: Boa a sua dica do  `>='A'` mas tem que tomar cuidado para colocar aspas simples e não aspa dupla.


pmin(x, 60) and subset regression

Question: Is there any difference between
y ~ pmin(x, 60) + sex , df = data

and
y ~ x + sex, df = subset(data, x <=60)

If they are the same, then why use pmin(x, 60)
Answer: pmin will replace all instances of x greater than 60 by 60, and leave the vector x of the same length as it was before applying pmin. On the other hand, subset will filter the data, so it will reduce the sample size to those units satisfying the subsetting condition. Hence, the two datasets are, in general, different.
Here is a simple example.
set.seed(25)

# generate some data
dd <- data.frame(x = c(1,3,60, 5, 100, 7, 200),
                 sex = c("M", "F", "M", "F", "F", "M", "F"),
                 y = runif(7))

# "pmined" data
dd2 <- dd
dd2$x <- pmin(dd$x, 60)

# filtered data
> subset(dd, x<= 60)
   x sex         y
1  1   M 0.4161184
2  3   F 0.6947637
3 60   M 0.1488006
4  5   F 0.8973850
6  7   M 0.9851157

# "pminded" data
> dd2

  x sex         y
1  1   M 0.4161184
2  3   F 0.6947637
3 60   M 0.1488006
4  5   F 0.8973850
5 60   F 0.1243921
6  7   M 0.9851157
7 60   F 0.6260962

Comment: Thanks your point is noted. Also just a headsup, I poseted another related question here, https://stats.stackexchange.com/questions/603083/breaking-the-regression-line-into-two-pieces

pmin(x, 60) and subset regression


Requiring the CPU to cache data using an offset (non consequtively)

Question: We all know that the following code will have low performace, since at each iteration the CPU will load the new element s from the RAM.
#define N a very large number
struct{
    float m;
    int x[N]
} S;

void main(){
  struct S s[elements];
  ...
     //working with data
     for (i=0; i<elements;i++){
         total+=s[i].m;
     }
 ...
}

If N is small, and the elements of kind s can be kept inside the cache, it is very fast. Otherwise, the CPU will always ask for the new element to the RAM.
Since the array s[k].x is not used inside the loop, soes a function, to ask the CPU to collect elements in the cache, let's say every N*sizeof(int) bytes exists?
In this way, the cache will contains all s[k].m variables, and so it may keep everything inside the cache.
Answer: This is a pattern modern CPUs are capable of recognizing. Read Optimizing Application Performance on Intel® Core™ Microarchitecture Using Hardware-Implemented Prefetchers:

Hardware prefetcher: The hardware prefetcher operates transparently, without programmer intervention, to fetch streams of data and instruction from memory into the unified second-level cache. The prefetcher is capable of handling multiple streams in either the forward or backward direction. It is triggered when successive cache misses occur in the last-level cache and a stride in the access pattern is detected, such as in the case of loop iterations that access array elements.


How to test significant difference of time-series data, i.e. the current data is significantly different from the past data

Question: I am working on some data like below. The data have an increasing trend with big error bars. So what kind of statistical tool I can use to test if the current level of flux is significantly higher than those from the past?
One reviewer says that the flux in 2017 is at the same level as that in 1945, because the error bars are overlapped. I just don't know how to reply to that.
Comment: Where does that confidence interval come from? If you observe the time-series what is its purpose?
Comment: The error bars come from the cumulated errors through several steps of calculations, using different sources of data. I want to interpret this graph as the fluxes are increasing especially after 2000, not just unchanged.
Answer: Your reviewer is (maybe) right, but he/she kind of cherrypicked his comparison point.
First, why a maybe. Even if two data points are in the 95% interval of each other, their difference might be significantly different at a 5% margin.
See: https://towardsdatascience.com/why-overlapping-confidence-intervals-mean-nothing-about-statistical-significance-48360559900a
To get a correct inference, you have to make the difference between 2017 and all other years, then compute the associated standard errors. Graphically, 1945 will be clearly an outlier compared to most "old" years.
Second, I would take averages over ten years, compute the difference between decades, and the associated standard errors. I think they will be lower. At the end, just make a separate test between the mean value over 2000-2017 and the mean value before. Seeing the graph, it will be significant I think.
Comment: In my answer, it is up to you to correctly compute the standard errors of the differences. Ideally, you would like to take accounts your errors are probably correlated. For instance, some kind of measurement might have produced a positive bias over all years. Not taking it into account might distort the test. (The provided example would make a test guessing independence too conservative.)
Comment: By the way, this is what your reviewer makes by just looking at the graph...


Restarting rsyslog re-sends logs again

Question: I am running Ubuntu 12.04.1 LTS on EC2.  I have a bunch of application servers which are configured to forward their logs to a central server via rsyslog.
Since putting in Nagios monitoring on the log files on the central server, I've been getting alerts indicating that particular application servers are failing to forward their logs to the centralized server.
Logging into the machines and restarting the rsyslog service fixes the problem.  However, rsyslog then re-transmits the logs again, resulting in duplicates on the collector.  Why is it doing this?
Answer: The freezing of log transmission aspect of this problem appears to likely be due to a bug in the way rsyslog is configured out of the box with 'buntu: https://bugs.launchpad.net/ubuntu/+source/rsyslog/+bug/940030
I was also able to find an interesting post on expertsexchange: www.expert-sex-change.com/OS/Linux/Administration/Q_27511414.html:

> I recently ran into a problem and was hoping someone could help me figure it out.  I am
> running Ubuntu 10.04 and rsyslog 5.8.1.  I setup rsyslog to monitor a few files and send
> the any changes to those files to Loggly (great service by the way).  Well, it all works
> great, except for the fact that whenever I restart rsyslog it resends everything from those
> files that it had sent in the past.  Now, it is my understanding that rsyslog should use
> the $WorkDirectory and create what file that you set for $InputFileStateFile to save the
> state of the monitored file so that it does not send duplicate entries.
>
> Here is an example that I'm working with:
>
> $WorkDirectory /var/log/rsyslog
>
> # Monit log file
> $InputFileName /var/log/monit.log
> $InputFileTag monit
> $InputFileStateFile monit-state
> $InputFileSeverity info
> $InputRunFileMonitor
>
> So, from my description above, rsyslog should create a "monit-state" file in
> "/var/log/rsyslog" which would save the state of the /var/log/monit.log" file so no
> duplicates are sent.  Is that correct?  If so, this is not happening!
>
> What should the premission of "/var/log/rsyslog" be?  Do I have to touch "monit-state" in
> "/var/log/rsyslog" (I tried that already and nothing happened)?

With an interesting answer:

> Ok, I found this site (Trouble Shooting Rsyslog) and went through the interactive debugging
> mode using:
>
> rsyslogd -c5 -dn > logfile
> 1:
> Select all
> Open in new window
>
>
> I was able to see that it was in fact a permissions problem.  I opened up permissions to
> 777 for my $WorkDirectory, just to test, and rsyslog did create the state files and
> everything worked as planned.  I will continue to play with the permissions so that it's
> not 777 (obviously), but I wanted to let anyone else that might be having this problem know
> how I solved it.

I have adjusted the permissions on /var/spool/rsyslog to be owned by user "syslog".  I've tested for duplicate transmissions after applying this change and it seems to have fixed the problem.  If the problem re-emerges or I find out that this didn't fix it, I will return here and update the answer.
SOLUTION:
<code>$ sudo chown syslog /var/spool/rsyslog
</code>

Restarting rsyslog re-sends logs again


Por que "segmentation fault " quando se intercala dois arrays?

Question: Estou construindo um simples programa em c/c++ que intercala dois arrays mas estou encontrando um erro inconveniente. Creio que ao chamar a função IntercalarArranjos, o programa apresenta um erro do tipo "segmentation fault".
Não sei se errei na lógica dessa função e sei que esse problema está relacionado a acesso indevido da memória ou simplesmente overflow da mesma. Perdoem me, mais sou ainda iniciante nesse assunto.
Aqui está o código:
 #include <iostream>
 #include <stdlib.h>
 #include <stdio.h>

 /****
 *
 *   Título do módulo :
 *
 *   Descrição geral  :
 *
 *   Entrada :
 *
 *   Saída   :
 *
 ****/
 void IntercalarArranjos ( float * primeiroArranjo , float *  segundoArranjo , float * arranjoIntercalado ,int quantPrimeiroArranjo ,  int quantSegundoArranjo , int quantArranjoIntercalado ){

     int i , j , k ;

     k = 0;

     j = 0;

     i = 0;

     while ( i < quantArranjoIntercalado ){

         if( j > quantPrimeiroArranjo ){

             *( arranjoIntercalado + i ) = *( segundoArranjo + j );

             k = k + 1;

         }

         if( k > quantSegundoArranjo ){

             *( arranjoIntercalado + i ) = *( primeiroArranjo + k );

             j = j + 1 ;

         }

         if(  j <=  quantPrimeiroArranjo && k <= quantSegundoArranjo ){

             if( i % 2 == 0 ){

                 *( arranjoIntercalado + i ) = *( primeiroArranjo + j );

                 j = j + 1 ;

             }
             else {

                 *( arranjoIntercalado + i ) = *( segundoArranjo + k );

                 k = k + 1 ;

             }
         }

     }
 }

 int cont = 0 ; /** variável global **/

 /****
 *
 *   Título do módulo : ImprimaVetor
 *
 *   Descrição geral  : Imprime o arranjo desejado
 *
 *   Entrada : (int) quantidade de elementos , (float) vetor dos elementos
 *
 *   Saída   : nenhuma
 *
 ****/

 void ImprimaVetor( int quantVetor , float * realVector ){

     int i ;

     cont += 1 ;

     if( cont == 1 ){

          printf("\nPrimeiro arranjo : ");

     }

     else{

         if( cont == 2 ){

             printf("Segundo arranjo : ");

         }

         else printf("Arranjos intercalados : ");

     }

     for( i = 0 ; i < quantVetor ; i ++ ){
         printf(" %f ", *( realVector + i ) );

     }

     printf("\n\n");

 }

 /****
 *
 *   Título do módulo : LeiaVetor
 *
 *   Descrição geral  : Lê o vetor de elementos
 *
 *   Entrada : (int) quntidade de elementos do vetor , (float) vetor dos    elementos
 *
 *   Saída   : nenhuma
 *
 ****/

 void LeiaVetor( int quantVetor , float * realVetor ){

     int i ;

     for( i = 0 ; i < quantVetor ; i ++ ){

         printf("\n\nDigite o %d elemento do arranjo :", i + 1 );
         scanf("%f", realVetor + i );

     }

 }

 int main()
 {

     float * primeiroArranjo , * segundoArranjo , * arranjoIntercalado ;
     int quantPrimeiroArranjo , quantSegundoArranjo , quantArranjoIntercalado ;

     printf( "---------------------------------------------------------");
     printf( "\nInsira a quntidade de elementos do primeiro arranjo :" );
     scanf("%d", &quantPrimeiroArranjo );

     primeiroArranjo = (float*) malloc( quantPrimeiroArranjo*sizeof(float) );

     LeiaVetor( quantPrimeiroArranjo , primeiroArranjo );

     printf("\n\n");

     printf( "---------------------------------------------------------");
     printf( "\nInsira a quntidade de elementos do segundo arranjo :" );
     scanf("%d", &quantSegundoArranjo );

     segundoArranjo = (float*) malloc( quantSegundoArranjo*sizeof(float) );

     LeiaVetor( quantSegundoArranjo , segundoArranjo );

     printf("\n\n");

     printf( "---------------------------------------------------------");

     quantArranjoIntercalado = quantSegundoArranjo + quantPrimeiroArranjo ;

     arranjoIntercalado = (float*) malloc(  quantArranjoIntercalado*sizeof(float) );

     IntercalarArranjos ( primeiroArranjo ,segundoArranjo ,arranjoIntercalado ,quantPrimeiroArranjo , quantSegundoArranjo ,quantArranjoIntercalado );

     ImprimaVetor( quantPrimeiroArranjo , primeiroArranjo  );

     ImprimaVetor( quantSegundoArranjo , segundoArranjo  );

     ImprimaVetor( quantArranjoIntercalado , arranjoIntercalado );

     printf("\n\n");

     return 0 ;

 }

Comment: C/C++ não existe! Se pretendes usar C++, usa C++ (`new`, `delete`, etc ... não uses `malloc()`, `free()`, etc)
Comment: Desculpe. Mas não achei seu comentário construtivo. E sim , posso usar malloc() e free() em um programa c++ . O que me impede ? Mas não é esse o problema.
Comment: *Hint*: uma forma mais usual de escrever `*(apontador + deslocamento)` é `apontador[deslocamento]`.
Answer: As instruções
     k += k + 1;
     j += j + 1;

deviam ser
     k = k + 1;
     j = j + 1;

ou
     k += 1;
     j += 1;

ou
     k++;
     j++;

Comment: Valeu. Nem percebi esse "detalhe" . Mas o problema persiste ainda.
Comment: Vou editar a pergunta
Answer: Caro colega, analisando o seu código percebi que ao alterar o operador relacional de < como consta no seu código, para >, dentro da função IntercalarArranjos() ele não exibe segmentation fault, mais precisamente nessa parte citada abaixo:
while ( i > quantArranjoIntercalado )

o que pude perceber é que você "instruiu" que enquanto i for menor que quantArranjoIntercalado faça isso, mas não houve uma verificação, visto que a única instrução que alterei foi essa além de declarar as funções antes de definilas.
Obs:Outra coisa que pude perceber no seu código é você está alocando, mas não se preocupou em liberar o que foi alocado.


tsparticles : Interruption in particle motion (defect in movement or has stutter and lag) after build in react

Question: everything works fine in development mode when I use npm run start, but in production and deployed mode after build (npm run build) there is Interruption in particle motion or it's way slow.
I changed and tested all the tsparticles options but it still did not work properly.
my react version is 17.0.2 , typescript 4.5.4 and tsParticles 1.38.0
import Particles from "react-tsparticles";
export const Header = (props:any) => {

return (

<Particles
      id="tsparticles"
      options={
        {
          "background": {
            "color": {
              "value": "#00000095"
            },
            "position": "50% 50%",
            "repeat": "no-repeat",
            "size": "cover",
            "opacity": 1,
            "image": "url('/img/bg1.jpg')"
          },

         "backgroundMask": {
           "composite": "destination-out",
           "cover": {
             "color": {
               "value": {
                 "r": 255,
                 "g": 255,
                 "b": 255
               }
             },
             "opacity": 1
           },
           "enable": true
         },

         "fullScreen": {
           "enable": false,
           "zIndex": -10
         },
         "interactivity": {
           "events": {
             "onClick": {
               "enable": true,
               "mode": "push"
             },
             "onHover": {
               "enable": true,
               "mode": "bubble",
               "parallax": {
                 "force": 60
               }
             }
           }
         },
         "particles": {
           "color": {
             "value": "#ffffff"
           },
           "move": {
             "attract": {
               "rotate": {
                 "x": 600,
                 "y": 1200
               }
             },
             "enable": true,
             "outModes": {
               "bottom": "out",
               "left": "out",
               "right": "out",
               "top": "out",
               "default": "none"
             },
             "direction": "right",
             "speed": 2
           },
           "number": {
             "density": {
               "enable": true,
             },
             "value": 60
           },
           "opacity": {
             "value": {
               "min": 0.1,
               "max": 0.5
             },
             "animation": {
               "enable": true,
               "speed": 1,
               "minimumValue": 0.1
             }
           },
           "shape": {
             "options": {
               "polygon": {
                 "sides": 5
               },
               "star": {
                 "sides": 5
               }
             },
             "type": "square"
           },

           "size": {
             "random": {
               "enable": true,
               "minimumValue": 0,
             },
             "value": {
               "min": 5,
               "max": 20
             },
             "animation": {
               "speed": 10,
               "minimumValue": 0.1
             }
           }
         }
       }
     }

   }
  />

  )
  }

I also changed the values of the retina_detect and detectRetina to false but it was not resolved.
Answer: I found the reason for this issue, there is a problem with the build tool or bundle file that occurs when using the npm run build command.
now I am building the project with Webpack and there is no interruption but not full fixed.
also may be solved by changing the browserslist in package.json
Following for more details this issue:
https://github.com/matteobruni/tsparticles/issues/2809


Is $\sum_{c \notin \mathbb Z_q}\psi(c)-\sum_{c \notin \mathbb Z_q}\psi(c^n)$ an integer?

Question: Let $n$ be a positive integer. Let $p$ be an odd prime and $q=p^k$. Let $c \in \mathbb Z_q$. Consider the additive character $\psi:\mathbb Z_q \rightarrow \mathbb C^{\times}$ that is defined as $\psi(m)=e^{2\pi im/p^k}$. Is the following always an integer?
$$\sum_{c \notin \mathbb Z^{\times}_q}\psi(c)-\sum_{c \notin \mathbb Z^{\times}_q}\psi(c^n)$$
where $\mathbb Z^{\times}_q$ is the multiplicative group of $\mathbb Z_q$
Comment: What do you sum over? $c\notin\mathbb Z_q$ - where is $c$?
Comment: If you take it over $c\in\mathbb Z_q^\times$ (in place of $c\notin \mathbb Z_p^\times$) then it's rational by say Galois theory and integer since it's an algebraic integer. If you sum over $c\in\mathbb Z_q$ then it's clearly an integer (0 unless $p^k$ divides $n$). So it is always integer.
Comment: I fixed the question. Sorry about that...
Comment: thank you. But I did not clearly understand why it is integer if I take the sum over $\mathbb Z_q^{\times}$
Answer: Since $\psi$'s domain is precisely $\Bbb Z_q$, both sums are empty sums, conventionally taken to be $0$. Thus, you have have $0-0=0$, an integer.
Comment: I fixed the question. It is changed now... Sorry about the syntax..


Joomla! 2.5 checking code for deprecated classes / methods

Question: How can I check my extensions for deprecated Joomla! API code?
Answer: This is to be done on a development machine, not on the production website!
The most basic way to check for deprecated code is to enable the System Debug Plugin and to enable the option "Log deprecated API".

After this in logs/deprecated.php you will find the entries.
Now, there will be lots of deprecated code loged and you need to identify it in your code.

A complementary option would be to use an IDE like Eclipse + PDT where you can get this info while you are coding:


Like system using laravel and ajax Error 500

Question: I am encountering a 500 error in my Laravel AJAX-like system, and I am seeking assistance to resolve this issue. When I click the like button, it triggers the likeIconClicked() function, which sends an AJAX request to the server. The request is intended to perform the like action and update the icon accordingly. However, instead of the expected behavior, I received a 500 error.
enter image description here
I have checked that the AJAX request parameters, such as the content ID, are correctly sent to the Laravel route. Additionally, I have verified that the route is properly defined and that the CSRF token is included in the request headers. Despite these confirmations, the issue persists. I would appreciate any insights or suggestions to help me troubleshoot and resolve this error. Thank you in advance for your assistance.
for the button
<button onclick="likeIconClicked()" id="like-icon">

js
function likeIconClicked() {

  // Envoyer une requête AJAX au serveur pour effectuer l'action de like
  $.ajax({
    url: '{{ route('like', $resultat->code) }}' ,
    method: 'POST',
    headers: {
    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
  },
    success: function(response) {

      // Changer la couleur de l'icône en fonction de la réponse du serveur
      if (response.liked) {
        // L'utilisateur a aimé, donc ajouter la classe CSS pour la couleur rouge
        $('#like-icon').addClass('liked');
      } else {
        // L'utilisateur a annulé son like, donc supprimer la classe CSS pour la couleur rouge
        $('#like-icon').removeClass('liked');
      }
    },
    error: function(xhr, status, error) {
      // Gérer les erreurs de la requête
      console.log(error);
    }
  });
}

controller
 public function like($code)
    {
        $annonce=Annonce::findorfail($code);
        $user=Auth::user();
        if($user->hasLiked($annonce)){
            $user->unlike($annonce);
            $bol=false;
        }
        else{
            $user->like($annonce);
            $bol=true;
        }

        return response()->json([
            'liked' => $bol,
        ]);
    }

route
Route::post('/like/{code}', 'App\Http\Controllers\AnnonceController@like')->name('like');

Comment: Thank you for your response! I followed your suggestion and used the URL {{ route('like', ['code' => $resultat->code]) }}. Additionally, after investigating the error logs in the laravel.log file, I discovered that the issue stemmed from the 'annonce_id' column being set to null when inserting data into the 'likes' table. I went ahead and fixed the method in my User model to ensure the proper assignment of 'annonce_id'.I'm happy to share that it worked! The error is now resolved.
Comment: Welcome to SO ... have you made sure that `$resultat->code` is not `null`? also i would explicitly define the key to make sure it is taking the parameter: `route('like', ['code' => $resultat->code])` ..... on a site note, you should check the server logs for what is causing the 500 error instead of guessing
Answer: Replace this code:
url: '{{ route('like', $resultat->code) }}'

With this code:
url: '{{ route('like', [$resultat->code]) }}'

OR this Code
url: "{{ route('like') }}" + '/' + $resultat->code,


AWS and Elastic Beanstalk

Question: I bought a domain from godaddy ex: yoursite.com.
Right now, I am running WordPress using aws elastic beanstalk and I want visitors to have access from my subdomain.
Let's say I own the domain "http://yoursite.ap-southeast-1.elasticbeanstalk.com". How can I link my environment with the subdomain from godaddy. I only found a way to link the primary domain with elasticbeanstalk
Answer: Check below screenshot. When you go to edit zone record below settings you have to apply for your subdomain to point to the elastic beanstalk.
Comment: only work for access subdomain.yoursite.com. Not work if user visit post or page at wordpress

if user click post. link become yoursite.beanstalk again
Comment: That you will have to achieve using your web server or htaccess file. Above procedure is for pointing your subdomain to your elastic beanstalk
Comment: I only found step by step yoursite.com link to elastic beanstalk. any tutorial that i can follow?
Comment: Can you elaborate what you want ? do you want to map your site.com to EB or subdomain.yoursite.com to EB?
Comment: only subdomain.yoursite.com and subdomain.yoursite.com/* to EB. I think I need to setup route53 but I dont know how to do it. my yoursite.com using other platform outside aws services
Comment: Do you have a htaccess file?

AWS and Elastic Beanstalk


How to prove a bitstring structural induction problem

Question: A bitstring is a string consisting of only 0s and 1s. Define "·" to be the operation of concatenation, and let $\epsilon$ be the empty
bitstring. Consider the following recursive definition of the function
"count", which counts the number of 1's in the bitstring:
• count$(\epsilon) = 0$,
• count$(s \cdot 1) = 1 +$ count($s$),
• count$(s \cdot 0) =$ count($s$).
How would I use structural induction to prove that count$(s \cdot t) =$ count($s$)+count($t$)? I know that the base case is $t = \epsilon$, but have no idea what to do for the inductive step.
Comment: I recommend using two base cases here: count$(s \cdot 0) =$ count$(s)$ and count$(s \cdot 1) = 1 +$ count$(s)$.
Answer: Here we have given the set of bitstrings and a function count which counts the number of $1$'s in a string. The function count is recursively defined via base case and constructor case:

base case: count$(\epsilon) = 0$

constructor case: count$(s \cdot a) = a + $count($s$), where $a\in\{0,1\}\qquad\qquad\qquad(1)$

In order to show for two bitstrings $s,t$ the claim
\begin{align*}
\color{blue}{\mathrm{count}(s\cdot t)=\mathrm{count}(s)+\mathrm{count}(t)}\tag{2}
\end{align*}
we will use the base case as well as the constructor case.
Base step:

Let $s$ be a bitstring. As base step we consider $t=\epsilon$. We obtain
\begin{align*}
\color{blue}{\mathrm{count}(s\cdot \epsilon)}&=\mathrm{count}(s\cdot \epsilon)\\
&=\mathrm{count}(s)\\
&=\mathrm{count}(s)+0\\
&\,\,\color{blue}{=\mathrm{count}(s)+\mathrm{count}(\epsilon)}
\end{align*}
and the base step follows.

Induction step: Let $s,t$ be bitstrings with $t=t^{\prime}\cdot a, a\in\{0,1\}$. According to the induction hypothesis we assume
\begin{align*}
\mathrm{count}(s\cdot t^{\prime})=\mathrm{count}(s)+\mathrm{count}(t^{\prime})\tag{3}
\end{align*}

We obtain
\begin{align*}
\mathrm{count}(s\cdot t)&=\mathrm{count}(s\cdot \left(t^{\prime}\cdot a\right))\tag{$\to$ definition of $t$}\\
&=\mathrm{count}(\left(s\cdot t^{\prime}\right)\cdot a))\tag{$\to$ concatenation rule}\\
&=\mathrm{count}\left(s\cdot t^{\prime}\right)+a\tag{$\to$  (1)}\\
&=\left(\mathrm{count}\left(s\right)+\mathrm{count}\left(t^{\prime}\right)\right)+a\tag{$\to$ (3)}\\
&=\mathrm{count}\left(s\right)+\left(\mathrm{count}\left(t^{\prime}\right)+a\right)\\
&=\mathrm{count}\left(s\right)+\mathrm{count}\left(t^{\prime}\cdot a\right)\tag{$\to$  (1)}\\
&\,\,\color{blue}{=\mathrm{count}\left(s\right)+\mathrm{count}\left(t\right)}\tag{$\to$ definition of $t$}
\end{align*}
and the claim (2) follows.


Rselenium - "This version of ChromeDriver only supports Chrome version 74"

Question: Estou tentando usar o Rselenium, mas parece que a versão do chromedriver foi atualizada e está retornando o seguinte erro:

"Selenium message:session not created: This version of ChromeDriver only supports Chrome version 74
    (Driver info: chromedriver=74.0.3729.6 (255758eccf3d244491b8a1317aa76e1ce10d57e9-refs/branch-heads/3729@{#29}),platform=Windows NT 6.1.7601 SP1 x86_64) (WARNING: The server did not provide any stacktrace information)"

O código que eu utilizo é o seguinte:
webdrive = selenium(retcommand = T, verbose = T)
TerminalId = rstudioapi::terminalExecute(webdrive)
chrome = remoteDriver(browserName = "chrome", port = 4567)
chrome$open()

Answer: Caso alguém tenha interesse, resolvi o problema com o seguinte código:
webdrive = selenium(retcommand = T, verbose = T, chromever = "73.0.3683.68")
TerminalId = rstudioapi::terminalExecute(webdrive)
chrome = remoteDriver(browserName = "chrome", port = 4567)
chrome$open()


Interpreting R regression output with multiple interaction variables

Question: Context
I am exploring how different factors in targeting affect subjects' self-reported likeliness to purchase a product. Likeliness to purchase was measured on a four point scale: "Very unlikely", "Unlikely", "Somewhat likely", "Very likely."
I fit two models, the first model compares people's responses to the survey at different times of the day. This model does not take into account my treatment and control variables (whether they had previously been shown an ad or not).
The results are as follows:
glm(formula = as.numeric(gfk_data$AnswerText) ~ gfk_data$daypart)

Deviance Residuals:
     Min        1Q    Median        3Q       Max
-2.03341   0.00086   0.00208   0.00376   1.00376

Coefficients:
                               Estimate Std. Error t value Pr(>|t|)
(Intercept)                    2.997917   0.028795 104.112   <2e-16 ***
gfk_data$daypartmiddle_of_day  0.001225   0.034217   0.036    0.971
gfk_data$daypartmorning        0.035496   0.036112   0.983    0.326
gfk_data$daypartovernight     -0.001681   0.032846  -0.051    0.959
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

So nothing is really significant here.
Then what I do is interact the time with the treatment variable so that I can see if people the time of day makes a difference for how likely they were to purchase.
The results for that model are:
glm(formula = as.numeric(gfk_data$AnswerText) ~ gfk_data$daypart *
    gfk_data$Exposure)

    Coefficients: (1 not defined because of singularities)
                                                       Estimate Std. Error t value Pr(>|t|)
(Intercept)                                             3.61140    0.21564  16.748  < 2e-16 ***
gfk_data$daypartmiddle_of_day                          -0.86140    0.38168  -2.257  0.02407 *
gfk_data$daypartmorning                                -0.41140    0.35475  -1.160  0.24623
gfk_data$daypartovernight                               0.05526    0.04918   1.124  0.26116
gfk_data$Exposurecontrol                               -0.57757    0.21907  -2.636  0.00841 **
gfk_data$Exposureexposed                               -0.65813    0.21129  -3.115  0.00185 **
gfk_data$daypartmiddle_of_day:gfk_data$Exposurecontrol  0.82915    0.38445   2.157  0.03108 *
gfk_data$daypartmorning:gfk_data$Exposurecontrol        0.36258    0.35803   1.013  0.31126
gfk_data$daypartovernight:gfk_data$Exposurecontrol     -0.10951    0.06603  -1.659  0.09729 .
gfk_data$daypartmiddle_of_day:gfk_data$Exposureexposed  0.90623    0.38024   2.383  0.01720 *
gfk_data$daypartmorning:gfk_data$Exposureexposed        0.55103    0.35366   1.558  0.11929
gfk_data$daypartovernight:gfk_data$Exposureexposed           NA         NA      NA       NA
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Question
I'm confused because given the base case, which is evening in both models above, how is it that daypartmiddle_of_day:gfk_data$Exposureexposed and daypartmiddle_of_day:gfk_data$Exposurecontrol have both have positive significant coefficients in the interaction model but middle_of_day in in the first model shows very little difference?
Am I interpreting this correctly in saying that both daypartmiddle_of_day:gfk_data$Exposureexposed and daypartmiddle_of_day:gfk_data$Exposurecontrol have on average ratings that are .8-.9 higher than the base case, which is the aggregate of control and exposed for evening?
Comment: When you have complex model output, it's incredibly helpful to plot your model predictions. The 'effects' package makes this very simple and I would recommend trying it out.
Comment: As a side note, I realized I made somewhat of a logical mistake in assembling the dataset I'm using for this model. What I really want to measure is if the time of the impression has an impact on the self reported likeliness to purchase... but regardless, the statistics question here still stands
Answer: There are two things that strike me. Let me demonstrate a little R code I ran to reproduce your dataset:
set.seed(10)

score <- sample(c(0,1,2,3), 40, replace = T)
daypart <- sample(c("Morning", "Midday", "Evening", "Night"), 40, prob =  c(1/3, 1/3, 1/6, 1/6), replace = T)
exposure <- sample(c("Control", "Exposed"), 40, replace = T)

summary(glm(score ~ daypart))

Deviance Residuals:
Min       1Q   Median       3Q      Max
-1.5294  -0.5294  -0.2059   0.5882   1.5882

Coefficients:
           Estimate Std. Error t value Pr(>|t|)
(Intercept)      1.6667     0.6011   2.773  0.00875 **
daypartMidday   -0.1373     0.6520  -0.211  0.83444
daypartMorning  -0.2549     0.6520  -0.391  0.69812
daypartNight     0.3333     0.8501   0.392  0.69727

So, as in your dataset, no time of day is doing significantly "better" than Evening.
(At this point another comment becomes necessary: By doing the analysis your way, you only compare Midday, Morning and Night AGAINST Evening. If you were interested in seeing whether there is an overall difference, you would have to run an ANOVA (or in the case of Treatment as Covariate an ANCOVA). If you were interested in contrasts of the different times of the day, you could run Tukey.)
Back to the dataset. So far no time of day was significantly better than Evening. So now we will include the treatment in our model:
summary(glm(score ~ daypart*exposure))

Deviance Residuals:
Min       1Q   Median       3Q      Max
-1.6250  -0.6250   0.0000   0.6111   1.7778

Coefficients: (1 not defined because of singularities)
                             Estimate Std. Error t value Pr(>|t|)
(Intercept)                     1.000e+00  1.066e+00   0.938    0.355
daypartMidday                   4.444e-01  1.124e+00   0.395    0.695
daypartMorning                  2.222e-01  1.124e+00   0.198    0.844
daypartNight                    8.158e-16  9.735e-01   0.000    1.000
exposureExposed                 1.000e+00  1.306e+00   0.766    0.449
daypartMidday:exposureExposed  -8.194e-01  1.405e+00  -0.583    0.564
daypartMorning:exposureExposed -5.972e-01  1.405e+00  -0.425    0.674
daypartNight:exposureExposed           NA         NA      NA       NA

1) As you can see (the same as in your model provided above) you get the warning: "(1 not defined because of singularities)", which means there is singularity in your data. The problem (in my case, I assume for you it will be the same) is quickly found:
sum(daypart == "Night" & exposure == "Control")
[1] 0

So there are no observations of "Night" and "Control" in the dataset. You will have a similar problem.
2) As you can see in my example, my Intercept contains "Evening" and "Control", so every parameter estimate is interpretable. e.g. Individuals who were both exposed and shopped in the morning will on average display a 0.59 lower score than my Intercept, so Individuals who shop in the Evening and are not exposed (this effect, however, is not significant).
In your data provided, it is unclear, what the Intercept is. Obviously it contains "Evening", but what is

aggregate of control and exposed

? If it is the mean of the two, then how can both Control and Exposure have a negative effect? Also this seems a bit over complicated for me, it would be much easier and cleaner to just compare control to exposure.
So to sum it up:
Firstly, I suggest you take a look at how your "gfk_data$Exposure" is defined and I suggest coding it just with 0/1 or C/E. Then you will get cleaner interpretations of your parameters.
Secondly, I suggest you rethink whether a glm is actually what you want to use here. (AN(C)OVA, Tukey, ...), since it's p-values will only allow you to interpret significant differences towards the reference time&treatment, and not overall.
If you now run your analysis again, I am sure the results will be less confusing.
Comment: Ah, yes you're right- the graphing helped a lot. I went through and changed the contrasts setting and it made sense after. It basically wasn't worth fitting the model to begin with.
Comment: glad everything resolved after all :)


Drupal 7 and MongoDB module howto

Question: Just installed 7.x-1.0-beta1 to Drupal 7rc1.
Should I see some new option in the configuration? Where should I set the connection settings? I have no idea how to use this module...
Comment: I found a README by poking around in the CVS archive, it looks helpful: http://drupalcode.org/viewvc/drupal/contributions/modules/mongodb/README.txt?revision=1.3&view=markup&pathrev=HEAD
Comment: If the module does not work, I wrote a how-to on syncing Drupal and MongoDB http://www.agnosticdev.com/blog-entry/mongodb/drupal-detachment-drupal-and-mongodb-part-23
Answer: I (and my team) wrote most of that module and -- as Jeremy says, it's only needed for extreme scalability. Because of that, it's supposed you know what you are doing (otherwise you will have no chance of scaling to the levels where MongoDB is necessary) and so no UI is provided, just use $conf overrides.
There's a DBTNG driver too but it's more in a proof-of-concept stage so it's in a separate project.
Comment: Hi chx and thanks for taking the time to answer :) I don't consider myself a Drupal expert, but it only took me a couple of hours to test memcache on my laptop (by following its docs), whereas I couldn't find a single example for your module. My humble suggestion would be to add $conf snippet to your project page, so that people like me can actually try out you great module. On the meanwhile I'll try what Grayside suggests.
Comment: I do not understand, grayside linked to the readme I wrote and it has $conf snippets.
Comment: That link does not work. I also don't see any documentation at http://drupal.org/project/mongodb
Comment: The README.txt is in every download. But, here's a post-git migration (which happened a year ago...) http://drupalcode.org/project/mongodb.git/blob/refs/heads/7.x-1.x:/README.txt link.
Answer: This is not a module that you should use unless you have a need to. It can support mongoDB in a number of cases, but doesn't look like it will totally replace mysql.
Generally you should be looking to use something like mongoDB if you are starting to have scalability problems.
What are you actually trying to do?

Drupal 7 and MongoDB module howto


Correct formula to find the range of a projectile (given angle (possibly negative), initial velocity, initial elevation, and g)

Question: Given:

$\theta$ (a negative angle)
$v_0$ (initial velocity)
$y_0$ (initial height)
$g$ (acceleration of gravity)

I want to find the range of a projectile (ignoring wind resistance)
Hours of searching have given no useful results. Those that I thought were useful turned out to be incapable of accounting for negative angles. This formula in particular returns a range of 0 if the angle is 0, which simply doesn't make sense.
For example:

$\theta=-12.5$°
$v_0=100$m/s
$y_0=1.65$m
$g=9.80665$
Comment: What is your question?
Comment: is $\theta$ an angle to the horizontal?
Answer: With horizental velocity $v_x=v_0\cos\theta$ and vertical velocity $v_y=-v_0\sin\theta-gt$ (here $\theta>0$) and integration we see
$$x=\int_0^tv_0\cos\theta\,dt=v_0\cos\theta\,t\,\,\,,\,\,\,y=\int_0^t v_y\,dy=-v_0\sin\theta\,t-\frac12gt^2$$
Eliminating $t$ between them gives
$$y=-\tan\theta\,x-\frac{g}{2v_0^2\cos^2\theta}x^2$$
the range $R$ is the point $(R,y_0<0)$ and you may continue from here!
Edit: The solution for $h=-y_0$ and $\theta<0$ after solving the equation
$$\frac{g}{2v_0^2\cos^2\theta}d^2+\tan\theta\,d-h=0$$
is
$$d=-\dfrac{v_0^2}{2g}\sin2\theta\left(1+\sqrt{1+\dfrac{2gh}{v_0^2\sin^2\theta}}\right)$$
which works for $\theta<0$ as you wanted.
Answer: You can try the following:
The initial horizontal velocity is $v\cos\theta$, the initial vertical velocity is $-v\sin\theta$ (note that it's positive). Before landing on the field, the coordinates of the rocket follows the following equations:
$$x=v\cos\theta\times t$$
$$y=h-v\sin\theta\times t-\frac{gt^2}{2}$$
The rocket lands at the moment $T$ such that $y(T)=0$. Solving the equation $y(X)=0$, one might be able to choose the root that "good" root for $T$. Put this into $x$ you get the range $x(T)$.
Answer: Assuming a projectile is launched at angle $\theta$ from horizontal from a height $y_0$ above the ground, where the ground is assumed to be represented by the line $y = 0.$
The measurement of the angle is such that $\theta = 0$ if the projectile
initially is moving horizontally to the right, and otherwise the angle is measured in a counterclockwise direction from "horizontal to the right,"
so small positive angles are upward and small negative angles are downward.
The objective is to calculate the horizontal distance $d$ from the launch point to the point where the projectile hits the ground, that is, when the $y$ coordinate of the projectile reaches zero.
One way to compute $d$ is first to compute $t_f - t_i,$ the time that elapses from when the projectile is launched until the projectile hits the ground.
We can arbitrarily set $t_i = 0.$
If the initial angle $\theta$ were positive, the projectile would first have to rise to the height where it stops rising, and then fall from that height to the ground.
The upward velocity at time $t$ after the launch is
$$v_y(t) = v_0 \sin\theta - gt.$$
If $t_0$ is the time such that $v_y(t_0) = 0,$ then
$$t_0 = \frac{v_0 \sin\theta}{g}.$$
The height of the projectile at that time is
$$y(t_0) = y_0 + \frac{v_0^2\sin^2\theta}{2g}.$$
The projectile then falls this far in the interval of time $t_f - t_0,$
that is,
$$\frac12 g(t_f - t_0)^2 = y_0 + \frac{v_0^2\sin^2\theta}{2g},$$
and therefore
\begin{align}
t_f
 &= t_0 + \sqrt{\frac2g\left(y_0 +  \frac{v_0^2\sin^2\theta}{2g}\right)} \\
 &= \frac{v_0 \sin\theta}{g}
    + \sqrt{\frac{2y_0}{g} +  \frac{v_0^2\sin^2\theta}{g^2}}.
\end{align}
Arbitrarily setting the $x$ coordinate of the starting point to $0,$
the horizontal position of the projectile at any time $t$ is
$$x(t) = v_0 t \cos\theta.$$
The desired distance $d$ is simply the $x$ coordinate at time $t_f$
(when the projectile hits the ground), so
\begin{align}
d &= v_0 t_f \cos\theta \\
  &= v_0 \left( \frac{v_0 \sin\theta}{g}
    + \sqrt{\frac{2y_0}{g} +  \frac{v_0^2\sin^2\theta}{g^2}} \right)
       \cos\theta \\
  &= \frac{v_0 \cos\theta}{g}
     \left( v_0 \sin\theta + \sqrt{2gy_0 + v_0^2\sin^2\theta} \right). \tag1
\end{align}

In the case $y_0 = 0,$ the square root in $(1)$ is just
$v_0 \sin\theta,$ and the formula can be simplified to the form
$\frac{v_0^2 \sin(2\theta)}{g}$ which is often given as the range of a projectile.
In the case where $\sin\theta \neq 0,$ we can pull a factor of
$v_0\sin\theta$ out of the expression in parentheses in $(1)$ to get
$$
d = \frac{v_0^2\sin\theta\cos\theta}{g}
\left( 1 + \sqrt{\frac{2y_0g}{v_0^2\sin^2\theta} + 1} \right).
$$
Then, using the fact that
$\sin\theta\cos\theta = \frac{\sin(2\theta)}{2},$
we get the formula you found on Wikipedia.
But if $\theta = 0$ then $\sin\theta = 0$ and the Wikipedia formula
has a division by zero, hence it does not evaluate to zero--it does not evaluate at all.
Comment: Right, accidentally said clockwise instead of counterclockwise.
Comment: Just to confirm I'm doing this right: if theta=0, then d=v0(2y0/g) right?
Comment: d=v0(sqrt(2y0/g)) forgot the radical
Comment: Yes, in that case the distance would simplify to $d=v_0\sqrt{2y_0/g}.$
Answer: $V_y = 100 \sin(-12.5) = -21.6440$ m/s
$V_x = 100 \cos(-12.5) = 97.6296$ m/s
Solving for the time of flight t
$S = V_y\cdot t + \frac{1}{2}\cdot g\cdot t^2$
$-1.65 = -21.6440t + \frac{1}{2}\cdot -9.80665\cdot t^2$
$4.90333t^2 + 21.6440t - 1.65 = 0$
$t = \frac{-21.6440+\sqrt{21.6440^2-(4\cdot 4.90333\cdot -1.65})}{2\cdot 4.90333}$
$t = .07496$ seconds
Range is $x = V_x\cdot t$
$x = 97.6296\cdot .07496 = 7.3184$ m
In summary:
$$x = V_x\cdot (\frac{V_y + \sqrt{V_y^2 - (4\cdot \frac{g}{2}\cdot S)}}{g})$$
Where:
$V_x = 100\cos(-12.5)$
$V_y = 100\sin(-12.5)$
$g = -9.80665$
$S = -1.65$
Comment: my answer was 438m.
Comment: The initial height was 1.65 m pointed downwards at an angle of 12.5 degrees? Is that what -12.5 degrees is?
Comment: The example I gave was -12.5, not 12.5, as in 12.5 degrees downward. I'm looking for a formula that works with negative angles.
Comment: For my method, it creates an inconsistency with negative velocities $(V_x)$ Making $V_0$ negative just shifts the inconsistency somewhere else.
Comment: To make it  consistent, $g, S$ and $V_y$ are all negative (downwards),  See edited solution.


Active-Directory blocks LDAP connections from other hosts

Question: I am trying to connect to Active-Directory using LDAP protocol. If the host is "localhost", then there is no problem. If I change the host to anything else, the server responds with wrong user/pass.
I have tried changing the "username" to user@domain, DOMAIN\user...
thanks.
(OS: win server 2012)
Screetshot explaining everything
Answer: Using the server name (example: SERVER.DOMAIN.COM), instead of the ip directly fixed the problem.
That means the dns is required.


Equivalence for direct sum of vector subspaces

Question: I have a lot of problems proving the following statement.

Let $V$ be a vector space. Let $W,K\leq V,$ where $\leq$ denotes vector subspaces.
$W\bigoplus K=V$ $\iff$ $K\leq V$ and is least element with the property $W+K=V.$

The proposition $\implies$ I got it. It's enough to prove that is least element.
Let $S\leq V$ such as $S\subset K.$ Then $K\cap(S+W)=S\cap(K+W),$ so $$K\cap(S+W)=S\cap V= S.$$ Note that, if $S+W=V$ We have $K=S.$ Therefore $K$ is least element with the property $W+K=V.$
My problem is the other implication. I cannot see a path to solve it. My attempt was to use contradiction but I don't achive get something useful.
Any kind of help will be thankful.
Answer: Suppose that the implication is false. Then there exists $v\in V$ such that there exist distinct $w_1,w_2\in W$ and $k_1,k_2\in K$ such that $w_1+k_1=v$ and $w_2+k_2=v$. Then $W + K\setminus\{k_2\}=V$. This is a contradiction.
Comment: Thanks for your answer. How did you conclude $W+K\\{k_{2}\}=V?$
Comment: @Suiz346 two subsets add to $V$ if for any $v\in V$, I can find two elements, one each subset, which together make $V$. What I have shown is that it is possible to remove an element from $K$, and you can still add it to $W$ to get $V$. Anytime you have something like $u+k_2=x$, where $u\in W$ and $x\in V$, you also have $u+w_1-w_2+k_1=x$, so you don't need $k_2$.
Comment: I got it! Thanks @Alex S. :) Your answer is very clear!


Sessão AppSettings não é lida quando executada em Container Docker

Question: Referente a leitura do AppSettings pelo Docker-Compose.
Quando eu rodo através do docker-compose, eu não consigo carregar o appsettings do arquivo.

Por isso, somente quando executo pelo docker-compose ele não encontra a sessão AppSettings e recebo um object reference na linha 19.
Pude analisar que:

O arquivo está dentro do Container.

O Ambiente foi setado corretamente pelo docker-compose

Esse erro só acontece quando eu executo via command-line o docker-compose. Ou seja, iniciando a aplicação pelo visual studio, ele lê corretamente o appsettings.
Inclusive eu já até mesmo executei um publish e localmente startei com sucesso através da .dll publicada.

Configuração desejada no appsettings.Production.json (eu até coloquei em todos para ver se o problema era algo com environment, mas parece ser mesmo sobre a leitura da AppSettings no arquivo).
Comment: acesse o container e verifique os paths dos arquivos. Lembre-se que se estiver a usar containers linux, os paths são *case sensitive*, para evitar problemas pode usar tudo minúsculo. Coloque logs na app tbm para validar se carregou corretamente os arquivos
Comment: Eu copio tudo para uma pasta **/app**, o conteúdo dessa é o item 2 que marquei. Sobre ser case sensitive, eu tento ler a sessão **"AppSettings"** tal como está no arquivo, e o environment eu defino como **- ASPNETCORE_ENVIRONMENT=Production**, acho que são os pontos em que isso atrapalharia, não me vem outro em mente. O arquivo do compose está com formato LF.
Comment: Realmente, revi com cuidado e era uma chamada do appsettings. Pode publicar como resposta para caso alguém passe por isso.
Answer: Como dito pelo @Ricardo Pontual, o problema era mesmo pelo case sensitive (que é considerado no linux).
Revisei o todo o código e encontrei a diferença numa chamada do appsettings.
 var builder = new ConfigurationBuilder()
            .SetBasePath(hostEnvironment.ContentRootPath)
            .AddJsonFile(path: "appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile(path: $"appsettings.{hostEnvironment.EnvironmentName}.json", optional: true, reloadOnChange: true)
            .AddEnvironmentVariables();


How to use jquery accordian in side bar first

Question:
I am using facets search filter. I want to use accordion in facest search filter.
Comment: This question appears to be off-topic because it is about implementing a functionality, or a layout seen in a site, for which only a screenshot or a site URL is provided. Please see [Help Center](http://drupal.stackexchange.com/help/on-topic).
Comment: Could you please more specific on your problem. As it currently stands we will not be able to understand your problem.
Answer: As I understood you want to make it Collapsible.  If yes try below mentioned module
https://drupal.org/project/facetapi_collapsible
https://drupal.org/files/project-images/collapsible_facets_0.png
Comment: I do not want to use facetapi collapsible. i am using link with check box widget as accordion functionality.


Measure of dispersion over unordered set

Question: I'm looking for a measure of dispersion, such as standard deviation, that can be used when distributing to an unordered set.
Specifically: A bucket distribution assigns a non-negative value to each bucket in a finite set.  The sum of all assigned values is one.  (So far, it's like a probability distribution).  However: The buckets in the set can be distinguished but have no order.  It's this which makes it different than a probability distribution.
We can represent bucket distributions as lists of decreasing non-negative numbers that sum to 1.  Eg [1] or [1/2,1/2] or [1/3,1/3,1/6,1/6] or [1/2,1/4,1/8,1/16...].
I'd like to be able to measure how dispersed a particular bucket distribution is.  Intuitively, [1] has 0 dispersion, [9/10,1/10] has some, [9/10,1/20,1/20] has more, [1/3,1/3,1/6,1/6] has more, etc.  But I haven't been able to quantify this.
I've tried using standard deviation, variance, moment of inertia, etc.  But I can't find a good way to do this.  I can arbitrarily rank order the buckets, but this seems, well, arbitrary.

(I'm the original poster, but can't seem to comment any more)
Ray: Great work, thanks for sharing this original research.  If you can provide more info on how you developed it, it would be fascinating.
whuber: Do you still feel entropy is a better measure than $k'$? Why? Intuitively, $k'$ fits like a glove.
Just noticed: The Wikipedia entry http://en.wikipedia.org/wiki/Diversity_index gives both $k'$, entropy, and other measures of diversity.  But, alas, no comparison (what are fundamental assumptions of each, when is one better suited, etc.)
Comment: Look up "entropy."
Comment: @whuber, I'm familiar with entropy: sum of (prob * log of prob).  Can you elaborate a bit on how to apply it here?
Comment: You just gave the formula!  You *do* have a probability measure (that's what you mean by "bucket distribution"); what you don't have--and it's irrelevant to entropy anyway--is a *random variable.*
Comment: @whuber Wow, what you're writing seems very interesting - really making me want to know more.  But I'm afraid I'm unable to understand your comment entirely.  I understand that I have a prob. measure.  I don't think I have a prob. distribution.  Hmmm... your comments are intriguing, if you'd elaborate more I'd be grateful.
Comment: Based on [a search](http://stats.stackexchange.com/search?page=2&tab=relevance&q=random%20variable%20probability%20distribution%20measure%20space), I suggest you start with http://stats.stackexchange.com/questions/10789 and http://stats.stackexchange.com/questions/30999. A *random variable* is a real-valued function $X$ on your "buckets" (which are more often modeled as tickets in a box or balls in an urn). The *distribution* of $X$ is given by the function $F_X(x)$ = $\Pr(X \le x)$, which is computed by adding the probabilities of all "buckets" where $X$ has a value of $x$ or less.
Comment: Re the edit: All these measures "fit" in the sense that they quantify variation in the probabilities. Choosing one well must depend on the *purpose* of the quantification: what decisions will you support with it?  What will you be comparing?  What inferences will you make?
Answer: $k' = 1 / \sum{p^2}$ is the "effective" number of buckets over which the distribution is uniform. $1 \le k' \le k =$ the # of buckets.

Edit

Thanks for adding the markup. Also, I'm new to this site, and I don't know how to reply to a comment, as opposed to replying to a post.

I developed k' myself, sometime in the 1970's, in response to a student's request for a way of measuring the variability across categories of admission diagnoses to a mental hospital, the question being whether there was more variability at certain times than at others. Recently, I discovered that it had previously been proposed by E.H. Simpson in a short article: Measurement of Diversity, Nature, 163 (1949), 688.

k' is not restricted to uniform distributions. Calling it the effective number of categories over which the distribution is uniformly distributed is just a way of establishing the scale it's on. It's analogous to the df in repeated measures anova after correcting for non-sphericity, with the normalized eigenvalues of the covariance matrix replacing the p's.
Comment: Also: Where did you get the idea from? Is this formula used elsewhere?
Comment: Thanks Ray.  (I added the markup to your post, but someone needs to approve it...)  I see how if the distribution is uniform, $k'$ is the number of buckets.  But can you justify why $k'$ makes sense when the distribution isn't uniform?
Comment: +1 Thank you for responding to the comments Ray, and welcome to our site! I have incorporated your separate answer as edits to this one. In general, consider editing your work when you wish to improve it and use the associated comments for material that might not properly be part of your answer. This provides a relatively clean separation between your work product and the commentary that may be associated with its development. The separation is important because the site treats answers differently than comments (in terms of searchability and so on).
Comment: This is also the inverse of the Herfindahl-Hirschman Index, which is a measure of competitiveness of an industry.


Secure copying (file transfer) between two Linux servers in the same datacenter (Linode)

Question: I have two Linodes in the same data center. I want to copy files from one to the other each night or on demand (for about the next month, until this project is finished). So I'm thinking about using rsync.
My question is how do I set up the two Linode servers to communicate via private IP addresses securely? Both servers are SSH hardened, they use denyhosts and have a fairly restrictive iptables setup.
I know I need to first assign private IP addresses to each server, then configure static networking according to this guide.
What is next? What SSH or iptables settings are needed to allow these two servers to communicate?
What further info do I need to supply in this question? I'm looking for a basic step-by-step guide for how to do this.
Comment: If you can access the hosts through ssh then that's all you need to copy files (use scp). Although I am not sure what _ssh hardened_ means.
Comment: This is a very basic discussion of ssh hardening: http://askubuntu.com/questions/2271/how-to-harden-an-ssh-server. I could post my sshd_config (redacted) if needed. I plan to use rsync, not scp, but the same considerations apply.
Comment: As mentioned by @drcelus the only thing now left is to copy/transfer the files using rsync(which internally uses scp by default). Further, you could also configure SSH public key authentication for transferring the files without the SSH daemon prompting for a password. This will also help you to automate the transfer using cronjob. You can see the following guide for the same [SSH Public Key Authentication](http://www.cyberciti.biz/tips/ssh-public-key-based-authentication-how-to.html)
Answer: As you are using Linux you have all the tools you need. Just use rsync over ssh
rsync -avz -e ssh user@remotehost:/remote/dir /this/dir/

No need for private IPs etc as this encrypts your traffic end to end.
Comment: One advantage with using private IPs in linode is that you don't pay for bandwidth on their private network.
Comment: @ErikA - yes, that's why I'm using private IPs -- free bandwidth.
Answer: As mentioned in a comment by ErikA, one advantage with using private IPs in Linode is that you don't pay for bandwidth on their private network. And the whole point of my question was to ask how to do this with private IP's. So I'm answering my own question with the solution I ended up using.

What SSH or iptables settings are needed to allow these two servers to communicate?

No changes were needed. Iain was right. The communication is still via the same port, and that port was already open in iptables. Even though this server is "SSH hardened", no changes where needed when using the private IPs instead of the public IPs.
As stated in my original question, I did plan to use rsync -- and that ended up being the final solution. But the use of a custom port and keyfile required quoting the ssh piece of the command as shown here:
rsync -av -e "ssh -p 222 -i /home/user/.ssh/id222_rsa" /this/dir/ --delete-excluded --exclude-from=my_exclude_list.txt email@example.com:/remote/dir

Figuring out the need for quotes and what part was inside the quotes was about the only minor challenge to the whole thing. It ended up being easier than I thought.
Answer: Unless Linode can provision you a private VLAN, using internal IPs won't make it any more secure.
Your easiest solution would be to set up a simple OpenVPN tunnel between the two machines, then send your rsync traffic over that. You could even use a weak cipher like arcfour with rsync to speed things up, as the encryption will be handled by he VPN tunnel itself.
There are lot ans lots of very simple guides out there for OpenVPN using x509 certificates for auth and on Linux, you can have it set up in minutes.
Here is a simple guide http://www.smallnetbuilder.com/security/security-howto/30353-how-to-set-up-a-site-to-site-vpn-with-openvpn


reason to change elliptic curves to normal form

Question: I would like to know about the concept of why we change the curve into Weierstrass normal form.
I mean for a specific example, if we have $x^3 +7y^3 + 64z^3=0$ and I went through all the steps and I changed it to $y^2= x^3 +ax^2 +bx + c$ .
I did this and I got very huge number like in trillions for $a, b, c$.
so we have $P$($2,2,-1$) belong to our first curve, what is this point considered w.r.t. the normal form?
I understood the process but I don't know why we do that and how can we find the rational points.
Thanks for your help in advance.
Comment: If the elliptic curve is in the form $y^2=x^3+ax+b$, then one can apply
https://en.wikipedia.org/wiki/Elliptic_curve#The_group_law to generate other rational point from existing one(s).
Comment: @Sahar Monlite - Another reason to use this construction is that when you describe your curve in terms of the "Weierstrass normal form" and the embedding into $\mathbb{P}^2$, a consequence is that you may parametrize "all elliptic curves".
Answer: First of all, ultimately you need to deal with such curves without using explicit equations. The higher-dimensional analogues of elliptic curves (called abelian varieties) do not easily submit to equation-theoretic reasoning.
Even for elliptic curves, the group law is best thought of geometrically, not in terms of equations for the curve.
If we do use equations, a reason for working with Weierstrass equations is related to the definition of an elliptic curve over a field: it is not just given by a smooth cubic, but also must have a point defined over the field. A famous example of your type of cubic that has rational coefficients but no point with rational coordinates is $3x^3 + 4y^3 + 5z^3 = 0$ (viewed in $\mathbf P^2$, so $[0:0:0]$ does not count). The projective curve defined by this equation (in algebraic geometry) is smooth of genus 1 but it is not an elliptic curve over $\mathbf Q$.
Every curve over a field defined by a Weierstrass equation has a rational point over that field: $[0:1:0]$. This point is also rather special geometrically among all points on a curve defined by a Weierstrass equation: the tangent line to the curve at that point is the line at infinity $Z = 0$ and this tangent line meets the curve at $[0:1:0]$ with multiplicity 3 (it is called a flex point), not just multiplicity at least 2. This can help you figure out how to find the Weierstrass equation for an elliptic curve given by a different equation: make a change of coordinates to move the flex point to $[0:1:0]$ so that the tangent line to the curve at the flex point turns into $Z = 0$.
Answer: You asked about

I would like to know about the concept of why we change the curve into Weierstrass normal form.

One reason might be that the curves entered into the
LMFDB
are given in terms of the Weierstrass normal form.
However, depending on context, you don't have to change to the
Weierstrass normal form. It is one of a few standard forms of
elliptic curve equations.
For example,
$\,y^2 + a_1 xy + a_3 y = x^3 + a_2 x^2 + a_4 x + a_6,\,$
is a popular one for number theory. The original Weierstrass equation $\,y^2 = 4x^3 - g_2x - g_3\,$ has
Weierstrass elliptic function solutions. Some other forms include Edwards curve,
Montgomery curve, Mordell curve, and Hessian curve.
Some integer points on your homogeneous curve
$\,C\!: 0 = x^3 +7y^3 + 64z^3\,$ are:
$$\,(2,2,-1),\,(4,0,-1),\,(5,-3,1),\,(8,-4,-1),\,(16,-12,5),\,(68,152,-73)$$
and infinitely many others. You can use a standard method to find
more points. For example, if $\,P\,$ and $\,Q\,$ are two
points on the curve $\,C$, then let $\,R := a P+b Q\,$
where $\,ab\ne 0\,$ and solve the equation
$\,0 = x^3 +7y^3 + 64z^3\,$ to find a new point.
For example, let $\,P := (2,2,-1),\,$ $Q := (4,0,-1).\,$
Then  $$R := a P+b Q = (2a+4b, 2a, -a-b).$$ The cubic equation
applied to $\,R\,$ becomes
$$0 = (2a+4b)^3 + 7(2a)^3 + 64(-a-b)^3 = -48ab(3a + 2b). $$
The nonzero solution is $\,a=-2,\, b=3,\, R=(8,-4,-1).\,$
The elliptic curve group law is given by any line
that intersects the curve at three points which are
now considered to have a group sum of zero.
The point $\,R_0 := (4,0,-1)\,$ is the group identity and
the point $\,R_1 := (2,2,-1)\,$ is a group generator. Now,
find that $\,R_{-1} := (8,-4,-1)\,$ is the additive inverse
of $\,R_1\,$ because $\,R_{-1} = 3 R_0 - 2 R_1\,$
is a solution of the cubic equation.
The line  $\,0 = x + 7y + 16z\,$ is tangent to $\,C\,$ at
$\,R_1\,$ and it intersects $\,C\,$ at $\,R_{-2} := (5,-3,1).\,$
Now $\,R_2 := (16,-12,5)\,$ is the additive inverse of
$\,R_{-2}\,$ because $\,R_2 = -R_0 + 4R_{-2}.\,$
Continue this chord and tangent
process to find any integer multiple $\,R_n\,$ of the point $\,R_1\,$ on the curve $\,C.$

However, it is possible to change your curve to Weierstrass
normal form with a few simple replacement steps.
The original curve is
$$ 0 = x^3 +7 y^3 +64 z^3. \tag1 $$
Scale the variables with the replacements
$(x\to x,\,y\to -z,\,z\to y/4)$ to get
$$ 0 = x^3 +y^3 -7 z^3. \tag2 $$
This curve appears in the solution to MSE question 4298049.
Apply the replacements $(x\to z-y,\,y\to z+y,\,z\to x)$ to get
$$ 0 = -6 y^2 z +7 x^3 - 2 z^3. \tag3 $$
This kind of step appears in the solution to MO question 145877 by Noam Elkies.
Scale the variables again with the replacements
$(x\to 6x,\,y\to y,\,z\to 252z)$ and remove a common factor of
$1512$ to get
$$ 0 = -y^2 z +x^3 -21168 z^3. \tag4 $$
This is the homogeneous equation of a elliptic curve.
Dehomogenize by setting $z=1$ to get
$$ y^2 = x^3 -21168. \tag5 $$
which is in Weierstrass normal form, However, it is not listed
in the LMFDB in this form. Now use the replacements
$(x\to 4x,\,y\to 8y+4z,\,z\to z)$ and remove a common factor
of $64$ to get
$$ 0 = -y^2 z -y z^2 +x^3 -331 z^3. \tag6 $$
Dehomogenize by setting $z=1$ to get
$$ y^2 +y = x^3 -331. \tag7 $$
This is the curve
LMFDB 441.d1.
The LMFDB gives the infinite order generator $P=(21,94).$
To conversion of points on this curve $(7)$ to the original curve
is given by the mapping
$$ (x,y)\mapsto(-8(y-31), -24 x, 2 (y+32)). \tag8 $$
For example, the generator $P$ is mapped to $(-504,-504,252)$
which is projectively equivalent to $(2,2,-1).$ Another example,
the double of the generator $2P=(7,3)$ is mapped to $(224,-168,70)$
which is projectively equivalent to $(16,-12,5).$
Comment: Thanks , but may I know how did you get these points?


Proof that $\textit{INFINITE}_{\text{DFA}}$ is decidable.(Sipser Q.4.10)

Question: The answer of the question is given below:

But I could not understand the intuition behind 2 and 3 in the description of the machine below, could anyone explain this for me please?
Answer: For a DFA $D$ with $k$ states, we have that $L(D)$ is infinite if and only if $D$ accepts some string $\omega$ of length $k \leq |\omega| \leq 2k-1$. So to test if $L(D)$ is infinite, we enumerate all strings with length between $k$ and $2k-1$. If $D$ accepts one of these strings, $L(D)$ is infinite. Otherwise, $L(D)$ is finite. The idea, as described in the answer you provided, is that a string with length between $k$ and $2k-1$ can be pumped up repeatedly, to generate infinitely many strings. So we can equivocally test if the DFA $D$ accepts any string of length at least $k$. This is what the answer is doing.
In particular, steps (2) and (3) are used to test if the DFA $A$ accepts any string of length at least $k$.
Comment: why $|w| \leq 2k -1$?
Answer: The intuition is to test if $A$ accepts any word of length greater than the number of its states.
Comment: why we do this ?
Comment: @Idonotknow it is explained in the passage under the algorithm in your post. It is a necessary and sufficient condition for L(A) to be infinite.
Answer: $D$ accepts any string with at least $k$ symbols. So $M$ recognises those strings from $A$ which have more than $k$ symbols. It's obvious that $D$ can be constructed, and there is a simple way ti construct a DFA which recognizes the intersection of the languages of two DFAs: intuitively, run both DFAs simultaneously and accept if both end the scan in an accepting state.
So we know that $M$ can be constructed. And we have an algorithm which can determine whether it is empty. If it is not empty, it contains at least one string with more than $k$ symbols, which must also be a member of $L(A)$, because all its strings have more than $k$ symbols and all its strings are in $L(A)$.
Finally, a DFA with $k$ states which recognises a string with more than $k$ symbols must recognise an infinite number of strings.


Visualize data in Power Bi as Matrix

Question: I have the following data:

With the matrix diagram I was able to visualize it like that:

But I want to visualize this data:

How can I get the two columns Diff and Diff%?
Answer: I'd create four measures to get the visualization you need. A measure called 2010 Value will calculate the 2010 sum of values; 2011 Value measure will calculate the 2011 sum of values. Diff(2011-2010) calculates the difference between 2011 and 2011 values, and Diff % calculates the porcentual difference between 2011 and 2010.
Use these DAX expressions to create the measures.
2010 Value = CALCULATE ( SUM ( [Value] ), YEAR ( 'Table'[Date] ) = 2010 )

2011 Value = CALCULATE ( SUM ( [Value] ), YEAR ( 'Table'[Date] ) = 2011 )
Diff(2011-2010) = ABS ( [2011 Value] - [2010 Value] )
Diff % = [Diff(2011-2010)]/[2010 Value]
Now you can add every measure to the Values pane in Power BI and it should provide the visualization you expect.

Note this is a static solution so if you have years different to 2010 and 2011 you have to create it manually. If you require dinamically calculate differences and other measures from the last two years in your data you have to play around with some time functions.
Let me know if this helps.
Comment: thank you so much. It works. I think I don't have a deep understanding about measures. Do you have a good reference about it?

Visualize data in Power Bi as Matrix


Why are there 8/4 notes in a 4/4 time signature?

Question:
I fought also link so you can see in proper quality
This is the sheet! I posted above photo of first page only
https://musescore.com/user/24625996/scores/4544086
The time signature is 4/4, but if I sum up the total of notes + rests in the first measure it is 8/4
I understand it is like a triplet kind of (don't know the exact term)
I get it that 1/8th rest + 1/4 note + 1/8 note should be played in 1/4 time but why? There is no notation there.
Also the last line has a number six grouping a couple of 1/32 notes
Please refer me to the theory part of this and explain more.
I can play first line fine, second line I do not know when to match right and left hand exactly due to complicated time
Comment: We get questions like this ("Why can't I read this notation in this sheet music I bought online?") not infrequently on this Stack, and quite often the answer is "It's not your fault, the notation is crap."  Someone should start a page to collect them.
Comment: @KristiJorgji if you can rate it, just give it 0 stars, and if you can comment, just add the link to this post.
Comment: I really don't get why so many people insist on sharing their **ugly** transcriptions when they are clearly not able to write proper scores. Do they even try to read what they "publish"?
Comment: The lesson here is you can't trust community scores on Musescore's platform. The people who create them might be geniuses or they might have many gaps in their knowledge of notation. This is definitely an example of the latter. So many things are wrong on just that one page.
Comment: @KristiJorgji:
Where did you buy it from for 5$? I don't think Musescore even lets you do that.
I do have a "pro" account (or whatever they call it nowadays), and don't really keep track of the policy changes, but I've never heard that they were **selling** scores.
Comment: @musicamante I also do not even know... Figure out this was 5 start rated in musescore and I bought it around 5$
Comment: This is the sheet, now has 4.8 rating (bought before 1 month) https://musescore.com/user/24625996/scores/4544086
Comment: And it's even been _copyrighted_!
Comment: @MichaelSeifert we should, yes. I bet we could find so many of them that we could even do a daily wall-of-shame blog and go on for over an year with 5 posts per week.
Answer: The notation is unhelpful. In the first bar of the piece there are two voices; Voice 1 plays four quarter notes, Voice 2 plays a pattern consisting of 4 x {eighth note rest then eighth-note}.
The reason it's confusing to read is that both voices are stems up - usual (helpful!) convention is to have voice 1 and voice 2 with stems going in opposite directions to make the distinction between the two voices really clear.
If you look carefully at bar 5 onwards you'll see it's still two voices, like the opening of the piece, but all the voices are notated stems up, which obscures the fact that there are two-voices.
The original track is here Archangel and it looks as though the transcriber should have written eight quavers in the first bar and used tenuto accents over the first quaver of each quaver pair. It's definitely in 4/4 time, not 12/8
Comment: Three voices if you count the whole notes.  Might've been clearer to move these to the lower staff.  (Making the quarter-note stems go down would also help, but would interfere with those whole notes, hence another reason to move them to the lower staff.  Maybe with a bracket below them to indicate that they should still be played with the right hand...)
Comment: @KristiJorgji There isn't really much "theory" to voices.  It's essentially a duette, but both parts have been mashed together onto one grand staff, without indicating which part is which.  Ideally you need four hands to play it properly!
Comment: Thanks! I was playing first line like this  1/8th rest + 1/4 note + 1/8 note in a 1/4 time. Please refer me more to voices theory, how can I know what to play exactly with right hand then and left one (especially in 2nd line and below). I am currently playing 2nd line and below with gut feeling, sounds good but crazy hard... Would love to know the theory and be able understand what is meant with this how to play it properly
Comment: I think I understand now that for example line 2 left hand can either play 2 x 2/4 notes or the other voice 1/8 rest +  2x 1/16 + 2 x 1/4 notes. So my question is here, which voice should I play ? What does it mean exactly 2 voices (I am totally begginer to theory). Does it mean this can be played by 2 pianos at same time ? I cannot play both voices at once with left hand in this example .. right ? I was kind of playing struggling to play 2/4 note then jump hand play the rest after the 1/8 pause with pedal pressed and so on
Comment: I think you'd need to go through this beat-by-beat and decide whether each note is voice 1 or voice 2. Or you could find the original music (not someone's "transcription").
Answer: Unclear and not proper notation. I agree with Brian Thomas.
In bar 5 you can see that the fourth notes correspond exactly with the half notes (1st and 3rd  beat) and the eighth rests and eighth notes in the r.h. fit exactly with the eighth and sixteenth in the l.h. So the key of the true interpretation of this horrible notation is to find in measure 5 (rhythmically and arithmetically).
Comment: Here is free to read the piece https://musescore.com/user/24625996/scores/4544086 How can I play measure 48 (page 4) especially left hand ? Are there 2 voices in the left hand ? I am kind of trying to play all of them lol in left hand which doubles the tempo makes it crazy hard get all notes there..


Paginated jQuery Result Set from XML File Problem

Question: I am having a spot of bother with a code I am developing to show 10 Magazines at a time that is being fed from an xml file. I have it working to some extent, FF and IE7+8 do not like it, maybe as it says there is an error on line 62 - being the core function calling the data to be fed in.
Here is my code:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="robots" content="noindex, nofollow" />
<title>Brave Creative - Online Archive</title>
<link rel="stylesheet" href="css/global.css" media="screen" />

Online Archive: FSM

     Previous
        Next

     t. 01733 392978 m. 07719442825

  e. firstname.lastname@example.com

        4 Milnyard Square, Orton Southgate, Peterborough PE2 6CX

The previous and next buttons do not work correctly, for instance I click next and I go to page 2, click next again - its blank, and click one last time I get told I have no more results to view. But if i click previous to start of with and go back 3 times (to the start again) then click next I can cycle back up to the same issue, this has really baffled me, any help would be deeply appreciated!
Answer: Just reading your code I have a few remarks.
This:
$('span.issuecount').html(+totalIssues+' Issues - '+numPages+' Pages');

Should be without the '+' before 'totalIssues', or am I missing something?
$('span.issuecount').html(totalIssues+' Issues - '+numPages+' Pages');

The end of
$('

').html('
'+date+' - #'+issue+'').fadeIn(500).appendTo(shelf);

seems to do things in the wrong order, isn't it? First fade and then appendTo?
This
$('#prevIssueButton').click(function() {
                if( startIndex < howMany) {
                    startIndex -= howMany;
                    displayIssues();

looks strange too, if startIndex indeed is less than howMany, then the startIndex will be negative after this call, is that intended?
Then I'm not sure it's a good idea to have all the code in the success event handler for the Ajax call. I would have separated these thing somewhat, but maybe you have tried that and decided on this. It's just a thought.


Como pegar a data atual menos dois anos no mysql?

Question: Preciso mostrar em uma consulta alguns itens entre a data  atual do tempo em questão e dois anos antes.
Answer: Utilize o BETWEEN com date_sub para subtrair um intervalo da data informada:
SELECT * FROM table WHERE data BETWEEN NOW() AND DATE_SUB(NOW(), INTERVAL 2 YEAR);


Use energy method prove wave equation has a unique of solution.

Question: Problem:  Use energy method to prove that the wave equation has a unique of solution.
$\begin{align}U_{tt}+U_t-C^2U_{xx}=0 \\ U(a,t)=U(b,t)=0 \\ U(x,0)=f(x) \\ U_t(x,0)=g(x) \end{align} \quad \text{with} \quad a\le x\le b ,t\ge 0.$
I try assume problem has two solution $U_1\neq U_2$ and set $W=U_1-U_2$,
define $\displaystyle E(t)=\dfrac{1}{2}\int\limits_{a}^{b} \left((W_t)^2+c^2(W_x)^2\right)dx$.
I can't prove $(E't)=0$ .
Answer: I think you need a $+$ in your energy rather than a minus, to account for an integration by parts.
As you said, suppose $U_1$ and $U_2$ are two solutions and take the difference $w = U_1 - U_2$.  Then $w$ solves a very similar problem
$$w_{tt} + w_t - c^2w_{xx} = 0$$
$$w(a,t) = w(b,t)=0$$
$$w(x,0) = 0$$
$$w_t(x,0) = 0$$
Notice that as a consequence of the boundary conditions $w_t(a,t) = 0$ and $w_t(b,t) = 0$, since $w(a, \cdot)$ (resp. $b$) is always $0$.  Notice also for my suggested energy $E(t) = \int_a^b (w_t)^2 + c^2(w_x)^2 \, dx$, if $E(t) = 0$ for all $t$ then $w_t =0$ for all $t$, thus $w(x, \cdot)$ is constant and $w(x,0)=0$, therefore $w = 0$.
Differentiate $E$,
$$E'(t) = \frac{1}{2}\int_a^b \left( 2 w_t w_{tt} + 2 c^2 w_x w_{x,t} \right) \, dx$$
We would like to use the equation $w$ satisfies to make this $0$ or $\leq 0$.  The obstacles are that the $x$-derivative terms are not quite right, and the absence of an "independent" $w_t$ term.
Integrate $\int w_x w_{x,t} \, dx$ by parts, using the fact that $w_t(a,t)=w_t(b,t)=0$ to dispose of the boundary terms leaving only $-\int w_{xx} w_t \, dx$.  This places us at
$$E'(t) = \int_a^b w_{tt} w_t - c^2 w_{xx} w_t \, dx$$
Add and subtract $(w_t)^2$ inside the integral,
$$E'(t) = \int_a^b (w_{tt} w_t + w_t w_t - c^2 w_{xx} w_t) - (w_t)^2 \, dx$$
Using $w_{tt} + w_t - c^2 w_{xx} = 0$, this ends up at $E'(t) = \int_a^b - (w_t)^2 \, dx$, which is a negative quantity.  Therefore $E$ is decreasing. Also Observe that $E(0) = 0$ and $E(t) \geq 0$ to conclude that $E(t)$ is constantly $0$.
Comment: To differentiate $E$, we need to use Lebesgue's Dominated Convergence theorem. Right?


How to analyze ordered data type with past missing observations?

Question: I am having trouble understanding what method to apply for the analysis of the following type of data:
<code>id  period  grade   GLP NAB ROE ROA OSS ESS PMA P30
1   1   NA  1790835 769 0.3795033   0.1171393   1.66014 1.221868    0.3976413   0.007312334
1   2   NA  2597351 1143    0.5896583   0.188034    1.947474    1.748581    0.4865142   0.01906484
1   3   15  3359203 1343    0.474556    0.1559151   1.814949    1.712795    0.4490202   0.02821528
2   3   16  12271110    15960   0.05    0.01    1.04    1.04    0.04    0.02
2   1   NA  5392109 9290    -0.02   -0.01   0.96    0.7 -0.04   0.02
2   2   NA  11128069    1253    -0.03332067 -0.005665337    0.9908606   0.9871047   -0.00922374 0.01818852
3   2   NA  820903  2225    0.06835087  0.004860066 1.012239    0.9919102   0.01209093  0.072
...
9   2   NA  652028  364 0.027   0.007   1.027   0.982   0.026   0.008
10  2   NA  31731236    251352  0.07033455  0.01930156  1.11506 1.069495    0.1031871   0.01566419
10  3   20  33016098    247747  0.0750367   0.02032998  1.124112    1.086046    0.1104093   0.01443777
10  1   NA  25151189    217818  0.03529102  0.01133722  1.059813    1.052836    0.0564377   0.02853068
</code>
They refer to credit ratings computed over three periods. The dependent variable is the grade (therefore ordered) and it does also depend on periods 1 and 2, but it not assigned until period 3, and therefore is missing. I thought to use ordered GEEs with a logit link, but in that case I would have either to put in the grade vector 0 or the period 3 values for each subject to analyze everything. Do you have any idea how to maintain the past observation without 'falsifying' the data? Help would be much appreciated!
Answer: After consulting a statistics professor specialized in GLMs, I realized this is not a longitudinal set with respect to the ordered value (because grades are assigned only in period 3) but a cross-section with lags, so a proportional odds logistic regression will make it.


User profiles for ESXi

Question: I have configured active directory with my ESXi Server and all is great. I created User Profiles for this experiment within Windows 2008r2. Logged in with a windows 7 VM within Vsphere, and all works.
My suspicions solely believe that Vsphere is just a management console for the ESXi Server. Or am I wrong? However I really am interested to know some peoples opinions please?

Upon logging in with x,y,z user they all can see every single VM that is running/shutdown etc. Is there a possible way to separate users so when they log into Vsphere they can only see the VM's they have created, and not have access to the any other users VM's.
If Vsphere is JUST a management console, what solution can anyone suggest that will help me achieve my goal?
Comment: What is your goal exactly?
Answer: First off, please read the VMware docs available here and here. Your question clearly shows that you didn't read it at all.
vCenter is how you manage ESXi Servers professionally in a multi-ESXi-host environment, it provides lots of features like host profiles, VM and Host Management via a web client, powerful scripting API, inventory etc.
On to your question:
Beside other options like centalized users/groups via Active Directory or LDAP, the box you installed vCenter on may be used as a user account store for vCenter. Roles and permissions are managed inside the application though.
This means that you have to log on to vCenter via Webclient or the vSphere client and create roles, assign them permissions and then assign those roles (or the predefined ones) to entities within the vCenter inventory (folders, clusters, hosts, VMs, datastores, etc.)
For details, see the VMware docs here: https://pubs.vmware.com/vsphere-55/topic/com.vmware.vsphere.security.doc/GUID-93B962A7-93FA-4E96-B68F-AE66D3D6C663.html?resultof="roles"%20"role"%20
Comment: Thanks for the constructive criticism!! :) I have learnt AD how to connect ESXi and authenticate users with it within 4 days! Give me some slack please! What I have know found the answer is yes I can basically! Just been looking at the permissions what I want to achieve.

User profiles for ESXi


How do I export Entityform submissions to CSV?

Question: I see that it is possible to bulk download Entityform submissions to a CSV file.
How do I do it? I don't see a "Download as CSV" button anywhere.
Answer: My problem was that I installed Views Data Export after installing Entityforms.
I had to go to the Entityforms view (which is the automatically generated admin view showing the form's submissions), click the arrow next to "Edit View Name/Description" and click "Revert View".
Now a CSV/XML export button shows up on the Submissions view, and I can export happily.


Induction Proof Clarification

Question:
$T= \{3^0, \ldots, 3^{k-1}\}, t>0$. We know that $T \in P(T)$ and for any $A \in P(T), A \subseteq T$ and further for any $B \in P(A) \subset P(T)$ which implies $B \subset T$.
So if we consider $A=T$ and $B=T$, we will get the maximum of $S$.
So the maximum is $$\sum_{a \in T}a + \sum_{b \in T}b =2\left(\sum_{k=0}^{t-1} 3^k \right) = \left(\sum_{k=0}^{t-1} 2\cdot 3^k \right)$$
I think that I solved part a) of this problem correctly, it seems straightforward by logic, but I don't know how to prove it.
Comment: Welcome to MSE! It would be helpful if you typed up both the problem and the solution using MathJax.
Comment: here is a [mathjax](https://math.meta.stackexchange.com/q/5020/306553) guide, try to type your question in mathjax, it doesn't have to be perfect but just try your best, your post will be edited by others to improved. For a start, just surround mathy object with the dollar sign.
Answer: All the elements of $T$ are positive, hence we should include all of them.
Note that you can further simplify
$$2\sum_{k=0}^{t-1} 3^k =2\cdot \frac{3^t-1}{2}=3^t-1$$
We have illustrated that we can attain this number. Furthermore, we can't attain a larger number than $3^t-1$ since we have used up all the positive numbers that we can sum. Hence, this is the maximum value that we can attain.

If you insist to write an induction:
I will leave the base case to you.
Suppose $T_k = \{ 3^i: i \in \{1, \ldots, k-1\}\}$ and we define $S_k$ accordingly and we have $\max (S_k)=3^k-1$.
Now consider the set $T_{k+1}$ and we defined $S_{k+1}$ accordingly.
Note that we have $T_{k+1}=T_k \cup \{3^k\}$ and consider the $A_{k+1}$ and $B_{k+1}$ that corresponds that attains $\max(S_{k+1})$. Suppose $3^k \notin A_{k+1}$ or $3^{k} \notin B_{k+1}$, then we have
$$\sum_{a \in A_{k+1}\cup \{3^k\}} a + \sum_{b \in A_{k+1}\cup \{3^k\}} b \ge  \max(S_{k+1}) + 3^k > \max(S_{k+1})$$ which is a contradiction. Hence we must have $3^k \in A_{k+1}$ and $3^k \in B_{k+1}$.
We have
$$\sum_{a \in A_{k+1}} a + \sum_{b \in B_{k+1}} b= \max(S_{k+1})$$
$$\sum_{a \in A_{k+1}\setminus \{3^k\}} a + \sum_{b \in B_{k+1} \setminus \{3^k\}} b= \max(S_{k+1})-2\cdot 3^k$$
Since $A_{k+1}\setminus \{3^k\}$ and $B_{k+1}\setminus \{3^k\}$ are subsets of $T_k$,
We have $$\max(S_{k+1})-2\cdot 3^k \le \max(S_k)=3^k-1$$
$$\max(S_{k+1}) \le 3^{k+1}-1$$
Hence $3^{k+1}-1$ is an upperbound and we just have to illustrate that we can attain it, i.e. by summing up every element.

Induction Proof Clarification


how to do filters in vue.js

Question: i am new to vue.js.so i want  to apply a filter thing in my project.i tried to do this from past 2 to 3 days..but i couldn't..can any one help me how to do this..
I have 3 input boxes one is experience,expected_ctc,and profile_role depending on these 3 i want to display the results..
Here is my js page:
const app = new Vue({
  el: '#app',
  data() {
    return {
      page: 0,
      itemsPerPage: 3,
    }
 },
 components: { Candidate },
  methods: {
  //custom method bound to page buttons
  setPage(page) {
    this.page = page-1;
    this.paginedCandidates = this.paginate()
  },
  paginate() {
    return this.filteredCandidates.slice(this.page * this.itemsPerPage, this.page * this.itemsPerPage + this.itemsPerPage)
  },
 },

 computed: {
  //compute number of pages, we always round up (ceil)
  numPages() {
    console.log(this.filteredCandidates)
    return Math.ceil(this.filteredCandidates.length/this.itemsPerPage);
  },
  filteredCandidates() {
    //filter out all candidates that have experience less than 10
    const filtered = window.data.candidates.filter((candidate) => {
      if(candidate.experience === 5) {
        return false;
      }

      return true;
    })
    console.log(filtered);
    return filtered;
  },
  paginedCandidates() {
    return this.paginate()
  }
 }
});

here is my buttons from view page:

Experience:<input type="text" v-model="experience" placeholder="enter experience">

Expected CTC:<input type="text" v-model="expected_ctc" placeholder="enter expected ctc">

Profile Role:<input type="text" v-model="profile_role_id" placeholder="enter role">

<input type="button" name="search" value="search" >

Can anyone help me..
Thanks in advance..
Comment: Quite a lot of questions: What does the Candidate component look like. Where do you use it? Where are the data definitions for the shown v-model bindings? Why is data bound to the window?!? If you want to use vue filtering this seems a little weird.
Comment: actually i don't know how to use v-model in the vue.js page fro the filter.....i just created..v-model in the input box..
Comment: i will edit my question..there u can see..how my candidate component look like..
Comment: where does your data come from? where do you load it? why is it on the window property? And maybe even more relevant: Where do you even use the candidate component?
Comment: it is coming from the vue page..i import candidate.vue in my js page import Candidate from './components/Candidate.vue';
Comment: what vue page? I only see that you have a setPage which again takes data from the window - why don't you put the data directly into your component or app ?
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/144223/discussion-between-frank-provost-and-bharathi).
Answer: Ok let's start with a smaller example. Lets say you have "Candidates" one one candidate might look like
{
  name: 'John Doe',
  expected_ctc: 'A',
  experience: 'B',
  profile_role_id: 1
}

From your current state I'd say you have all candidates in an array returned by laravel. Let's say we're in your current template where you have your vue app

   <input type="text" v-model="experienceSearch"/>

{{ result.name }}

And now to the script
// always init your v-model bound props in data
// usually you wouldn't take the candidates from the window prop. However, to keep it easy for you here I will stick to this
data: function() {
  return {
     experienceSearch: '',
     candidates: window.data.candidates
  }
},

// the list that is displayed can be defined as computed property. It will re-compute everytime your input changes
computed: {
  candidatelist: function() {
     // now define how your list is filtered
     return this.candidates.filter(function(oCandidate) {
        var matches = true;

        if (this.experienceSearch) {
           if (oCandidate.experience != this.experienceSearch) {
              matches = false;
           }
        }

        // here you can define conditions for your other matchers

        return matches;
     }.bind(this));
  }
}

General steps:

all candidates are in data -> candidates
relevant (filtered) candidates are represented by the computed prop candidatelist
inputs are bound with v-model to EXISTING data prop definitions

Fiddle https://jsfiddle.net/sLLk4u2a/
(Search is only exact and Case Sensitive)
Comment: And i have another doubt..if it is one condition it's working..how to apply for multiple conditions..
Comment: Define them at `// here you can define conditions for your other matchers` this is why I've used the matches variable. You can check each condition one by one here. Basically it is an AND condition. If you want and "or" condition just set matches to false on default and change it to true on match.
Comment: yup..it's working..thank you..thanks a lot..@Frank Provost
Comment: i want to give a button after 3 filters..then only i want to display the results..can you please explain me how to do that..
Comment: instead of putting the candidateList in a computed prop you can define a "candidateList" array in the data section and copy the function that is currently used in the computed prop as a method. Then you call the method as you press the button. Don't forget to change `return matches` in the bottom line to `this.candidateList = matches`
Comment: this is working fine..but when i apply this code...the results is showing in console..and not showing in view..and my pagination also not working..if it possible can you please tel me where i mistaken,,i will share my code..
Comment: you should open a new question for this.

how to do filters in vue.js


Java Convert Facebook created_time to UTC

Question: I am using Facebook graph API to retrieve user wall information. In that, I am getting the post created time value as:
created_time: "2012-04-19T09:00:02+0000"

Can anyone suggest me how to convert this time to UTC or epoch value in Java?
Answer: The format of date you receive is ISO 8601.
As described in Converting ISO8601-compliant String to java.util.Date (using Joda-Time):
DateTimeFormatter parser = ISODateTimeFormat.dateTimeNoMillis();
String jtdate = "2012-04-19T09:00:02+0000";
System.out.println(parser.parseDateTime(jtdate));

Comment: You may use `getMillis()` method on result of `parseDateTime()` to get the number of milliseconds from epoch.
Comment: Thanks for your reply. When I use the above DatatypeConverter, I receive an exception: java.lang.IllegalArgumentException: 2012-04-19T09:00:02+0000. Its state illegal argument type. Can you please suggest what I am doing wrong?
Comment: @Venkat, I've accidently provided wrong sample code. Corrected
Comment: Thank you. After parsing it prints 2012-04-19T14:30:02.000+05:30. I need the values in UTC format. How can I get it? Please correct me if I am wrong. Thanks again.
Comment: Thank you Juicy Scripter. You saved my time :)
Answer: You basically need to parse the ISO8601 date format. There are libraries out there that would do it for you or you can create your own parser (relatively simply), e.g.
http://www.java2s.com/Code/Java/Data-Type/ISO8601dateparsingutility.htm
Comment: Thank you scibuff. Let me also look in to this.