text:
Q: Display Handlebars.js context in a template Is there a variable passed into every handlebar.js template that contains all the context content that is accessible by the template?
e.g. I'm creating a template, but I don't know all the context content accessible by the template. I want to be able to type into the template {{ debug }} and handlebars.js will spit out all the context content into the HTML

A: You can use the following code to iterate through this object:
{{#each this}}
  {{@key}}: {{this}}
{{/each}}

or a similar piece of code iterating through @root object:
{{#each @root}}
  {{@key}}: {{this}}
{{/each}}

A: Handlebars has built-in helper log.
You just need to set logging level to DEBUG.
Handlebars.logger.level = 0;

Then use helper:
{{log this}}

EDIT: Sorry, this will not write context to HTML, helper uses console.log. For outputting to HTML you need to write custom helper that will use for example JSON.stringify.

A: Though this question is somewhat old, someone might find this usefull. You can just dump the handlebars current context into plain text with;
{{{.}}}


text:
Q: Jquery Form Validation - Required Field Error I struggle for long hours to display error messages under input fields in a form. What I  am trying to do is, show an error message when an input is left empty. I could find a sample on internet but I could not get it work as i want . I added an extra input field which has "sur_contact_name" id. But there is no error message regarding this input. It did not work out somehow. can anyone help me please to solve the issue. Here is the code exported to jsfiddle http://jsfiddle.net/allence/zK7pn/3/
HTML code for input fields:

            Name:
            <input type="text" id="contact_name" name="name"></input>
            This field is required

            Name:
            <input type="text" id="sur_contact_name" name="surname"></input>
            This field is required

Thankss..

A: You should have posted the complete code in your question.
The question will become meaningless if the jsfiddle link goes away.
Based on the code you have in jsfiddle you've got a couple of issues.
Quick fix:
Change

    Name:
    <input type="text" id="sur_contact_name" name="surname"></input>
    This field is required

to

   Name:
   <input type="text" id="contact_surname" name="surname"></input>
   This field is required

and eliminate the jquery code you added to validate surname

        $('#sur_contact_name').on('input', function() {
            var input=$(this);
            var sur_name=input.val();
            if(sur_name){input.removeClass("invalid").addClass("valid");}
            else{input.removeClass("valid").addClass("invalid");}
        });

    for (var input in form_data){
        var element=$("#contact_"+form_data[input]['name']);

because the name validation will handle it as well...

redpajama_set_name: RedPajamaStackExchange


text:
Q: Biconditional statements with an "easy" direction. I was reading through Lax's Functional Analysis, when I came across the following statement:

Theorem: X is a normed linear space over $\mathbb{R}$, $M$ a bounded subset of $X$. A point $z$ of $X$ belongs to the closed, convex hull $\breve{M}$ of $M$ iff for all $l$ in $X'$, $$l(z) \leq S_M(l).$$

I don't have a question about this theorem, but I would like to use it as an example. Its proof, like many "if and only if" proofs has one direction (the forward one in this case) which is fairly trivial and one that is difficult. This is reflected in the length of the two parts of Lax's proof. I'm sure there are much better examples than this.
After reading this theorem, I was reminded of a professor I had not too long ago who made a big deal about these asymmetrical proofs. I remember he asked us, "If two statements are equivalent, why shouldn't it be equally easy to prove one from the other?" He admitted he had no real answer, but suggested it had to do with human psychology. Other people I've spoken to have claimed that, to some great genius, both directions would be of equal difficulty.
My questions are these:

*

*Is this actually an interesting phenomenon?

*If it is, is there any way to state it less "softly?"

*Do you have any favorite examples of these theorems?

*Why is one direction easier in these cases?

Thanks and hope this isn't too vague.

A: I would not step to the esoteric or psychological level here. Let me introduce an easy example of two obviously equivalent statements: $\forall x Rx$ holds if and only if $(\exists x Px \lor \forall x\neg Px)\rightarrow \forall x Rx$, so
$$\forall x Rx \leftrightarrow((\exists x Px \lor \forall x\neg Px)\rightarrow \forall x Rx)$$
is a tautology. But see what happens if we prove the two directions in a sequent calculus:
Direction "$\rightarrow$"

Direction "$\leftarrow$"

The essence of the example: Just because two formulas $\varphi$ and $\psi$ are equivalent, this does not mean that the proofs of the logical true, but otherwise potentially substantially different formulas $\varphi\rightarrow\psi$ and $\psi\rightarrow\varphi$ are equally hard. In the example, we had to actually proof the premise $\exists x Px \lor \forall x\neg Px$ in the "$\leftarrow$" direction, while we could treat it in the "$\rightarrow$" direction as a blackbox.
Also: The logical equivalence of two formulas tells us nothing about the complexity of their respective proofs! This is no human psychology, just technical issues. And a genius would probably look at the formulas and state: "hey, but the second one will have a more complex proof" ;)
Remark: I you are not comfortable with the sequent calculus, regard it the following way: In the left-to-right direction, you can exploit the fact that $\varphi\rightarrow(\psi\rightarrow\varphi)$ is always true (propositional tautology), regardless of the truth of $\psi$. For $(\psi\rightarrow\varphi)\rightarrow\varphi$, you have to prove $\psi$ first, because only then this becomes logically true. All this is not effected by the fact that the formulas of the above example are equivalent, and both directions are therefore provable. Provability and complexity of proofs are two different things.
Edit: Now specifically addressing your questions -

*

*Is this actually an interesting phenomenon?

I'd vote for yes - but rather from the proof-theoretic "technical" point of view than from a philosophical one.

*If it is, is there any way to state it less "softly?"

Well, you could phrase it towards an investigation of the lengths of the shortest proofs (in a formal system) for the two directions of a bi-implication.

*Do you have any favorite examples of these theorems?

One of my favorites is the soundness and completeness of a formal proof system for first-order logic: A theorem is logically true if and only if it is provable in the system.

*Why is one direction easier in these cases?

The "$\leftarrow$" direction (soundness) is the easy one, you just have to do a structural induction over the calculus. The "$\rightarrow$" direction ((strong) completeness) is the complicated (and more interesting) one; interesting facts like the compactness theorem follow from the existence of such complete proof systems.

A: I think a lot of theorems could be stated in such a way as to fulfil the requirements, e.g., $x^n+y^n=z^n$ has a solution in positive integers if and only if $n\le2$; the Riemann zeta function has infinitely many zeros with real part $s$ if and only if $s=1/2$ (OK, the "only if" part may not be a theorem just yet); there is a sporadic simple group of order $n$ if and only if $n$ is in the following list [insert here list of orders of sporadic simple groups], and so on. Perhaps a more interesting example is Hall's Marriage Theorem, which gives a necessary and sufficient condition for the existence of certain pairings. The "necessary" part is trivial, the "sufficient" part takes a bit of work.


text:
Q: Are we allowed to rearrange a convergent series by grouping elements of it and converging to the same number. for a sequence like $\sum_{0}^{\infty}a_{n} = a_{0} + a_{1} + ... = L$
are we allowed to group its element like $b_{0} = a_{0} + a_{1} = a_{1} + a_{0}$  and  $b_{1} = a_{2} + a_{3} = a_{3} + a_{2}$ , and so on. (in pairs)
then can we conclude that;
$\sum_{0}^{\infty}a_{n} = \sum_{0}^{\infty}b_{n} = \sum_{0}^{\infty}a_{n} = (a_{1} + a_{0}) + (a_{3} + a_{2})... = L$
I know that even if I can not have such a rearrangement, still $\sum_{0}^{\infty}a_{n} = L \Rightarrow   (a_{1} + a_{0}) + (a_{3} + a_{2})... = L $ holds. So my question is not that do they converge to the same real number L. My question is that are we allowed to make such an rearrangement and say they converge to the same real number L? And if this rearrangement is doable then I wonder whether I can generalize it by grouping, say 7 many elements, by their permutations?

A: If a series $\sum a_n$ converges to $L$, then the series $\sum b_n$ with $b_n = a_{kn}+ a_{kn +1}+ \dots + a_{kn+k-1}$ also converges to $L$, whatever the integer $k>1$ is.
This is not difficult to prove as $\{a_n\}$ converges to zero.
Obviously, the converse is not true.

A: No, we cannot. Because the infinite series are a bit tricky to handle. Unlike finite summations, the infinite summations can lead to contradictions if rearranged. Please, refer to this link for a detailed answer. Check out Ramanujan Summation of Natural Numbers. While proving that the $1-1+1-1+\cdots = \frac{1}{2}$. He has rearranged the summation which lead to the contradiction(because the limit of the sum is indeterminate). One more example. If we assume that the above statement is true then:
\begin{align}
S = 1+\left({1 \over 2}   + {1 \over 3}\right)+\left({1 \over 4}   + {1 \over 5}\right)\cdots   \\= 1+ {1 \over 3}   + \left({1 \over 2} +{1 \over 4}\right)   + {1 \over 5} \cdots \\
= 1+ \left({1 \over 3}   \right) +\left[\left({1 \over 2} + {1 \over 4}\right)   + {1 \over 5}\right] \cdots
\end{align}
We can do this till we don't get
\begin{align}
S = 1+{1 \over 3}   + {1 \over 5}+{1 \over 7}+ \cdots + \left({1 \over 2}   + {1 \over 4}+{1 \over 6} \cdots \right ) \\
= 1+{1 \over 3}   + {1 \over 5}+{1 \over 7}+ \cdots + {1 \over 2}\left({1 \over 1}   + {1 \over 2}+{1 \over 3} \cdots \right )
\end{align}
$$ S =  \left(1+{1 \over 3}   + {1 \over 5}+{1 \over 7}+ \cdots \right)+{1 \over 2} S $$
From the above we conclude $ {1 \over 2} S  ={1 \over 2}   + {1 \over 4}+{1 \over 6} \cdots = 1+{1 \over 3}   + {1 \over 5}+{1 \over 7}+ \cdots $ . Which doesn't seems to be obvious.
Also, See the  Link here


text:
Q: openweathermap API doesn't change the local time for the desired city The time does not change when I change the city location where everything else does. The sunrise and the sunset are changing to the California time in the U.S. I want the time to change to the local time of the city I specify.
JSONObject jsonObj = new JSONObject(result);
JSONObject main = jsonObj.getJSONObject("main");
JSONObject sys = jsonObj.getJSONObject("sys");
JSONObject wind = jsonObj.getJSONObject("wind");
JSONObject weather = jsonObj.getJSONArray("weather").getJSONObject(0);
Long updatedAt = jsonObj.getLong("dt");
String updatedAtText = "Updated at:   " + new SimpleDateFormat("MM/dd/YYYY   hh:mm a", Locale.ENGLISH).format(updatedAt * 1000);
Long sunrise = sys.getLong("sunrise");
Long sunset = sys.getLong("sunset");
sunrised.setText(new SimpleDateFormat("hh:mm a", Locale.ENGLISH).format(new Date(sunrise * 1000)));
sunsetted.setText(new SimpleDateFormat("hh:mm a", Locale.ENGLISH).format(new Date(sunset * 1000)));`


text:
Q: Undefined response from meteor method call I am calling meteor function which has an api to fetch data from google. But before getting the result it returning from method. I know it is similar to the question  Returning value from callback within Meteor.method
But i don't want to use any npm module(future-fiber) to solve this. Is there any similar package in meteor which provide same functionality.


text:
Q: Problema paralelización en R para descargar datos Estoy intentando descargar los cif de un listado de 111.000 empresas más o menos mediante web scraping.
Para situarse, el cif de cada empresa está en un enlace distinto, es decir, tengo un enlace para cada empresa, unos 111.000.
Os pongo la función creada para la descarga de los cif que funciona bien:
extraer_cif <- function(x,cif){
  for (i in 1:length(x)){
    try({cif[i] <- read_html(x[i]) %>% html_nodes(".text-right") %>% html_text
    }, silent = TRUE)
    print(paste0("Se han descargado CIF de:",i))
  }
  return(cif)
}

Hasta aquí está todo bien, el problema viene ahora cuando intento paralelizar el proceso para que sea más rápida la descarga porque sino es un proceso muy pesado y largo.
He estado buscando por ahí y lo he intentado con las librerías parallel, foreach y doSNOW.
Pongo el código de lo que tengo en la paralelización:
n.cores <- detectCores()

cl <- makeCluster(6)

registerDoSNOW(cl)

prueba <- enlaces[1:100]

ver <- c()

ver <- foreach(i = 1:length(prueba)) %dopar% {
  extraer_cif(prueba,cif)
}

Las 3 primeras líneas de código no debería haber problema ya que es el tema de los núcleos del sistema.
Luego cree prueba para probar si funcionaba simplemente con los primeros 100 enlaces.
Y por último, a partir del foreach es ya la paralelización. Lo he hecho siguiendo ejemplos que ha hecho otra gente y parece que funciona pero el problema está en que no me rellena bien el objeto ver y lo llena de NULL.
Algún problema tonto debe de ser pero no soy capaz a dar con ello.


text:
Q: How can I synchronize two CPU threads at a specific line of code? I have two threads and one CPU.
I want each of the two threads that reached line A earlier in their program to wait for the other thread to reach line A, after which both threads continue to run their program. I have done this as follows, But I want both threads of line A to run their program exactly at the same time.
How can I accomplish this?
My code:
//headers
static volatile bool waitFlag[2];

void *threadZero(void*){
    //some codes

    waitFlag[1] = true;
    while(!waitFlag[0]);
    //line A of thread zero

    //some codes
}

void *threadOne(void*){
    // some codes

    waitFlag[0] = true;
    while(!waitFlag[1]);
    //line A of thread one

    //some codes
}

int main(){
    waitFlag[0] = waitFlag[1] = false;
    //Creates two threads and waits for them to finish.
}

A: A busy loop is inefficient for this purpose. What you want is a condition, a mutex and a simple counter:

*

*Lock the mutex.

*Increase the counter.

*

*If the counter is 2, broadcast on the condition.

*Otherwise wait on the condition.

*Unlock the mutex.

This logic can be easily adapted to any number of threads by changing the threshold for the counter. The last thread to increment the counter (protected by the mutex) will broadcast on the condition and will unlock itself and all the other threads simultaneously. If you want to synchronize multiple times you can also reset the counter.
Here's an example:
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/random.h>

pthread_cond_t cond;
pthread_mutex_t cond_mutex;
unsigned int waiting;

// Sleep a random amount between 0 and 3s.
// This is just for testing, you don't actually neeed it.
void waste_time(void) {
    unsigned us;
    getrandom(&us, sizeof(us), 0);
    us %= 3000000;
    fprintf(stderr, "[%lx] Sleeping %u us...\n", pthread_self(), us);
    usleep(us);
}

void synchronize(void) {
    pthread_mutex_lock(&cond_mutex);

    if (++waiting == 2) {
        pthread_cond_broadcast(&cond);
    } else {
        while (waiting != 2)
            pthread_cond_wait(&cond, &cond_mutex);
    }

    pthread_mutex_unlock(&cond_mutex);
}

void *threadZero(void *_) {
    waste_time();
    // ...
    synchronize();
    fprintf(stderr, "[%lx] Resuming.\n", pthread_self());
    // ...
    return NULL;
}

void *threadOne(void *_) {
    waste_time();
    // ...
    synchronize();
    fprintf(stderr, "[%lx] Resuming.\n", pthread_self());
    // ...
    return NULL;
}

int main(void) {
    pthread_t zero, one;

    pthread_create(&zero, NULL, threadZero, NULL);
    pthread_create(&one, NULL, threadOne, NULL);
    // ...
    pthread_join(zero, NULL);
    pthread_join(one, NULL);

    return 0;
}


text:
Q: Hay alguna forma de resumir todos estos else if? Buenas, estoy con un proyecto donde una función comprueba si una bola toca un muro, el cual es un array de 15 "porciones" con cada uno de 50u de tamañano. Necesito saber que parte del muro toca y para eso he hecho lo siguiente, pero queda exageradamente aparatoso:
if(bolaY == INIPANTALLAY + ALCADAMAO)//Comprueba que llegue hasta la altura del maon
            {
                if (bolaX > 30 && bolaX < 80)
                {
                    if (Mao[0].maotrencat == false)//Si el maon tocado no esta roto continua
                    {
                        Mao[0].maotrencat = true;//Cambia el estado del maon
                        punts += 1;//Suma 1 punto
                        dirX *= -1;// cambio de direccion
                        dirY *= -1;// cambio de direccion
                    }
                }
                else if (bolaX > 80 && bolaX < 140)
                {

                    if (Mao[1].maotrencat == false)//Si el maon tocado no esta roto continua
                    {
                        Mao[1].maotrencat = true;//Cambia el estado del maon
                        punts += 1;//Suma 1 punto
                        dirX *= -1;// cambio de direccion
                        dirY *= -1;// cambio de direccion
                    }
                }
                else if (bolaX > 140 && bolaX <200)
                {

                    if (Mao[2].maotrencat == false)//Si el maon tocado no esta roto continua
                    {
                        Mao[2].maotrencat = true;//Cambia el estado del maon
                        punts += 1;//Suma 1 punto
                        dirX *= -1;// cambio de direccion
                        dirY *= -1;// cambio de direccion
                    }
                }
                else if (bolaX > 200 && bolaX <260)
                {

                    if (Mao[3].maotrencat == false)//Si el maon tocado no esta roto continua
                    {
                        Mao[3].maotrencat = true;//Cambia el estado del maon
                        punts += 1;//Suma 1 punto
                        dirX *= -1;// cambio de direccion
                        dirY *= -1;// cambio de direccion
                    }
                }
                else if (bolaX > 260 && bolaX <320)
                {

                    if (Mao[4].maotrencat == false)//Si el maon tocado no esta roto continua
                    {
                        Mao[4].maotrencat = true;//Cambia el estado del maon
                        punts += 1;//Suma 1 punto
                        dirX *= -1;// cambio de direccion
                        dirY *= -1;// cambio de direccion
                    }
                }
                else if (bolaX > 320 && bolaX <380)
                {

                    if (Mao[5].maotrencat == false)//Si el maon tocado no esta roto continua
                    {
                        Mao[5].maotrencat = true;//Cambia el estado del maon
                        punts += 1;//Suma 1 punto
                        dirX *= -1;// cambio de direccion
                        dirY *= -1;// cambio de direccion
                    }
                }
                else if (bolaX > 380 && bolaX <440)
                {

                    if (Mao[6].maotrencat == false)//Si el maon tocado no esta roto continua
                    {
                        Mao[6].maotrencat = true;//Cambia el estado del maon
                        punts += 1;//Suma 1 punto
                        dirX *= -1;// cambio de direccion
                        dirY *= -1;// cambio de direccion
                    }
                }
                else if (bolaX > 440 && bolaX <500)
                {

                    if (Mao[7].maotrencat == false)//Si el maon tocado no esta roto continua
                    {
                        Mao[7].maotrencat = true;//Cambia el estado del maon
                        punts += 1;//Suma 1 punto
                        dirX *= -1;// cambio de direccion
                        dirY *= -1;// cambio de direccion
                    }
                }
                else if (bolaX > 500 && bolaX <560)
                {

                    if (Mao[8].maotrencat == false)//Si el maon tocado no esta roto continua
                    {
                        Mao[8].maotrencat = true;//Cambia el estado del maon
                        punts += 1;//Suma 1 punto
                        dirX *= -1;// cambio de direccion
                        dirY *= -1;// cambio de direccion
                    }
                }
                else if (bolaX > 560 && bolaX <620)
                {

                    if (Mao[9].maotrencat == false)//Si el maon tocado no esta roto continua
                    {
                        Mao[9].maotrencat = true;//Cambia el estado del maon
                        punts += 1;//Suma 1 punto
                        dirX *= -1;// cambio de direccion
                        dirY *= -1;// cambio de direccion
                    }
                }

He intentado mejorarlo con un Switch, pero no estoy seguro si es posible teniendo en cuenta la comparación y el && en cada caso.

A: Debes aprovechar que cada porción tiene el mismo tamaño, esa es la clave. Entonces podrías utilizar un ciclo for de esta manera:
for (int i = 0; i < 15; i++)
{
    if (bolax > 20 + 60*i && bolax < 80 + 60*i)
    {
        if (Mao[i].maotrencat == false)//Si no esta roto continua
        {
            Mao[i].maotrencat = true;//Cambia el estado del maon
            punts += 1;//Suma 1 punto
            dirX *= -1;// cambio de direccion
            dirY *= -1;// cambio de direccion
        }
    break; // este break evita que se siga evaluando todos los otros casos
    // tambien puede servir
    // i = 15;
    }

}

De esta manera tu código queda todo reducido.

A: Prueba lo siguiente si da el mismo resultado; veo que lo común es siempre realizar:
Mao[INDICEAMODIFICAR].maotrencat = true;
// Las siguientes 3 son simprelas mismas
punts += 1;//Suma 1 punto
dirX *= -1;// cambio de direccion
dirY *= -1;// cambio de direccion

Los if internos a if(bolaY == INIPANTALLAY + ALCADAMAO) de la siguiente forma:
int indice=-1; // Iniciado el negativo para indicar ninguno a modificar.

if (bolaX > 30 && bolaX < 80 && (!Mao[0].maotrencat))
{
    indice=0;
}
else if (bolaX > 80 && bolaX < 140 && (!Mao[1].maotrencat))
{

    indice=1;
}
else if (bolaX > 140 && bolaX <200 && (!Mao[2].maotrencat))
{
    indice=2;
}
else if (bolaX > 200 && bolaX <260 && (Mao[3].maotrencat))
{
    indice=3;
}
else if (bolaX > 260 && bolaX <320 && (!Mao[4].maotrencat))
{
    indice=4;
}
else if (bolaX > 320 && bolaX <380 && if (!Mao[5].maotrencat))
{
    indice=5;
}
else if (bolaX > 380 && bolaX <440 && (!Mao[6].maotrencat))
{
    indice=6;
}
else if (bolaX > 440 && bolaX <500 && (!Mao[7].maotrencat))
{
    indice=7;
}
else if (bolaX > 500 && bolaX <560 && (!Mao[8].maotrencat))
{
    indice=8;
}
else if (bolaX > 560 && bolaX <620 && (!Mao[9].maotrencat))
{
    indice=9;
}

if (indice>=0) {
   Mao[indice].maotrencat = true;
   punts += 1;//Suma 1 punto
   dirX *= -1;// cambio de direccion
   dirY *= -1;// cambio de direccion
}

Otra forma es que en vez de evaluar if ([...] && (!Mao[INDICE].maotrencat)) solamente evalues bolaX (es la única que veo evaluas) y el if que puse donde se evalua indice:
if (indice>=0) {
   if (!Mao[indice].maotrencat) {
      Mao[indice].maotrencat = true;
      punts += 1;//Suma 1 punto
      dirX *= -1;// cambio de direccion
      dirY *= -1;// cambio de direccion
   }
}

A: Puedes usar un array para obtener el resultado directamente.
No entiendo exactamente como está organizado tu muro; por lo que veo en tu código, son trozos de distinto tamaño. Pero, en cualquier caso, todos los trozos son multiplos de 10, así que puedes utilizar algo como esto:
struct accion_s {
  int Mao;
  int punts;
  int dirX;
  int dirY;
};

struct accion_s acciones[620/10] = {
  { W, X, Y, Z },
  { W2, X2, Y2, Z2 },
  { W3, X3, Y3, Z3 },
  ...
};

Ahora, tan solo tienes que comprobar una vez:
if( bolaY == INIPANTALLAY + ALCADAMAO ) {
  struct accion_s accion = acciones[bolax / 10];

  // Es SEGURO que estamos en el muro.
  Mao[accion.Mao].maotrencat = true;//Cambia el estado del maon.
  punts += accion.punts; //Suma 1 punto
  dirX *= accion.dirX;// cambio de direccion
  dirY *= accion.dirY;// cambio de direccion
}

Esto es una técnica básica en el desarrollo de juegos: precalcula todo  lo que puedas.

A: Después de leer todos los comentarios, entiendo que lo que quieres hacer es esto:
Tienes un muro, dividido en varios trozos, y una pelota:
------
  o

Los trozos con contiguos, sin separación. La coordenada X del primer trozo de muro es 20. La anchura de todos los trozos es la misma, 60 pixels.
Y conoces en todo momento la posición X de la pelota.
Para conoces el trozo de muro en el que impactas, no hay que hacer ningún if. Te basta con una simple división.
muro = ( pelota.X - 20 ) / 60;

Restamos a la posición actual de la pelota el inicio del primer muro, y lo dividimos entre la anchura de los muros; con eso, ya tenemos directamente un índice para tus Mao[].
Puesto que, en todos los casos, haces lo mismo, te bastaría con hacer
if( bolaY == INIPANTALLAY + ALCADAMAO ) {
  int idx = ( bolaX - 20 ) / 60;

  if( Mao[idx].maotrencat == false ) {
    Mao[idx].maotrencat = true;
    punts += 1;
    dirX *= -1;
    dirY *= -1;
  }
}

En el caso de que tuvieras que realizar distintas operaciones dependiendo del muro, es cuando emplearías la solución propuesta por @Trauma: añadir los datos concretos de cada muro en un array. En tu caso, por lo que veo, añadirías esos datos extra a tu Mao[].


text: Q: prevent database entries rollsback incase of error in nestjs migration run I have written a migration in nestjs which iterates through some data in a for each loop. Each loop iterations saves entry in the database. The problem is when an error occurs, migration deletes all the entries in the database it has added. How can I prevent that? I don't want the database to roll back to the previous state but keep all the entries that have been added. I a, using typeorm


text:
Q: $A \in M_n(\mathbb R)$ is symmetric: If one of the entries in its diagonal is positive, prove that it has at least one positive eigenvalue
Let $A \in M_n(\mathbb R)$ be symmetric. Given that one of the entries in its diagonal is positive, prove that it has at least one positive eigenvalue.

I didn't come to any conclusion.
Thanks guys.

A: Let $\ell$ be the linear transformation and $q$ the quadratic form given by $A$:
$$\ell(x):=Ax,\quad q(x):=x^TAx.$$
The assumption that $A$ has a positive diagonal entry means that there is a vector on which $q$ is positive.
A matrix represents $\ell$ (in an appropriate basis) iff it is of the form $PAP^{-1}$ with $P$ invertible.
A matrix represents $q$ (in an appropriate basis) iff it is of the form $PAP^T$ with $P$ invertible.
The theory tells us that, since $A$ is symmetric (*), we can pick a $P$ such that $P^{-1}=P^T$ and $PAP^T$ is a diagonal matrix $D$. In particular, the entries of $D$ are the eigenvalues of $A$. If they were all nonpositive, $q$ would be nonpositive on all vectors.
(*) See Gerry Myerson's comment to percusse's answer.

A: Suppose the matrix $A$ has no positive eigenvalue, hence a negative (semi)definite matrix $A\preceq 0$ or $x^TAx \leq 0$ for all $x\in\mathbb{R}^n$.
For simplicity, assume that the positive entry is the $A_{11}$ (or upper left etc.) entry of the matrix. Then, using a vector $x = \begin{bmatrix}1 &0 &\ldots &0\end{bmatrix}^T$, we know that $x^TAx > 0$.

A: Because $A$ is symmetric, it admits real Schur decomposition, i.e. $A= U^t.D.U$.
Now suppose $A_{1,1}$ is positive, and assume that all eigenvalues are non-positive. Then
we arrive at contradiction:
$$
  A_{1,1} = \sum_{k=1}^n U^t_{1,k} \lambda_k U_{k,1} =  \sum_{k=1}^n \lambda_k \left( U_{k,1} \right)^2 <= 0
$$


text:
Q: Counting Graphs which are a sum of Cycles If $G$ and $H$ are graphs with vertex set $V(G), V(H)$ and edge set $E(G), E(H)$ respectively.  Define the sum $G+H$ to be the graph with vertex set $V(G) \cup V(H)$ and edge set $E(G) \cup E(H)$
How many unlabelled isomorphism classes of graphs are there on $n$ vertices which are a sum of cycle graphs on more than $3$ vertices?
So for example there are $2$ such graphs on $6$ vertices namely $C_6$ and $C_3 + C_3$. There are $4$ on $9$ vertices: $C_9$, $C_3+C_6$, $C_4 + C_5$ and $C_3 + C_3 + C_3$.

A: To put it more simply, you are asking for the number of unlabelled $2$-regular graphs on $n$ vertices; equivalently, the number of partitions of $n$ into parts $\ge3.$ This is OEIS sequence A008483.


text:
Q: "Function with duplicate name cannot be defined" error but no duplicate function While trying to write a function for gradient descent in Matlab I got the following error:
Function with duplicate name "gradientDescent" cannot be defined. The program I'm working on has two functions in it, and when I remove the second one the problem goes away. I don't understand why this is happening given that the two functions have completely different names. Here's the code:
function dJ = computeDerivative(X, y, theta, feature)
m = length(y); % number of training examples
hypothesis = X * theta;
error = ((hypothesis - y) / m) .* X(feature, :)
dJ = sum(error);
end

function theta = gradientDescent(X, y, theta, alpha, num_iters)
%GRADIENTDESCENT Performs gradient descent to learn theta
%   theta = GRADIENTDESENT(X, y, theta, alpha, num_iters) updates theta by
%   taking num_iters gradient steps with learning rate alpha

m = length(y); % number of training examples
for iter = 1:num_iters

for i = 1:length(theta)
    theta(i) = theta(i) - alpha * computeDerivative(X, y, theta, i)
end

end
end

A: When you create a MATLAB function, each function should be in a separate file and the name of each file should be identical to the name of the function. If however you have a main file, and you want some local function, you can write the local function in the same file, but only the main function will have access to it. In your case computeDerivative is the main function and gradientDescent is the local function


text:
Q: How to display connections from Oracle using Java? I want to create JSF page which displays Oracle connections. The web page will be hosted on Glassfish server. How I can get this information from Oracle with SQL query?
Best wishes

A: Following query displays all sessions, you can use state, status, username, machine, program and ... to retrieve information you want
select *
  from v$session


text:
Q: Why is wp_head() creating a top margin at the top of my theme header? I am creating a custom theme, and elements behave as they should but when I place the <?php wp_head() ?> tag I get a top margin, at the top of my theme header.
When I remove the <?php wp_head(); ?> the margin goes away. I have been at this for a while any help would be great.

A: If you try to hide the Admin Bar by hooking into the show_admin_bar filter, but do this too late (init with the default priority is too late for example), you will get an extra 28px top margin but no admin bar there.

A: The margin style block is output by the _admin_bar_bump_cb function which runs on the wp_head action. You can remove the action by calling:
remove_action('wp_head', '_admin_bar_bump_cb');

I placed it in my enqueue scripts function hook and it successfully removed the top margin output, but I'm sure you could place it anywhere in the functions.php and have it work correctly.
That way you don't need a silly override in your css =)

A: Hard to saw without looking at it, but an educated guess:
More than likely it is the CSS for the admin bar, which only appears when you are logged in. the <?php wp_head() ?> will include the css for it, and <?php wp_footer(); ?> includes the html for the admin bar.
If you look, it should actually be a margin-top added to the html tag.

A: I also encountered the same problem and I solved it by adding this:
html{ margin-top:0px !important;}

Put at the top of your theme's CSS file.

A: This happened with me as well, this space is for the admin bar at the top of your theme which gets displayed to a logged in user.
If you have logged in to your WordPress dashboard in the same browser in which you're using the custom theme, then there is the problem.
Simply log out from the WordPress admin account and open your custom theme again.

A: adding "margin-top: 0px !important" to the top of your CSS file actually will work, but ONLY if you re-arrange your header information to call the css file AFTER wp_head gets called.
the lowest CSS attribute will get applied, 100% of the time.

A: You should see what class is adding the margin with firebug or a similar tool.

A: Try this,
html { margin-top:0px; padding-top:0px; }


text:
Q: Split word into syllables How to split the syllables in a word using JavaScript. Is there any API for that? Any help will be appreciated.

A: Now, back to being constructive, what I suggest is that you find a couple online dictionary sites and look at their APIs (I know dictionary.com has a free API) and see if you can use it to access just the word split into syllables from a lookup.
Unfortunately, from what I have read, it looks like you would really need a dictionary of words split already to check against and there aren't any standalone versions out there.
Be the first and post it somewhere! :)


text:
Q: Novel where time travel has been discovered, and is used for imprisoning criminals I read this book in the mid 80's, and what I remember of it, is that time travel has been discovered (invented if you will), but it only works one way. It's possible to send poeple back in time, but it's impossible to go forward. That which has been sent back can't even be brought to its original time again.
This would seem fairly useless, but for one thing, namely imprisonment. The main character is, as far as I can remember, the leader of a group of prisoners. They regularly search they're surroundings for time junk1, which is what they call stuff that was sent back during early stages of testing the time travel. I also distinctly fossils of trilobites being mentioned.
One day a man arrives on The Anvil1, which is what they call the device (platform, scaffold, or whatever) where new prisoners and supplies appear. He claims to be a prisoner, but for some reason the main character gets suspicious of this new man, and starts following him. And in the end it is revealed that this man is an agent of the government, and that they have discovered a way to go forward in time, and that it has been decided that they have all been pardoned, and that they are free to return home. However, the main character decides to stay and he is employed as a guide to time tourists.
1Time junk and anvil are direct translations from my native language to English, but it's perfectly possible that those are not the names used in an official English version.

A: Hawksbill Station (aka The Anvil of Time), a novel by Robert Silverberg, also the answer to this old question. (A shorter version was published as a novella with the same title, "Hawksbill Station", text available at escapepod.org.) Here is a plot summary from Wikipedia:

Hawksbill Station was a penal colony in the Precambrian era created by the United States government, using time travel as a means to exile rebels and political dissidents into the past. The colony houses only male exiles, who are sent there as a "humane" alternative to execution. The machine only works one way, leaving prisoners are marooned in the past.
The prison is in a barren coastal area prior to the development of the land. The novel focuses on the personal relationship of the main character, the de facto leader of the colony, and both his government torturer/prosecutor and Dr. Hawksbill, each of whom had been members of the dissidence movement. It also explores the picayune ideological differences among the prisoners, and the confused circumstances leading to the establishment of the authoritarian government.
The prisoners, all of them middle-aged or elderly, are surprised by the arrival via the time machine of a much younger prisoner. The newcomer, ostensibly an economist, is questioned about economic theory and political ideology, and his answers reveal his essential ignorance of either. His ignorance and youth cause the prisoners to wonder if he is fact a political prisoner or a common criminal exiled for a heinous crime.
When the newcomer arrives via the time machine a second time, it is revealed that he is a police officer of a new government which overthrew the authoritarian regime but was unrelated to the dissident movements of the exiles; upon the overthrow, the new government discovered both the existence of Hawksbill Station and the means to time travel from past to future, making it possible to retrieve prisoners from the colony. The newcomer has been sent to evaluate the prisoners and to recommend whether they are mentally stable for retrieval.
With return now possible, the leader of the exiles realizes that he is a time traveler of a different sort: the struggle against the authoritarian regime, his life's work, is over; his closest friends in the movement and his bitterest enemies, who left the movement to join the authoritarian government, are dead; and those who finally overthrow the government have little connection with or regard for his brand of dissent. He is now somewhat inclined to visit the newcomer's future, but staying at Hawksbill Station is now the only existence he knows.


text:
Q: where command line arguments are stored? I have a doubt @ the storage of command line arguments.
myprog.exe -cfgfile myconfig.cfg

The command line args are passed when the process gets created, so are they stored outside the process?
Where does the OS stores it?

A: For Windows, the command line arguments are kept in the process environment block (PEB), which is allocated in the user process address space when the process is created.
You can read Windows Internals for a lot more details. Here's a snippet from Chapter 5 - Processes, Threads, and Jobs.
I would assume that it's the same for the Unix flavors. This data needs to be in the process memory, so that it can be accessed by the process itself.

A: It depends on the OS and possibly the language. A good C-centric answer is that the OS creates the process space (including loading the code, creating the heap and stack, etc). Then it puts the command line argument vector in a location, and then copies the address of the argument vector to 'argv' on the stack, and the count of words to 'argc'.
Only after these tasks are done does the OS allow the process to execute.

A: The command line arguments are stored in the application's memory space.  Exactly where differs from OS to OS, my guess is it usually goes at the bottom of the heap.  The code which puts it there is in the kernel source code for exec on Unix-like OSs, not sure where it would be in Windows (not that you can see the source anyway).  The C runtime code (this is where "crt" comes from) takes argv and argc from the stack and then calls main.  If you are interested in learning more how an executable starts up in Linux, this paper by Ulrich Drepper (glibc maintainer) may be of value: http://people.redhat.com/drepper/dsohowto.pdf

A: in Linux :
command line arguments will get stored in stack.
dont confuse environmental variable with command line args, process address space have separate memory area for environmental variables


text:
Q: Invalid argument supplied for foreach() (View: C:\xampp\htdocs\E-Commerce\resources\views\orders\order.blade.php) commerce application, I have Order table and OrderProduct table, whenever I save order the order and the order_products tables are working fine, but when I want to retrieve all the order_products I got that error. I don't what am missing. Thanks for your help, Here is my code.
This is my Order table
class Order extends Model
{

    use AsSource;

    protected $fillable = ['user_id', 'billing_email', 'billing_first_name', 'billing_last_name', 'billing_address',
        'billing_city', 'billing_town', 'billing_postalcode', 'billing_phone', 'billing_total', 'error'
    ];

    public function user()
    {
        return $this->belongsTo('App\User');
    }

    public function product()
    {
        $this->belongsToMany('App\Product')->withPivot('quantity');
    }
}

This is my OrderProduct table
class OrderProduct extends Model
{
    protected $table = 'order_product';

    protected $fillable = ['order_id', 'product_id', 'quantity'];
}

This is my method
public function show(Order $order, Request $request)
{
    $order = Order::where('id', $request->order->id)->first();
    $products = $order->product();

    // dd($products);
    return view('orders.order')->with([
        'products' => $products,
        'order' => $order
    ]);
}

and if I dd($products) I got Null
And here is my route
Route::get('order/{order?}', [\App\Http\Controllers\OrderProductController::class, 'show'])->name('platform.order.edit');

Thanks for your concern!.

A: Try like this and what do you get ?
$order = Order::with('product')
    ->where('id', $request->order->id)
    ->first();
return $order;

Let we know if get an error


text:
Q: Using OR Operator for File Dependencies I want to add the file dependency to a job. Suppose there are 2 files
1 : Test.Pdf
2 : Test.xml
Whenever there is either of the file(any one of the file or both) the job should trigger.
I tried multiple qualifiers but not getting the desired result.
Qualifiers that I have tried so far :
A)-w %p/I%DATE:~12,2%%DATE:~4,2%%DATE:~7,2%*Test.xml || *Test.Pdf
B)-w %p/I*Test.xml || *Test.Pdf
C)-w %p/I*Test.xml || /I*Test.Pdf
D)-w %p/I*Test.xml || -w %p/I*Test.Pdf
Can anyone let me know how to add the OR Dependency?

A: The file dependencies are actually running test <qualifier> command, replacing %p with the filename in qualifier.
This should work for you scenario:
OPENS "/tmp" (-w %p/Test.xml -o -w %p/Test.Pdf)


text:
Q: How to make a DIV scrollable instead of BODY? I want my page's BODY not to be scrollable but a DIV inside the BODY should be scrollable.
I have this in my css file:

body {
overflow:hidden
}

.mainSection {
overflow:scroll
}

but it doesn't work and the DIV doesn't become scrollabel (it just shows two disabled scroll bars for the DIV)!

A: .mainSection needs to have a height. Otherwise the browser can not know what it should consider overflow.

A: Are you sure the style for your mainSection class is being applied? You can use a tool like Web Developer or Firebug (for Firefox) to make sure that the style is being correctly applied. Also if you just have one mainSection, you might want to use an id instead of a class. the tag in html would then be
 instead of
 and the css becomes #mainSection { ... } instead of .mainsection { ... }

A: Here is the whole thing well explained
http://www.w3schools.com/css/pr_pos_overflow.asp
You can experiment.

A: I had the same problem before, but I could manage to solve it just with overflow: auto;. Try it and it will work.
Updated
The full html code looks like this

    <title>Test page</title>

my div text

Works perfectly in any browsers. I tested myself in Chrome, IE, Safari, Mozilla, and Opera


text:
Q: Charindex vs Contains delivering very different results I am running two queries that are supposed to do the same thing on our CV database table:

*

*CONTAINS (full-text indexed table - cv, fullname etc are all included in the index)
 SELECT COUNT(1)
 FROM [CVDatabase]
 WHERE CONTAINS ((CVText, fullname, city, CompanyName, jobTitle, targetJobTitle),'"cost accountant*"') AND (Country='South Africa')

Number of results: 300

*CHARINDEX (unindexed)
SELECT COUNT(1)
FROM [CVDatabase]
WHERE (CHARINDEX ('cost accountant', cvtext) > 0 OR
       CHARINDEX ('cost accountant', fullname) > 0 OR
       CHARINDEX ('cost accountant', city) > 0 OR
       CHARINDEX ('cost accountant', companyname) > 0 OR
       CHARINDEX ('cost accountant', jobtitle) > 0 OR
       CHARINDEX ('cost accountant', targetjobtitle) > 0)
  AND (Country = 'South Africa')

Number of results: 339
This is over a 10% discrepancy. Naturally CHARINDEX with capture 'cost accountant', 'cost accountants' (which CONTAINS will also capture with the wildcard). The difference might come from characters before 'cost accountant' which CHARINDEX will capture but not CONTAINS - but I cannot think of any characters that would make sense before the word 'cost'.
Is it possible there is something wrong with the indexing, and it is not picking up all the results? It is set to track automatic changes so it should be indexing correctly.

A: *

*Are all those rows indexed?

*SQL FT will split the text into words so it will not find "xyzcost accountant", but that's probably ok. Still, what happens if you search for "cost accountant" (i.e. without the wildcard"?

*Here are some details on how to check if the indexing process has completed. Note that if it hasn't your queries still run but produce inconsistent results (i.e less results). This is because the designers of FT want to enable the system to update and insert new data without downtime but a little data loss may happen.

*The examples on msdn do not show how to combine phrase search with an wildcard. Maybe you could use "NEAR" instead?


text:
Q: Integrate $\int_{0}^{2\pi}\log|1-e^{i\theta}| d\theta$ Here is exercise 11, chapter 3 from Stein & Shakarchi's Complex Analysis II:
Show that if $|a|<1$, then:
$$\int_{0}^{2\pi}\log|1-ae^{i\theta}|\,d\theta = 0$$
Then, prove that the above result remains true if we assume only that $|a|\leq 1.$
($a\in \mathbb{C}$)
I've already proved it for $|a|<1$, but couldn't make it for $|a|=1$, which I thought would be the easy part. But the only thing I could come up with was that, WLOG, it is enough to prove that:
$$\int_{0}^{2\pi}\log|1-e^{i\theta}|\,d\theta = 0$$
Tried to look for some kind of symmetry, but could't find it. Any ideas? Thanks!

A: Note that for $|a|=1$, we can write $a=e^{i\psi}$.  Then, exploiting the $2\pi$-periodicity of the integrand, we have
$$\begin{align}
\int_{-\pi}^\pi \log|1-ae^{i\theta}|\,d\theta&=\int_{-\pi}^\pi \log|1-e^{i(\theta+\psi)}|\,d\theta\\\\
&=\int_{-\pi+\psi}^{\pi+\psi} \log|1-e^{i\theta}|\,d\theta\\\\
&=\int_0^{2\pi}\log|1-e^{i\theta}|\,d\theta
\end{align}$$
METHODOLOGY 1:
Note that we have $|1-e^{i\theta}|=\sqrt{2(1-\cos(\theta))}=2|\sin{\theta/2}|$.  Now, we have
$$\int_0^{2\pi}\log|1-e^{i\theta}|\,d\theta=4\int_0^{\pi/2}\log(2\sin(\theta))\,d\theta=0$$
since $\int_0^{\pi/2}\log(\sin(\theta))\,d\theta=-\frac{\pi}{2}\log(2)$

METHODOLOGY 2:
Now, we cut the complex plane with a line from $(1,0)$ and extending along the positive real axis.
Note that $\log(1-z)$ is analytic within and on a closed contour $C$ defined by $z=e^{i\phi}$ for $\epsilon \le \phi \le 2\pi -\epsilon$, and $z=1+2\sin(\epsilon/2) e^{i\nu}$ for $\pi/2 + \gamma \le \nu \le 3\pi/2 -\gamma$, where $
\cos(\gamma)=\frac{\sin \epsilon}{\sqrt{2(1-\cos \epsilon)}}$ and $0 \le \gamma <2\pi$ on this branch of $\gamma$.
Then, from the residue theorem, we have
$$\int_C  \frac{\log(1-z)}{z}dz=2\pi i \log(1-0)=0$$
which implies
$$\begin{align}
\int_C \frac{\log(1-z)}{z} dz&=\int_{\epsilon}^{2\pi-\epsilon} \log(1-e^{i\phi})i d\phi+\int_{3\pi/2-\gamma}^{\pi/2+\gamma} \frac{\log(-2\sin(\epsilon/2) e^{i\nu})}{1+2\sin(\epsilon/2) e^{i\nu}}i2\sin(\epsilon/2) e^{i\nu}d\nu\\\\
&=i\int_{\epsilon}^{2\pi-\epsilon} \log(1-e^{i\phi}) d\phi+ i2\sin(\epsilon/2)  \int_{3\pi/2-\gamma}^{\pi/2+\gamma} \frac{\log(-2\sin(\epsilon/2)e^{i\nu})e^{i\nu}d\nu}{1+2\sin(\epsilon/2)e^{i\nu}}   \\\\
&=i\int_{\epsilon}^{2\pi-\epsilon} \log|1-e^{i\phi}| d\phi -i \int_{\epsilon}^{2\pi-\epsilon} \arctan \left(\frac{\sin \phi}{1-\cos \phi}\right)d\phi \\\\
&+ i2\sin(\epsilon/2)  \int_{3\pi/2-\gamma}^{\pi/2+\gamma} \frac{\log(-2\sin(\epsilon/2)e^{i\nu})e^{i\nu}d\nu}{1+2\sin(\epsilon/2)e^{i\nu}}   \\\\
&=0
\end{align}$$
As $\epsilon \to 0$ the first term on the RHS approaches $i$ times the integral of interest.  The second term approaches zero since $\arctan(\frac{\sin \phi}{1-\cos \phi})$ is an odd, $2\pi$-periodic function of $\phi$ and the integration extends over the entire period.  And the last term approaches $0$ since $x\log x \to 0$ as $x \to 0$.  Thus, the integral of interest is zero!

A: I'll plod on and see
what happens.
We want to show that
$\int_{0}^{2\pi}\log|1-e^{it}|dt
= 0
$.
$\begin{array}\\
|1-e^{it}|
&=|1-\cos(t)-i\sin(t)|\\
&=\sqrt{(1-\cos(t))^2+\sin^2(t)}\\
&=\sqrt{1-2\cos(t)+\cos^2(t)+\sin^2(t)}\\
&=\sqrt{2-2\cos(t)}\\
&=\sqrt{2(1-\cos(t))}\\
&=\sqrt{2(2\sin^2(t/2))}\\
&=2\sin(t/2)
\qquad\text{if }0 \le t \le 2\pi\\
\end{array}
$
so
$\log|1-e^{it}|
=\log(2\sin(t/2))
$
so that
$\begin{array}\\
\int_{0}^{2\pi}\log|1-e^{it}|dt
&=\int_{0}^{2\pi}\log(2\sin(t/2))dt\\
&=2\pi\log(2)+\int_{0}^{2\pi}\log(\sin(t/2))dt\\
&=2\pi\log(2)+2\int_{0}^{\pi}\log(\sin(t))dt\\
&=2\pi\log(2)+2(-\pi \log(2))
\qquad\text{according to Wolfy}\\
&=0\\
\end{array}
$
By Googling for
"integral with sine and log"
I got a number of references to
$\int_{0}^{\pi}\log(\sin(t))dt
=-\pi \log(2)
$
being a result of Euler
including this one:
http://www.ams.org/journals/proc/2005-133-05/S0002-9939-04-07863-3/S0002-9939-04-07863-3.pdf
(Added later)
According to that paper,
Euler proved his result
by using
$ \log(\sin x)
= -\sum_{n=1}^{\infty} \dfrac{\cos(2nx)}{n}− \log 2
$
and
$\int_0^{\pi} \cos(2nx)dx
= 0
$.


text:
Q: Get the average mean of entries per month with datetime in Pandas I have a large df with many entries per month. I would like to see the average entries per month as to see as an example if there are any months that normally have more entries. (Ideally I'd like to plot this with a line of the over all mean to compare with but that is maybe a later question).
My df is something like this:
ufo=pd.read_csv('https://raw.githubusercontent.com/justmarkham/pandas-videos/master/data/ufo.csv')
ufo['Time']=pd.to_datetime(ufo.Time)

Where the head looks like this:

So if I'd like to see if there are more ufo-sightings in the summer as an example, how would I go about?
I have tried:
ufo.groupby(ufo.Time.month).mean()

But it does only work if I am calculating a numerical value. If I use count()instead I get the sum of all entries for all months.
EDIT: To clarify, I would like to have the mean of entries - ufo-sightings - per month.

A: You could do something like this:
# count the total months in the records
def total_month(x):
    return x.max().year -x.min().year + 1

new_df = ufo.groupby(ufo.Time.dt.month).Time.agg(['size', total_month])

new_df['mean_count'] = new_df['size'] /new_df['total_month']

Output:
    size    total_month     mean_count
Time
1   862     57              15.122807
2   817     70              11.671429
3   1096    55              19.927273
4   1045    68              15.367647
5   1168    53              22.037736
6   3059    71              43.084507
7   2345    65              36.076923
8   1948    64              30.437500
9   1635    67              24.402985
10  1723    65              26.507692
11  1509    50              30.180000
12  1034    56              18.464286

A: I think this what you are looking for, still please ask for clarification if i didn't reached what you are looking for.
# Add a new column instance, this adds a value to each instance of ufo sighting
ufo['instance'] = 1

# set index to time, this makes df a time series df and then you can apply pandas time series functions.
ufo.set_index(ufo['Time'], drop=True, inplace=True)

# create another df by resampling the original df and counting the instance column by Month ('M' is resample by month)
ufo2 = pd.DataFrame(ufo['instance'].resample('M').count())

# just to find month of resampled observation
ufo2['Time'] = pd.to_datetime(ufo2.index.values)

ufo2['month'] = ufo2['Time'].apply(lambda x: x.month)

and finally you can groupby month :)
ufo2.groupby(by='month').mean()

and this is the output which looks like this:
month   mean_instance
1       12.314286
2       11.671429
3       15.657143
4       14.928571
5       16.685714
6       43.084507
7       33.028169
8       27.436620
9       23.028169
10      24.267606
11      21.253521
12      14.563380

A: Do you mean you want to group your data by month? I think we can do this
ufo['month'] = ufo['Time'].apply(lambda t: t.month)
ufo['year'] = ufo['Time'].apply(lambda t: t.year)

In this way, you will have 'year' and 'month' to group your data.
ufo_2 = ufo.groupby(['year', 'month'])['place_holder'].mean()


text:
Q: Netbeans: How to alter naming pattern used to identify testSuites I have numerous JUNIT TestSuites that have a "Tests" suffix. Eclipse recognises the static suite() method and makes a run test option available in package explorer. However the same is not true with NetBeans which only gives me the default Run context menu option. However i noticed that it does recognize any class that uses "TestSuite" as a suffix as a Tests suite. I am new to NB 7.0 and am unable to find out how to alter the pattern or some how make NB work in the same way as Eclipse.

A: Ok, actually, I figured it out, while digging around trying to solve my own problem. Vanilla NetBeans uses ant, so this question is actually an ant question. If you look in the project's directory, we see that there is the build.xml file. This is the primary file that instructs ant what to do. If we look inside the file, we see that it's primary function is to simply <import /> the nbproject/build-impl.xml file. So, what we need is in here. We can use this file to override the functionality of the default implementation.
If you dig down into the build-impl.xml file, you'll come upon the junit section. Look for this section:
<target depends="init,compile-test,-pre-test-run" if="have.tests" name="-do-test-run">
    <j2seproject3:junit testincludes="**/*Test.java"/>
</target>

This is the section that actually runs the tests, and it's in a small block of xml, which is exactly what we need, because we're only trying to override one small bit. As is hopefully obvious, you can see we're only matching (recursively) file names that match the patter "*Test.java". So, in your case you would edit (or add) to that the pattern "TestSuite.java". Don't add this line to that file though, it might get hosed, as this is an automatically generated file. Instead, copy that whole bit to the actual build.xml file, and I think it needs to be pasted above the <import /> directive so it will take precedence. (Maybe not, try it below as well if that doesn't work.)
Now, here's the tricky bit, NetBeans has a custom junit runner, the <j2seproject3:junit /> tag. Without digging down even further to see how to pass it arguments, we don't know exactly how to add arguments to it, but for your case, this is fine, we don't really need to add one, we can make it work by just editing the one.
<target depends="init,compile-test,-pre-test-run" if="have.tests" name="-do-test-run">
    <j2seproject3:junit testincludes="**/*Test*.java"/>
</target>

This should likely do it for you. Now it will match anything that has the word test in it, and not just stuff that ends with the word test.

A: If you're using an ant project, you need to go into the ant files in the project directory, and find the ant commands that locate the tests. Last time I checked (a couple of years ago), the file name pattern that it was looking for was hard coded.


text:
Q: Using dynamic components to render Angular attributes to svg I would like to render dynamically matTooltip directive to SVG element .
I'm trying to use dynamic components in Angular in order to render a component with matTooltip directive inside a circle element
But tooltip is not getting render. I think that the template reference is not well placed
here's the tutorial I used
A bug reproduction demo


text:
Q: How to perform a search in a Multivalued Field in Solr? I'm having dificulties to execute a search in Solr. My Solr has a Multivalued field like this document below:
<int name="id">2166324592435</int>
...others fields
<arr name="Series">
   <str>The Walking Dead<\str>
   <str>Game of Thrones<\str>
<\arr>

The Multivalued field Series has the Tv serie which the document references. In the example above, my document says about The Walking Dead and Game of Thrones. I can have documents with one, two or more series or even no series.
What I want to do is search in Solr. I want to give the series that I want and Solr should returns the documents that says about my query. I tryed but I couldn't do it. I tryed the following:
q=series:The Walking Dead or series:Game of Thrones or ...&wt=json

I think I'm doing wrong. What's the correctly way to do it?
Thanks in advance
Thiago

A: Try something like this:
 series:("The Walking Dead" OR "Game of Thrones")

A: In addition to @user1452132 's answer -
When you are searching q=series:The Walking Dead, only the is searched across the series field while the walking dead is search across the default search field.
The query formed would be series:the OR text:(Walking Dead)
You can debug the Query using the debugQuery=on in your request url.
You can use Dismax query handler to make it more manageable.

A: Use in fq parameter (filter query),
E.g
    name:("Java" OR "Python")
    name:("Java" AND "Web")

    // multivalued fields
    author_ids:(1733 OR 58)
    author_ids:(1733 AND 58)

Solr url encoding:

*

*':' become '%3A'

*space become '+'

Thus, you might get a url like this:

http://localhost:8983/solr/xxx/select?q=programming&fq=title%3A("Java"+AND+"web")&wt=json&indent=true&defType=edismax&qf=title&stopwords=true&lowercaseOperators=true

A: Depending on what the intent of the search is try the following two searches
series:"The Walking Dead" OR series:"Game of Thorns"
series:(The Walking Dead) OR series:(Game of Thorns)
Please read solr query syntax and the underlying Lucene query syntax

A: I think your the actual problem is using OR as lowercase. When you do something like that, The or value is searched in defaultTextField. Also don't forget to put quotes if there's a whitespace in your query - and you're looking for an exact match.


text:
Q: Помогите решить задачку по Ruby Напишите программу, которая рекомендует, как одеться сегодня.
В файлах лежат шмотки в формате:
название шмотки
тип шмотки
диапазон температур

Например,
шапка-ушанка из зайца
шапка
(-20, -5)

или
шлепанцы
ботинки
(+20, +30)

Программа спрашивает у пользователя, какая сейчас температура, а потом генерирует набор одежды, выводит название на экран (в консоль) по одной случайной шмотке каждого типа (если нашлась): шапка, шарф, кофта, куртка, штаны, ботинки, перчатки.
Уточнение:
Под диапазон может подходить по 2 или 3 шмотки каждого типа например:
валенки
ботинки
(-35, -15)

унты
ботинки
(-25, -15)

утепленные кроссовки
ботинки
(-25, -10)

и если пользователь введет -18 то выйдет все 3 типа, а нужен 1 случайный тип, нельзя пойти на улицу и надеть на утепленные кроссовки еще валенки сверху.
Какая сегодня температура?
-18

Рекомендуется надеть: шапку вязанную, шарф, куртка с мехом, джинсы с начесом, валенки.

Чтобы решить задачу я создал класс ClothesItem
class ClothesItem

  attr_accessor :title, :type, :line

  def initialize(path)
    File.open(path) do |file|
      arr = file.readlines
      @title = arr[0].chomp
      @type = arr[1].chomp
      @line = arr[2].chomp
    end
  end

  def in_interval?(t)
    int1, int2 = @line.gsub(/[() ]/, '').split(',')
    (int1.to_i..int2.to_i).include?(t)
  end
end

И вот моя не законченная основная программа (файлы положил в папку clothes)
require_relative 'clothes_item'

puts 'Какая сегодня температура?'
temperature = STDIN.gets.chomp.to_i

all_clothes = Array.new

Dir["#{File.dirname(__FILE__)}/data/*.txt"].each do |path|
  all_clothes << ClothesItem.new(path)
end

suit_clothes = Array.new
types_of_clothes = Array.new

all_clothes.each do |c|
  if c.in_interval?(temperature)
    types_of_clothes << c.type
    suit_clothes << [c.title, c.type]
  end
end

Не могу понять как сделать так, чтобы вывести на экран название шмотки 1 случайного типа одежды.
Я только учусь ruby знаю как синтаксис знаю много методов но у меня тут как то не хватает логики.

A: Ну ты правильно начал рассуждать. Тебе нужен класс для типа вещи.
Если рассуждать дальше - тебе нужен ещё и класс, для того, чтобы хранить и обрабатывать коллецию. Например такой:
class ClothesCollection

  attr_reader :collection

  def initialize(data_folder, item_class)
    @collection =
      Dir[File.join(data_folder, "*.txt")].map do |item_file|
        item_class.new(item_file)
      end
  end

  def by_temperature(temperature)
    typed_collection.each_value do |type_group|
      type_group
        .find_all { |item| item.in_interval?(temperature) }
        .example
    end
  end

  private

  def typed_collection
    @typed_collection ||= collection.group_by(&:type)
  end

end

Соответсвенно, использовать так:
collection =
    ClothesCollection.new(File.expand_path("data", __FILE__), ClothesItem)
collection.by_temperature(-5)

Оговорюсь: код далёк от идеала (например вложенные блоки не есть хорошо) и я не проверял его на работоспособность. Это просто пример.

A: Вот так получилось, не совсем изящно но все же сработало.
require_relative 'clothes_item'

puts 'Какая сегодня температура?'
temperature = STDIN.gets.chomp.to_i

all_clothes = Array.new

Dir["#{File.dirname(__FILE__)}/clothes/*.txt"].each do |path|
  all_clothes << ClothesItem.new(path)
end

suit_clothes = Array.new
types_of_clothes = Array.new

all_clothes.each do |c|
  if c.in_interval?(temperature)
    suit_clothes << c
    types_of_clothes << c.type
  end
end

recommended_clothes = Array.new

types_of_clothes.uniq.each do |type|
  for_rand_name = Array.new

  suit_clothes.each do |clothes_item|
    if type == clothes_item.type
      for_rand_name << clothes_item.title
    end
  end

  # для того чтобы не добавлять nil
  unless for_rand_name.empty?
    recommended_clothes << for_rand_name.sample
  end
end

puts "Сегодня, из вашего гардероба рекомендую одеть: #{recommended_clothes.join(', ')}."

Сделаю еще 1 класс как предложил anoam, думаю это прям будет вообще отлично.


text:
Q: When i Update Eclipse it Doesn't allow to create AVD even pressed ok still it is not creting AVD? I have updated my eclipse from help and check for new update  and now when I try to create a new AVD , Even when I press ok, nothing happens. As you can see ,my AVD shows repairable devices. But when clicked repair, nothing happens.

ANd When I try to create a new AVD Even after clicking OK nothing happens.
As you can see, ok is clickable. But when clicked nothing happens.

I have installed all the files through SDK manager under each version.
Any solution?

A: If you have updated your ADT to ADT 22.6 then i would suggest you to use lower version like ADT 22.3 or something else because this is a bug from Google side.
You can check more about this issue here in this link
https://code.google.com/p/android/issues/detail?id=66661
To download lower version visit this link
Cannot create or edit Android Virtual Devices (AVD) from Eclipse, ADT 22.6
and check update 5, there you will see download link for ADT 22.3.0

A: As many posts say this is a bug related to the new version of ADT, I did not want to rollback and test/use a different version. For me it worked by going directly in the Android SDK folder and launching the AVD manager (AVD Manager.exe) or from SDK manager -> Tools -> Manage AVDs. Meanwhile will wait for a fix related to the ADT plugin.


text:
Q: I cannot create a database in android I follow a example code but i cannot create my database i dont know why, in the emulator in folder there is not any database.This is my code
This is my main activity
public class T5Compras extends Activity {

      private EditText myEditText;
private ListView myListView;
private SimpleCursorAdapter cursorAdapter;
private Cursor cursor;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_t5_compras);

final ComprasDBAdapter comprasDBAdapter = new ComprasDBAdapter(this);

myEditText = (EditText) findViewById(R.id.txtAdd);
myListView = (ListView) findViewById(R.id.lstBuying);

myEditText.setOnKeyListener(new OnKeyListener() {

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if(event.getAction()==KeyEvent.ACTION_DOWN){
            if(keyCode==KeyEvent.KEYCODE_ENTER){

                comprasDBAdapter.open();
                comprasDBAdapter.insertProduct("jorge");
                myEditText.setText("");

                return true;
            }

        }

        return false;

    }
});

/*   ComprasDBAdapter comprasDBAdapter = new ComprasDBAdapter(getApplicationContext());
   comprasDBAdapter.open();
   cursor = comprasDBAdapter.getAllProductItemsCursor();

   cursorAdapter = new  SimpleCursorAdapter(getApplicationContext(), R.layout.lst_layout, cursor,
           new String[]{ComprasDBAdapter.KEY_PRODUCT,ComprasDBAdapter.KEY_ID}, new int []{R.id.list_txtProduct,R.id.list_txtId });
  */
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.t5_compras, menu);
    return true;
}

}
This is my class
      public class ComprasDBAdapter {
private static final String DATABASE_NAME = "listCompra.db";
private static final String DATABASE_TABLE = "productItems";
private static final int DATABASE_VERSION = 1;
private SQLiteDatabase db;
public static final String KEY_ID = "_id";
public static final String KEY_PRODUCT = "product";
private ComprasDBOpenHelper dbHelper;

public ComprasDBAdapter(Context _context) {
// TODO Crear una instancia de ComprasDBOpenHelper.
// Inicializar el CursorFactory a null para utilizar el que
// el sistema tiene por defecto.

ComprasDBOpenHelper comprasDBOpenHelper = new ComprasDBOpenHelper(_context, DATABASE_NAME, null, DATABASE_VERSION);

}

public void close() {
       db.close();

}

public void open() throws SQLiteException {
try
{
      db = dbHelper.getWritableDatabase();
}
catch (SQLiteException ex)
{
      db = dbHelper.getReadableDatabase();
}
}
// Insertar un producto

public long insertProduct(String _product) {
// TODO
    ContentValues cv = new ContentValues();
    cv.put("KEY_PRODUCT", _product);

    db.insert(DATABASE_TABLE, null, cv);

    return 0;
}
// Eliminar un producto según su ID

public boolean removeProduct(int _id) {
//TODO
    db.delete(DATABASE_TABLE, "KEY_ID='_id'", null);
return false;
}

// Actualizar el producto

public boolean updateProduct(long _rowIndex, String _product) {
// TODO
    ContentValues cv = new ContentValues();
    cv.put(KEY_PRODUCT, _product);
    db.update(DATABASE_TABLE, cv, "KEY_PRODUCT='_product'", null);
    return false;
}

public Cursor getAllProductItemsCursor() {
// TODO

return db.rawQuery("SELECT * FROM productItems", null);
}

private class ComprasDBOpenHelper extends SQLiteOpenHelper {

    public ComprasDBOpenHelper(Context context,
    String name,
    CursorFactory factory,
    int version)
    {

    super(context, name, factory, version);

    }
    // Sentencia SQL para crear la nueva base de datos.
    private static final String DATABASE_CREATE = "CREATE TABLE "
    + DATABASE_TABLE + " ("
    + KEY_ID
    + " integer primary key autoincrement, "
    + KEY_PRODUCT
    + " text not null)";
    @Override

    public void onCreate(SQLiteDatabase _db)
    {

    _db.execSQL(DATABASE_CREATE);

    }
    @Override

    public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion)
    {
    Log.w("ComprasDBAdapter", "Upgrading from version " +
    _oldVersion + " to " +
    _newVersion + ", which will destroy all old data");
    _db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
    onCreate(_db);
    }

}

}
When I try to insert some values my application is crashed and the logcat said that the error is in there I supposed that is database becasue database is not created
That is the logcat
06-16 06:45:08.331: E/AndroidRuntime(1066): FATAL EXCEPTION: main
06-16 06:45:08.331: E/AndroidRuntime(1066): java.lang.NullPointerException
06-16 06:45:08.331: E/AndroidRuntime(1066):     at com.imaginagroup.t5compras.ComprasDBAdapter.open(ComprasDBAdapter.java:43)
06-16 06:45:08.331: E/AndroidRuntime(1066):     at com.imaginagroup.t5compras.T5Compras$1.onKey(T5Compras.java:43)
06-16 06:45:08.331: E/AndroidRuntime(1066):     at android.view.View.dispatchKeyEvent(View.java:7200)
06-16 06:45:08.331: E/AndroidRuntime(1066):     at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1359)
06-16 06:45:08.331: E/AndroidRuntime(1066):     at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1359)
06-16 06:45:08.331: E/AndroidRuntime(1066):     at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1359)
06-16 06:45:08.331: E/AndroidRuntime(1066):     at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1359)
06-16 06:45:08.331: E/AndroidRuntime(1066):     at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchKeyEvent(PhoneWindow.java:1920)
06-16 06:45:08.331: E/AndroidRuntime(1066):     at com.android.internal.policy.impl.PhoneWindow.superDispatchKeyEvent(PhoneWindow.java:1395)
06-16 06:45:08.331: E/AndroidRuntime(1066):     at android.app.Activity.dispatchKeyEvent(Activity.java:2370)
06-16 06:45:08.331: E/AndroidRuntime(1066):     at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1847)
06-16 06:45:08.331: E/AndroidRuntime(1066):     at android.view.ViewRootImpl.deliverKeyEventPostIme(ViewRootImpl.java:3701)
06-16 06:45:08.331: E/AndroidRuntime(1066):     at android.view.ViewRootImpl.handleImeFinishedEvent(ViewRootImpl.java:3651)
06-16 06:45:08.331: E/AndroidRuntime(1066):     at android.view.ViewRootImpl$ViewRootHandler.handleMessage(ViewRootImpl.java:2818)
06-16 06:45:08.331: E/AndroidRuntime(1066):     at android.os.Handler.dispatchMessage(Handler.java:99)
06-16 06:45:08.331: E/AndroidRuntime(1066):     at android.os.Looper.loop(Looper.java:137)
06-16 06:45:08.331: E/AndroidRuntime(1066):     at android.app.ActivityThread.main(ActivityThread.java:5041)
06-16 06:45:08.331: E/AndroidRuntime(1066):     at java.lang.reflect.Method.invokeNative(Native Method)
06-16 06:45:08.331: E/AndroidRuntime(1066):     at java.lang.reflect.Method.invoke(Method.java:511)
06-16 06:45:08.331: E/AndroidRuntime(1066):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
06-16 06:45:08.331: E/AndroidRuntime(1066):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
06-16 06:45:08.331: E/AndroidRuntime(1066):     at dalvik.system.NativeStart.main(Native Method)

A: Change your ComprasDBAdapter constructor from
public ComprasDBAdapter(Context _context) {
// TODO Crear una instancia de ComprasDBOpenHelper.
// Inicializar el CursorFactory a null para utilizar el que
// el sistema tiene por defecto.

ComprasDBOpenHelper comprasDBOpenHelper = new ComprasDBOpenHelper(_context, DATABASE_NAME, null, DATABASE_VERSION);

}

to
public ComprasDBAdapter(Context _context) {
// TODO Crear una instancia de ComprasDBOpenHelper.
// Inicializar el CursorFactory a null para utilizar el que
// el sistema tiene por defecto.

dbHelper  = new ComprasDBOpenHelper(_context, DATABASE_NAME, null, DATABASE_VERSION);

}


text:
Q: OpenOffice Search Sheet Programmatically I have an Open Office/Excel spreadsheet (some people edit using Open Office, some with Excel, so needs to remain an XLS document). In this spreadsheet there are a number of sheets and hundreds of rows in each sheet.
I know the best way to proceed would be to use a database, but management don't like that idea (Time to build, test, retraining, quality control, backups, etc, etc)
So I want to know if its possible to have a 'Search sheet' in which someone types a word and it then lists all the rows containing that word (as in, copying the row to the 'search sheet') rather than having to use the built in search and constantly clicking 'Next'.
Your probably thinking "WTF?" right now, and rightly so, but at least this way, the people who want to save time can do so, and the people that prefer to look through every sheet for what they are looking for can also do. Everythings the same to the people who don't care, and no retraining moanings from management.

A: How about the best of both worlds and having something abstract? There are libraries around that can read XLS files, and I don't know if you know PHP, but a simple PHP front end to the XLS document could be done. Eg. google for 'excel_reader2.php'. You could then type in something to search for and the script will display those entries. When management recognise that its a good idea, you could use the same kind of script to convert it to a database (parse XLS doc -> populate SQL db).


text:
Q: Show selected images, webpage I am trying to show an image selected by the user from the list, but I do not see anything on the screen.

<!DOCTYPE html>

Images:

  <select id="ImSelect" size="6" onchange "getvalue()">
    <option value="LB_1_000561">LB_1_000561</option>
    <option value="LB_1_000562">LB_1_000562</option>
    <option value="LB_1_000563">LB_1_000563</option>
    <option value="LB_1_000564">LB_1_000564</option>
    <option value="LB_1_000565">LB_1_000565</option>
    <option value="LB_1_000566">LB_1_000566</option>
    <option value="LB_1_000567">LB_1_000567</option>
    <option value="LB_1_000568">LB_1_000568</option>
    <option value="LB_1_000569">LB_1_000569</option>
  </select>

A: That's because nothing ever calls your getValue function. You're onchange needs an = after it, as in onchange="getvalue()". But, you shouldn't be setting up event handlers in HTML in the first place. You need that function to be called whenever you make a selection in your select, so a change event handler needs to be set up for it and that handler should be set up in JavaScript.
Also, you are trying to set the src of your image before you've created it. You need to swap those two lines.
Additionally, you don't have a head section to your document and your style element should go in there, rather than in body.
Finally, your code will create a new image and append it to the document every time a selection is made, so you could wind up with many images showing. If you only want one image showing (the most recently selected one), then instead of creating a new image and appending it to the document, just create a static img element in the page, where you want it, but don't set its src in the HTML. Then, all your JavaScript needs to do is access that pre-existing image and set its src instead of generating a new one an appending it.

<!DOCTYPE html>

Images:

    <select id="ImSelect"  size="6">
      <option value="LB_1_000561">LB_1_000561</option>
      <option value="LB_1_000562">LB_1_000562</option>
      <option value="LB_1_000563">LB_1_000563</option>
      <option value="LB_1_000564">LB_1_000564</option>
      <option value="LB_1_000565">LB_1_000565</option>
      <option value="LB_1_000566">LB_1_000566</option>
      <option value="LB_1_000567">LB_1_000567</option>
      <option value="LB_1_000568">LB_1_000568</option>
      <option value="LB_1_000569">LB_1_000569</option>
    </select>


text:
Q: Locust Websocket Sends and receives data, but fails to repeat the action for concurrent users The application works on a two step process, I send data to initialize conversation via a unique wss and receives some data back. I then send another message/data to a different wss uri to await a response. This requires two websockets connection. When I simulate of a single user it works, but fails to execute multiple users. Error, socket already closed.
class WebsiteUser(WebsocketLocust):
  root="wss://xxxx.com/"
  uri_start_conversation = "".join([root, "/xxx?bot_integer_id=xx"])
  url = uri_start_conversation
  user_id = "some id"
  uri_send_audio = "".join([root, "messages/", user_id, "/ws/bot/xxx?bot_integer_id=xx"])
  print(uri_send_audio)

  @task
  def conversation(self):
     while True:
        recv = json.loads(self.client.recv())
        print(recv)
        question = int(recv.get("reply")[0].split("|")[0])
        send_audio_file = audio_files(index_value=question) # binary data
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop.run_until_complete(self.speech(get_url=self.uri_send_audio, user_id=self.user_id, message=send_audio_file)))

  def on_start(self):
     websocket.enableTrace(True)
     self.client.connect(self.url)
     self.data = {
        "user_id": self.user_id,
        "message": "",
        "source": "web"
    }
     msg = json.dumps(self.data)
     self.client.send(msg)

  async def speech(self, get_url: str, user_id: str, message):
     Flag = True
     print(Fore.YELLOW + "[speech] wss")
     ws = create_connection(get_url) # audio wss
     print(Fore.GREEN + "[audio] wss")

     async with websockets.connect(get_url) as ws:
        while Flag:

            msg = await ws.send(message)
            #logging.info("{} audio_send".format(user_id))
            packet = await ws.recv()

            #logging.info("{} audio_response".format(user_id))
            packet = json.loads(packet)

            if (packet["reply"] != ["Complete"]):
                question = int(packet.get("reply")[0].split("|")[0])
                message = audio_files(index_value=question) # binary data
            else:
                Flag = False # end of conversation


text:
Q: Program compiling and running, but not working? I had some problems with this code, got some help and it was working fine. Proceeded to do some tweaking and now the program compiles and runs, but it's not doing what it is supposed to do (take in a c++ file, remove the comments, and print out a new file). It is not printing out a new file...any ideas what I messed up?
#include <iostream>
#include <fstream>
#include <string>
#include <cassert>
#include <cstdio>

using namespace std;

void remove_comments (ifstream& , ofstream&);

int main(void)
{
  int i;
  string inputFileName;
  string outputFileName;
  string s;
  ifstream fileIn;
  ofstream fileOut;
  char ch;

  do
  {
    cout<<"Enter the input file name:";
    cin>>inputFileName;
  }
  while (fileIn.fail() );
  cout<<"Enter the output file name: ";
  cin>>outputFileName;

  fileIn.open(inputFileName.data());
  assert(fileIn.is_open() );
  remove_comments ( fileIn , fileOut);

  fileIn.close();
  fileOut.close();

  return 0;
}

void remove_comments( ifstream& fileIn , ofstream& fileOut)
{
  string line;
  bool flag = false;

  while (! fileIn.eof() )
  {

    getline(fileIn, line);

    if (line.find("/*") < line.length() )
      flag = true;
    if (! flag)
    {
      for (int i=0; i < line.length(); i++)
      {

        if(i<line.length())
          if ((line.at(i) == '/') && (line.at(i + 1) == '/'))
          break;
          else
            fileOut << line[i];
      }
      fileOut<<endl;

  }
  if(flag)
  {
    if(line.find("*/") < line.length() )
      flag = false;
  }

}
}

A: You forgot to open the output stream file using std::ofstream::open:
fileOut.open(outputFileName);

also notice that std::ifstream has an overload for open that takes an std::string by constant reference, so:
fileIn.open(inputFileName.data());

can become:
 fileIn.open(inputFileName);

A: Why won't you get parameters from command line?
it would be much simple.
void remove_comments (ifstream& , ofstream&);

int main(int argc, char** argv)
{
  if(argc!=3){
    cerr<<"usage: "<<argv[0]<<" input.file output.file\n";
    return -1;
  }
  int i;
  string inputFileName=argv[1];
  string outputFileName=argv[2];
  string s;
  ifstream fileIn(inputFileName.c_str());
  if(!fileIn.is_open()){
     cerr<<"error opening input file\n";
     return -1;
  }
  ofstream fileOut(outputFileName.c_str());
  if(!fileOut.is_open()){
     cerr<<"error opening Output file\n";
     return -1;
  }
  remove_comments ( fileIn , fileOut);

  return 0;
}


text:
Q: Does anyone know a good pastebin where I can easily pickup the code with curl? I'm in a domU with nothing but a console to work with an internet connection.
I need to configure a file in it that I feel is too long to just type by hand.
So I want to pick it up from somewhere else instead.
The first and only thing that has come up to me is pastebin + curl, but I don't know any pastebins that show it's pastes naked.
There's always html stuff surrounding it.

A: Try Bitbucket snippets: from the link, scroll to heading=Rich set of APIs. That links to, e.g., curl-based API to put a snippet and get a snippet.


text:
Q: How do you copy over an array of no elements to an output file so that it contains an empty array? I know that you can do this if you have elements in your array:
FILE *ptr;
ptr = fopen( bobby.txt , "wb" );
int array[3] = {1,2,3};
fwrite(array, sizeof(int), 3, ptr );
fclose(ptr);

but, when we come across corner cases like an empty array, how would we copy an empty array into a file? Would it look something like this?
FILE *ptr;
ptr = fopen( bobby.txt , "wb" );
int array[0] = {};
fwrite(array, sizeof(int), 0, ptr );
fclose(ptr);

EDIT:
if the array was null would that also count as an empty array?

A: fopen( bobby.txt , "wb" );
This is wrong.
fopen( "bobby.txt" , "wb" );
The array has nothing in it and your are trying to copy nothing to a file?
This sounds contradictory. When there is nothing in the array don't write it to a file.
If you want to check whether the file exists or not check the below link.
What's the best way to check if a file exists in C? (cross platform)


text:
Q: HTML Bullet point with no indent I'm creating an html email and want to create bullet points without indent.
Because it's an email it has to be html and inline CSS. Is there a way to edit your bullet settings? These are multi line bullets.

A: You can assign a choice of two properties to alter position of bullet points:

list-style-position: outside;
list-style-position: inside;
Then adjust padding accordingly.
See this example on Codepen.
You will still need to deal with display differences within individual email clients however.

A: Just set the ULs margin and padding to zero.

A: Unordered list tag has a default padding assigned to it, you can override it by giving margin-left: -10px css. this should resolve your issue.
On giving a 0px padding you will end up losing your bullets.
Thanks

A: Just put • at the start of the line, instead of a list:
• List item here

• Another list item here

Renders as:
• List item here
• Another list item here
This way you can be sure it will be consistent across email clients.


text:
Q: Best practice for setting the default value of a parameter that's supposed to be a list in Python? I have a Python function that takes a list as a parameter. If I set the parameter's default value to an empty list like this:
def func(items=[]):
    print items

Pylint would tell me "Dangerous default value [] as argument". So I was wondering what is the best practice here?

A: For mutable object as a default parameter in function- and method-declarations the problem is, that the evaluation and creation takes place at exactly the same moment. The python-parser reads the function-head and evaluates it at the same moment.
Most beginers asume that a new object is created at every call, but that's not correct! ONE object (in your example a list) is created at the moment of DECLARATION and not on demand when you are calling the method.
For imutable objects that's not a problem, because even if all calls share the same object, it's imutable and therefore it's properties remain the same.
As a convention you use the None object for defaults to indicate the use of a default initialization, which now can take place in the function-body, which naturally is evaluated at call-time.

A: Use None as a default value:
def func(items=None):
    if items is None:
        items = []
    print items

The problem with a mutable default argument is that it will be shared between all invocations of the function -- see the "important warning" in the relevant section of the Python tutorial.

A: I just encountered this for the first time, and my immediate thought is "well, I don't want to mutate the list anyway, so what I really want is to default to an immutable list so Python will give me an error if I accidentally mutate it." An immutable list is just a tuple. So:

  def func(items=()):
      print items

Sure, if you pass it to something that really does want a list (eg isinstance(items, list)), then this'll get you in trouble. But that's a code smell anyway.

A: In addition and also to better understand what python is, here my little themed snippet:
from functools import wraps
def defaultFactories(func):
    'wraps function to use factories instead of values for defaults in call'
    defaults = func.func_defaults
    @wraps(func)
    def wrapped(*args,**kwargs):
        func.func_defaults = tuple(default() for default in defaults)
        return func(*args,**kwargs)
    return wrapped

def f1(n,b = []):
    b.append(n)
    if n == 1: return b
    else: return f1(n-1) + b

@defaultFactories
def f2(n,b = list):
    b.append(n)
    if n == 1: return b
    else: return f2(n-1) + b

>>> f1(6)
[6, 5, 4, 3, 2, 1, 6, 5, 4, 3, 2, 1, 6, 5, 4, 3, 2, 1, 6, 5, 4, 3, 2, 1, 6, 5, 4, 3, 2, 1, 6, 5, 4, 3, 2, 1]
>>> f2(6)
[1, 2, 3, 4, 5, 6]


text:
Q: MySQL. Way to compose query with "LIKE" which will work similar as url regular expression for example I have table 'urls'
urls:
___________________________________________
|   id   |              href              |
+--------+--------------------------------|
|    1   | /a/b/c/d/e/f/g/                |
+--------+--------------------------------|
|    2   | /a/b/g/                        |
+--------+--------------------------------|
|    3   | /a/c/g/                        |
+--------+--------------------------------|
|    4   | /a/d/g/                        |
+--------+--------------------------------|
|    5   | /a.php?code=g                  |
+--------+--------------------------------|
|    N   | anyUrlString                   |
+--------+--------------------------------|

I wanna select urls which have special format, for example (like ROUTE in popular PHP frameworks)
"/a/@anyparam/g"

so: WHERE href LIKE '/a/%/g'
but it also will select row with id 5, 1..
How to compose LIKE statement to I can get only URI enabled values in @anyparam ?
must be something like this /a/[%, but not ('/','?','\')]/g but what exactly?
Thanks for any proposition!
P.S. Do not propose to use regular expression (it don't use indexes)!

A: Can you use multiple clauses?
 LIKE '/a/%/g' AND NOT LIKE '/a/%?%/g' ....

Chain some "exceptions" together, attacking cases that do not match.  It's hard to come up with a general case, with your limited sample set.  An EXPLAIN will show if Indexes are still in use.

A: String and pattern taken from your code:
SELECT 1 WHERE '/a.php?code=g' LIKE '/a/%/g'

^ should not give you anything, since the string your testing doesn't end in /g, it ends with =g.
But an often overlooked ability of LIKE is negative character-classes. Unfortunately they are not variable-length, they always only represent 1 character, but you could REPEAT() them:
LIKE '/a/' + REPEAT('[^/?\]', LEN(@someVar)) + '/g'


text:
Q: How can I improve performance of TextIO or AvroIO when reading a very large number of files? TextIO.read() and AvroIO.read() (as well as some other Beam IO's) by default don't perform very well in current Apache Beam runners when reading a filepattern that expands into a very large number of files - for example, 1M files.
How can I read such a large number of files efficiently?

A: When you know in advance that the filepattern being read with TextIO or AvroIO is going to expand into a large number of files, you can use the recently added feature .withHintMatchesManyFiles(), which is currently implemented on TextIO and AvroIO.
For example:
PCollection<String> lines = p.apply(TextIO.read()
    .from("gs://some-bucket/many/files/*")
    .withHintMatchesManyFiles());

Using this hint causes the transforms to execute in a way optimized for reading a large number of files: the number of files that can be read in this case is practically unlimited, and most likely the pipeline will run faster, cheaper and more reliably than without this hint.
However, it may perform worse than without the hint if the filepattern actually matches only a small number of files (for example, a few dozen or a few hundred files).
Under the hood, this hint causes the transforms to execute via respectively TextIO.readAll() or AvroIO.readAll(), which are more flexible and scalable versions of read() that allow reading a PCollection<String> of filepatterns (where each String is a filepattern), with the same caveat: if the total number of files matching the filepatterns is small, they may perform worse than a simple read() with the filepattern specified at pipeline construction time.


text:
Q: Output pdf file shows empty references after inserting BibTeX in Lyx 2.0.5 My output pdf file shows empty references after inserting BibTeX in Lyx 2.0.5. The BibTeX file is created by JabRef 2.9.2 and I am using Windows 7.

A: You have run into this 7 year old bug that will be fixed for LyX 2.1 (beta to be released soon). bibtex is probably trying to tell you what's wrong but LyX is not passing that information on. To see the bibtex log, export to LaTeX (pdflatex) and compile manually with pdflatex and bibtex. If you don't understand the error, post it here. And yes, similar to what Papiro says, please post a LyX minimal example.
EDIT: note that the bug was not fixed for LyX 2.1. It was viewed as too intrusive of a change. Many users had documents were compiling and were upset when suddenly they received errors. See the ticket (click on "this" above) for more information.


text:
Q: Solving for Ellipse Parameters Given a radius and angle (Challenge 2) Given an ellipse centered on the origin in an x-y plane expressed as
$$\bigg(\frac{x}{a} \bigg)^2+\bigg(\frac{y}{b} \bigg)^2 = 1$$
In polar coordinates with radius $R$ and angle = $\theta$, this can be expressed as:
$$R = \sqrt{\big(a^2 cos^2\theta\big)+\big(b^2 sin^2\theta\big)}$$
If we set a and b to be related as follows:
$a = 1 - \Delta$
$b = 1 + \Delta$
The solution for $\Delta$ as a function of $R$ and $\theta$ is determined from
$$R = \sqrt{1 - 2\Delta cos(2\theta)+ \Delta^2}$$
Which as given in Solving for Ellipse Parameters given a radius and angle (Challenge 1)
has the simplest solution as $$\Delta = cos(2\theta) \pm \sqrt{R^2-sin^2(2\theta)}$$
I am trying to similarly solve for $\Delta$ given a modified ellipse with the following relationship:
$$R = (1-\Delta)\sqrt{1 - 2\Delta cos(2\theta)+ \Delta^2}$$
What is the simplest form of $\Delta$ given $R$ and $\theta$ from the above equation?
If a simple relationship does not exist, then an approximation will be acceptable given that I can limit $\Delta$ to be $0.9<\Delta<1$
(Note this is related to my answer at this link on the signal processing site where I had to find the root of the equation to solve but am hoping for a simple closed form equation: https://dsp.stackexchange.com/questions/54006/computation-of-parameter-filter-to-match-a-given-frequency-response/54008#54008)

A: Squaring both sides gives
$$R^2 = (1 - \Delta)^2 (\Delta^2 - 2 \Delta \cos 2 \theta + 1) .$$
This is a quartic equation in $\Delta$, so there is a closed form in terms of $R, \theta$, but it's too large to reproduce here: For general values of $\theta, R$ there won't be a simple form, and given the content of the linked post, the numerical approximations you've already been using are probably the most useful. If you're interested in limiting cases, say, $R \ll 1$ or $R \gg 1$, one can analyze the above equation to produce good approximate solutions for $\Delta$.
Edit If we have the additional condition that $R \ll 1$, then substituting gives $\Delta \approx 1$. To get a next-order approximation, we can set $\Delta = 1 + \epsilon$ with $\epsilon \approx 0$ (this is close to the condition specified in the edit to the original question), giving $$\epsilon^4 + 4 \sin^2 \theta \, \epsilon^3 + 4 \sin^2 \theta \, \epsilon^2 = R^2 .$$ Provided that $\sin \theta$ is not too close to $0$, the $\epsilon^2$ term on the left dominates the others, giving $$\epsilon \approx \pm \frac{R}{2} \csc \theta,$$
so
$$\Delta \approx 1 \pm \frac{R}{2} \csc \theta .$$
On the domain $\frac{9}{10} < \Delta < 1$ of interest, this is a robust approximation:

From innermost to outermost, the red curves are the graphs of the solution functions $\Delta(\theta)$ for $R = \frac{1}{8}, \frac{1}{16}, \frac{1}{32}, \frac{1}{64}, \frac{1}{128}$, and the blue curves are the graphs of the above approximations.
On the other hand, for very small $R$, say, $R < \frac{1}{64}$, it's possible for to have $\frac{9}{10} < \Delta < 1$ but $\sin \theta$ small enough that the above approximation becomes poor: In the limit $\sin \theta \to 0$, the $\epsilon^4$ term dominates, giving a zeroth-order approximation $\Delta \approx 1 - \sqrt{R}$. Computing to second order in $\sin \theta$ gives the approximation $$\Delta \approx 1 - \sqrt{R} + \left(1 - \frac{1}{\sqrt{R}}\right) \sin^2 \theta .$$

This plot for $R = \frac{1}{256}$ is typical for $R < \frac{1}{100}$; the green curve is the small-angle approximation. (NB the expanded scale of the horizontal axis.)


text:
Q: MySQL | PHP - Gather rows by two different date I have a table like this (where 'date' is when the user ask for a validation and 'date_validation' is when it's validated:
id | type | date | date_validation | equipement_id

I can sort it by date or rather date_validation by a simple sorting and by doing some PHP code.
Display I have
12/06/17
ID '1', Ask for validation
ID '2', Ask for validation
12/06/17
ID '3', validated
10/06/17
ID '4', Ask for validation
10/06/17
ID '5', validated
Display I would like to have
12/06/17
ID 1', Ask for validation
ID '2', Ask for validation
ID '3', validated
10/06/17
ID '4', Ask for validation
ID 5', validated

How to gather informations by date, while having two different date column?

A: I think you are looking for this :
SELECT id,  date as dt, 'Ask for validation' AS DtTtype
FROM thetable
UNION ALL
SELECT id,  date_validation  as dt, 'validated' AS DtType
FROM thetable
ORDER BY dt

In the PHP, break on the dt field, and the dttype field  give you what type of date it is


text:
Q: How to read fast with Python from MS SQL How to fast search specific data in MS SQL with Python if you have three dependent variables and you have 10 million data? If prepare use pyodbc library or any else?

A: Starting from the fact that 10 million rows for a table in a RDBMS is not a huge number, I personally used TurboODBC with MSSQL to migrate a table with ~2 billion rows. I was very satisfied.
You should carefully review and optimize your query/schema (adding indexes, exploiting them, etc.) regardless of the technology you will use to run it. Most likely the database query execution will be the bottleneck of your process (assuming that you will not process this data in python).

A: Using a columnstore index is appropriate for high volume of data/rows in a table (many millions at least). If your criterias for the WHERE cluse of the SELECT are the 3 variables, create such index with those three columns. As an hypothetical exemple :
CREATE COLUMNSTORE INDEX XC_MyTable ON MyTable (Col1, Col2, Col3);


text:
Q: Why is simple_form not creating my fields and creating hidden fields instead? This is my ruby code:
<%= simple_form_for([@video, @video.comments.new]) do |f| %>
  <% f.association :comment_title %>
  <% f.input :body %>
  <% f.button :submit %>
<% end %>

This is the generated HTML markup:
<form accept-charset="UTF-8" action="/videos/485/comments" class="simple_form comment" id="new_comment" method="post">
    <div style="margin:0;padding:0;display:inline">
        <input name="utf8" type="hidden" value="✓">
        <input name="authenticity_token" type="hidden" value="55xSU8JUe1SgipjAkAEvCvidFdJY3hv8Qz5VBqUSrdE=">
    </div>
    <input class="button" id="comment_submit" name="commit" type="submit" value="Create Comment">
</form>

Obviously it's not creating the :body input field and the association select list correctly. Why is this and how can I fix it?
Btw, a video has many comments, and a comment belongs to video. Also, a comment_title has many comments, and a comment belongs to a video. Comment_title is generated with virtual attributes.
Please let me know if there is any other code you would like to see.

A: Both of these are because of choices in your rails application.  The first is that you have selected to configure the application to use utf8 for character encoding.  The second is because by default the application is setup to protect against cross site request forgery attacks.  The authenticity token ensures that the response coming back to the server when the user submits the form is actually from you and not some other source just watching your traffic and posting away to mess with your database.

A: Ok so the problem was that I needed to add the "=" to <%= in my form elements.


text:
Q: CFWheels: Form helpers coding the old way not working I have a simple form that is suppose to show one field.
Controller:
public function t_validate_3()
        {
            title = "Complete";

            supervisor = model("supervisors").new();

        }

View 1: Using Form helpers (work)
<cfoutput>

#startFormTag(action="t_validate")#

        #textField(label="Supervisor Name:", objectName="supervisor", property="name")#
        #errorMessageOn(objectName="supervisor", property="name")#

    #submitTag()#

#endFormTag()#

</cfoutput>

View 2: Using Plain old HTML (doesn't work)
<cfoutput>

    #startFormTag(action="t_validate_3")#

            Supervisor:
            <input id="Name" name="supervisor[name]" value="#supervisor.name#" />
            #errorMessageOn(objectName="supervisor", property="name")#

        #submitTag()#
    #endFormTag()#

</cfoutput>

The error above is "Element NAME is undefined in SUPERVISOR." This error comes from the line "#supervisor.name#". Keep in mind, I know initially it is empty but I need that line so it remembers the value if it is filled. I got the idea from the documentation;
http://docs.cfwheels.org/docs/form-helpers-and-showing-errors
However it doesn't seem to work. Is there a way for the form to ignore if it empty but remember if it is filled without this error.
Please help.