R - lmer vs glmer

Question: Having trouble finding straightforward information this topic.
Basically, I'm trying to use the lme4 package to analyze my data, and the model looks something like (A ~ BCD) + (random effects term 1) + (random effects term 2).
'A' is a yes/no response, which, based on what I've read, indicates that I should use glmer(). However, my experiment uses repeated measures - each subject undergoes many trials. It's a psychophysical experiment, so there are many subjects who essentially make yes/no judgements about many, many images. I've read that when there are many trials within a subject, you should use lmer().
Sorry if the info given is too sparse; if anyone thinks they can help me out with this, I'll provide as much info as necessary.
Question: When exactly should one use lmer() vs glmer(), especially in the context of psychophysical experiments where one subject will undergo many trials with binomial outcomes?
More info/part 2 of question: I initially analyzed my data using ANOVAs in SPSS. The SPSS indicated a highly significant interaction, one that is logical and predicted. When running the same data to modeled in glmer(), that interaction in highly insignificant. When running through lmer, it is significant again.
If anyone can help shed some light on whether this makes sense or why it would be so, I'd appreciate it very much.
Comment: Does, in your case, repeated measure mean that you have measured `A` at different time points (say, every 6 months over a period of 2 years)? I don't see why you would model a binary response in growth models (first two time points a person answered "yes", the last two time points "no"). If you are saying that subjects make judgements many times, perhaps your response is always a different one?
Comment: No, not measured at different time points. It means each subject makes a response about similar images featuring different conditions. Specifically, there are hundreds of images featuring a target that can vary in size and position. For each image, the subject has to decide whether the target is on the left or the right side of the screen, so their response is correct/incorrect. Whether or not they correctly detected the stimulus would depend on 3 things: age (between-subjects factor) and target size/position (within-subjects factors)
Comment: So what is your dependent variable? You don't want to run hundreds of models, one per image, where the response "correct/incorrect" for this image is used as dependent variable?
Comment: What exactly are your `lmer` and `glmer` model formulas? Also, please provide output from `str(data)` and head(`data`). It sounds like you have repeated measures on subjects but without more information it is hard to advise. Also, do different subjects make judgements on the same images ?
Comment: @Daniel - The dependent variable is the subject response. The independent factors are the size and position of the stimulus, as well as the age group of the subject. In a simple ANOVA, actually the medians of each condition were first calculated and then compared. I think this part of my confusion - I'm not sure if my data is truly binary, when we're often actually working with these "response accuracies" that are calculated from binary responses.
Comment: @Daniel - (cont'd)  I.E., say there are 6 conditions. For each condition, the subject sees 100 similar images and inputs a binary response. Then, for each condition, an average or median is calculated as a proportion correct. If the proportion correct is treated as the outcome, is the data more continuous?
Comment: The dependent variable ist always a subject response. It's important to know, which question or item could be the dep. var., or what you would like to find out. To me, it seems that you are indeed looking for modeling the proportion of correct answers, which is on a continuous scale. Just because you "repeat" questions, it is not a repeated measure. In this case, repeated measure would mean that you repeat the complete trial over X years and see how the proportion of correct answers changes within this time span. However, if you calculate the average/median proportion of correct inputs...
Comment: (cont'd) I wonder whether size and object of the image differs for each image, and if so, does this have an impact on computing the median/average? It sounds like you are calculating a "score" of correct responses, and this score - however it is weighted by size and position - is your dependent variable. You could then run a random-intercept model, but currently I'm not sure that you need a repeated measure or growth model design.
Answer: lmer is used to fit linear mixed-effect models, so it assumes that the residual error has a Gaussian distribution. If your dependent variable A is a binary outcome (e.g. a yes/no response), then the error distribution is binomial and not Gaussian.
In this case you have to use glmer, which allow to fit a generalized linear mixed-effects model: these models include a link function that allows to predict response variables with non-Gaussian distributions. One example of link function that could work in your case is the logistic function, which takes an input with any value from negative to positive infinity and return an output that always takes values between zero and one, which is interpretable as the probability of the binary outcome (e.g. the probability of the subject responding 'yes').
About the repeated measurement design, both lmer and glmer can handle it equally well, you just have to set 'subject' as a grouping factor (in the random-effect part of the model) for the within-subject predictors. In this way you allow these predictors to have a fixed-effect (common to all subjects) and a subject-specific random effect, so that you can test statistically the effect common to all subjects, and treat the subject-specific variations as a nuisance term.
For more details on how to proceed I would recommend this excellent book by Knoblauch and Maloney that dedicates a large section on the application of mixed-effects models (using R and the lme4 library) to the modelling of psychophysical data.
Comment: I suggest you to read carefully the documentation about the functions `glm` and `glmer`. You will see that you can set the link function through the `family` argument of the function. For example to fit a logistic model you should set it to `family=binomial(link = "logit")`
Comment: It isn't t surprising that also `lmer` find a significant interaction, especially if the effect is large. Nevertheless a linear regression fit (such as `lmer`) is wrong when your data is binomial (i.e. a binary outcome). It would violate the assumptions of the linear models (which assume that the outcome variable is continuous, the residual are normally distributed with constant variance, and so on). Even if the linear regression might result in similar parameter estimates, the estimated standard error for these parameters will be invalid, and might lead to erroneous inferences.
Comment: Thanks so much for this response and the book recommendation, they're both very helpful. How would I go about applying the link function? Also, do you have any insight as to the second part of my question (under the tl;dr?)
Comment: I know this is an old post but you may want to use signal detection theory to analyze this type of data. If you calculate the sensitivity (d') and Bias (c) of each individual over all the stimuli for each session, you can analyze their sensitivity to the stimulus and their bias for selecting left or right. This is will not tell you the same thing as a raw analysis of your data, instead, this will tell you more about how well an individual was able to detect the stimulus and not just percentages.
Comment: A probit GLM would be exactly equivalent to a (Gaussian, equal-variance) SDT analysis; see here [mlisi.xyz/files/SDT_GLM.pdf](https://mlisi.xyz/files/SDT_GLM.pdf), although of course there's more to SDT than Gaussian-equal-variance models

R - lmer vs glmer


wp_enqueue_script não funciona

Question: Estou criando um tema para WordPress, porém o wp_enqueue_scripts não funciona. O código que está no functions.php é:
<?php
function scripts_and_styles() {

  if ( ! is_admin() ) {
      wp_enqueue_script( 'jquery' );
      wp_register_style( 'style.css',get_template_directory_uri().'/style.css' );
      wp_enqueue_style( 'style.css' );
      wp_register_style( 'bootstrap.min.css','https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css' );
      wp_enqueue_style( 'bootstrap.min.css' );
    }
}

add_action('wp_enqueue_scripts', 'scripts_and_styles');
?>

Outras informações que talvez ajudem a identificar o que está acontecendo:

Quando insiro echo 'Oi!'; aparece Oi! no index.php, como esperado;
Tenho que inserir no header.php o <?php do_action('wp_enqueue_scripts') ?>, e pelo que havia entendido isto não seria necessário;
Quando uso var_dump no wp_enqueue_script( 'jQuery' ); e nos outros wp_enqueue_script() é 'impresso' NULL no index.php;
Nada que use jQuery funciona no meu tema (Creio que porque eu não consiga chamá-lo);
Eu utilizo o XAMPP.

Só para deixar mais claro: Não é só o jQuery que não funciona, nada é incluso. Não chama nem estilo e nem script. Tenho ciência que o jQuery vem incluso no Wordpress e que tenho que apontar caso algum script dependa dele.
Comment: O que você precisa fazer que depende do jQuery? Quando aos styles, acredito que o handle esteja incorreto por conter a extensão do arquivo (mas não sei, não testei). Ainda sobre os styles, recomendo que você sirva uma cópia local do bootstrap, e não a partir de um cdn, esse downtime *pode* estar causando algum problema.
Comment: @CaioFelipePereira Muito obrigado pela disposição, mas o erro era outro faltava wp_head() e wp_footer()!
Answer: O jQuery, assim como vários outros scripts, já vem incluso no core do WordPress, e eles funcionam on-demand, ou seja, apenas quando são necessários.
O que acontece é que, dentro da lógica do WP, você pode criar scripts dependentes de outros scripts sem se preocupar com a ordem de inclusão. Você apenas deixa clara a dependência que um script tem do outro, e deixa que o WP faça a inclusão na ordem correta.
Imagine que você tenha um script animacoes.js (que é dependente do jQuery), e você quer incluí-lo na sua página. Como o jQuery já existe no WP, você não precisa se preocupar com ele (que é o caso da primeira linha da sua condição !is_admin(). O que você precisa fazer é dizer pro WP que essa dependência existe, e que ele faça a inclusão, da seguinte maneira:
 wp_register_script('animacoes', get_template_directory_uri() . '/js/animacoes.min.js', array('jquery'), '1.0', true);

Veja que aqui estou apenas registrando o script. Não estou fazendo a inclusão do mesmo propriamente dita. O método wp_register_script() recebe alguns parâmetros, que são:

O nome do handler do seu script. (A partir desse ponto, é esse nome que você vai referenciar no seu código);
O caminho do script;
Um array contendo os handlers das dependências. Veja que o handler do jQuery é jquery, com a letra q em caixa baixa. Caso você tenha mais de uma dependência, basta que você a inclua neste array;
A versão do seu script
Um bool para colocá-lo ou não no rodapé da página.

Depois de registrado, basta enfileirar-lo, usando o método wp_enqueue_script(), da seguinte maneira:
wp_enqueue_script('animacoes');

Onde o parâmetro é o handler do script previamente registrado.
O WordPress tem o cuidado de trabalhar com o jQuery no modo noConflict, em virtude de outras bibliotecas que podem usar o $ e mais uma série de motivos que não vem ao caso. Você pode ter tentado abrir o console no seu site e rodado $('html').addClass('classe') (ou basicamente qualquer outra coisa usando o método $()), e ter acabado recebendo um $ is not defined. Isso ocorre justamente por conta desse modo. Se você rodar jQuery('html').addClass('classe'), vai ver que tudo dá certo.
Para contornar esse fato, e usar $ sem problema no seu script animacoes, você pode fazer algo como o seguinte:
//animacoes.js
(function($){

    $('html').addClass('class');
    // code...

}) (jQuery);

Basicamente, dentro desse script, você está dizendo que $ deve ser resolvido pelo jQuery.
Essa é a maneira mais habitual de se trabalhar com scripts dentro do WP. Pode até parecer meio estranho no inicio, mas você pega o jeito logo logo. Lembre-se em sempre usar o que a ferramenta já disponibiliza. Trabalhar registrando e "desregistrando" scripts pode acabar sendo altamente não produtivo.
Comment: Não era isso que eu queria, mas votei pela sua disposição, descobri o erro! É muito elementar, faltava o wp_head() e o wp_footer() !
Comment: @RafaelFD Acontece! Depois dessa vc nunca mais esquece.
Answer: Solucionei o problema adicionado o wp_head() e o wp_footer()!
Answer: Tenta fazer dessa forma:
wp_deregister_script( 'jquery' ); // remove o registro se houver
wp_register_script('jquery', ("http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"), false);
wp_enqueue_script('jquery');

Comment: eu tentei não funciona nada do tipo, mas mesmo assim, agradeço por ter dedicado seu tempo buscando ajudar!

wp_enqueue_script não funciona


An everywhere differentiable function needs to be continuous?

Question: I know that all absolutely continuous functions are differentiable almost everywhere. Is the converse true?
Or a better question: If $f$ is an almost everywhere differentiable function, what is the regularity of $f$?
Comment: The Heaviside function is differentiable almost everywhere, and definitely not continuous.
Comment: Differentiability implies continuity.
Comment: https://en.wikipedia.org/wiki/Absolute_continuity By this the converse is not necessarily true since the set of absolute continuous functions is the subset of the set of almost everywhere differentiable functions, but not vice versa.
Comment: Of corse. But, what about almost everywhere differentiability?
Comment: Thanks!...Therefore I conclude that an almost everywhere differentiable function f is continuous almost everywhere. Now, could $f$ be continuous at every irrational numbers and discontinuous at every rational numbers?; I think this not hapen because we need that $\lim_{h \rightarrow 0} \frac{f(x-h)-f(x)}{h}$ has sense when $h$ is small for almost every $x$ in the domine of $f$. Am I right?
Answer: I think it is possible for the function to be discontinuous on a dense set, and differentiable almost everywhere.  Here is my example.
Let $f_n(x) = 2^{-n} [2^n x]$, that is, the least multiple of $2^{-n}$ less than or equal to $x$.  Note that for any $x,y$ we have $|f_n(x) - f_n(y)| \le |x-y| + 2^{-n}$.
Let
$$ g = \sum_{n=0}^\infty 2^{-2n} f_n .$$
Clearly $g$ is discontinuous at numbers of the form $\frac{k}{2^n}$.
Let
$$ E_n := \bigcup_{k=0}^{2^n-1} [\tfrac k{2^n} + \tfrac1{2^{2n}}, \tfrac {k+1}{2^n} - \tfrac1{2^{2n}}] .$$
Note that the measure of $[0,1] \setminus E_n$ is less than $\frac1{2^{n-1}}$, and hence by the Borel Cantelli Lemma, $E = \liminf E_n$ has full measure in $[0,1]$.
We will show that $f'(x) = 0$ for $x \in E$.  Suppose that $x \in E$, that is, for some $n_0 \ge 0$, we have $x \in \bigcap_{m \ge n_0} E_m$.  Suppose that $|x - y| < 2^{-2n}$ for $n \ge n_0$.  Then there exists an $m \ge n$ such that $2^{-2m-2} \le |x-y| < 2^{-2m}$.  Since $x \in E_m$, we have that $f_l(x) = f_l(y)$ for $l \le m$.  Then
\begin{align} |g(x) - g(y) |
&\le \sum_{l \ge m} 2^{-2l} |f_l(x) - f_l(y)|
\\& \le \sum_{l \ge m} 2^{-2l}(|x-y| + 2^{-l})
\\& \le 2^{-2m} | x-y | + 2^{-3m}
\\ &\le 5 \times2^{-m} |x-y|
\\ &\le 5 \times2^{-n} |x-y|
.\end{align}
To make it discontinuous at the rationals, use $n!$ instead of $2^n$.  However, I don't see how to make it differentiable at all the irrationals, only on a set of full measure.
Comment: Great answer!! I am working with your example. Thanks a lot!!


c# foreach loop list with class

Question: Trying to display the names and student ID with a foreach loop at the end of the program, but instead of listing the names it just gives me the output "Assignment_8.Student".  How exactly would I display the names and ID's instead of that directory its giving me?
using System;
using System.Collections.Generic;

namespace Assignment_8
{
class Program
{
    static void Main(string[] args)
    {

         List<Student> myList = new List<Student>();

        Student s1 = new Student();
        s1.FirstName = "John";
        s1.LastName = "Smith";
        s1.StudentID = 2560;
        myList.Add(s1);

        Student s2 = new Student("Peter");
        myList.Add(s2);

        Student s3 = new Student("Morgan", "Simmons");
        myList.Add(s3);

        Student s4 = new Student("James", "Walters");
        myList.Add(s4);

        Student s5 = new Student("Linda", "Scott", 1005);
        myList.Add(s5);

        Console.WriteLine();

        Console.WriteLine("Total students: {0}", Student.Count);

        foreach (var item in myList)
        {
            Console.WriteLine("Student: {0}", item);
        }

    }
}
}

Here is the Class:
using System;
using System.Collections.Generic;
using System.Text;

namespace Assignment_8
{
class Student
{
    public static int Count { get; private set; }
    private static readonly Random rnd = new Random();

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int StudentID { get; set; }

    public Student(string first, string last, int id)
    {
        FirstName = first;
        LastName = last;
        StudentID = id;
        ++Count;
        Console.WriteLine("Student Name: {0} {1}, Student ID: {2}",
            FirstName, LastName, StudentID );
    }

    public Student(string first ="", string last ="")
    {
        FirstName = first;
        LastName = last;
        ++Count;
        Console.WriteLine("Student Name: {0} {1}, Student ID: {2}",
           FirstName, LastName, rnd.Next(1000, 9999) );
    }

}
}

Here is the Output of the program:
Student Name:  , Student ID: 4101
Student Name: Peter , Student ID: 9074
Student Name: Morgan Simmons, Student ID: 2328
Student Name: James Walters, Student ID: 5481
Student Name: Linda Scott, Student ID: 1005

Total students: 5
Student: Assignment_8.Student
Student: Assignment_8.Student
Student: Assignment_8.Student
Student: Assignment_8.Student
Student: Assignment_8.Student

Answer: You need either to use the same approach as you do in constructors:
    foreach (var item in myList)
    {
        Console.WriteLine("Student: {0} {1} {2}", item.StudentID, item.FirstName, item.LastName);
    }

Or to override ToString (otherwise class name will be used to convert class instance to string):
class Student
{
    public override string ToString()
    {
        return string.Format("Student: {0} {1} {2}", StudentID, FirstName, LastName);
    }
}

And usage in you loop:
Console.WriteLine(item);

Also since C# 6 there you can beautify it with string interpolation:
    public override string ToString()
    {
        return $"Student: {StudentID} {FirstName} {LastName}";
    }

Comment: The for each loop works untill it gets to the random student id part. How would I go about it outputting the StudentID's that are set and the ones that are Random as well? I also have to use the foreach loop for this, thanks in advance!
Comment: @WilliamDaly you just outputing `rnd.Next(1000, 9999)` to `Console`, and not assigning it to `StudentID`. Also you constructor can [invoke another](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/using-constructors).
Comment: How would I go about assigning the rnd.next to the studentID, thats the part that im currently stuck on.
Comment: @WilliamDaly the same as you do with non-random id.
Comment: Ok I finally got it, I appreciate the help Guru!
Answer: On this line here:
Console.WriteLine("Student: {0}", item);

item is an object of type Student. Because Microsoft never wrote a WriteLine(string, Student) method that knows specifically how to print out one of your Students with its name and everything, the form of WriteLine that ends up getting used is WriteLine(string, object).
This form of WriteLine will use the first string as a format spec to create a custom string using the other objects passed in in plae of the numbered placeholders in the string. Because it needs the objects to be a string, it simply calls the .ToString() method on whatever thing is passed into it as the object argument, in this case a Student, when it is building the string to output from the format string "Student: {0}".
Because your Student doesn't have a specific version of the ToString() method, it uses the default one on the base object, from which Student is derived (everything inherits from object if it doesn't inherit from something more specific)
The ToString() method on object is very primitive: it merely returns the name of the kind of object it is, in this case a Assignment_8.Student
The end result is that WriteLine(string, object) is processing the "Student: {0}", string, it finds placeholder {0}, it goes to the 0th argument (the Student item), calls ToString() on it, gets "Assignment_8.Student" back, pops it in the string "Student: {0}" in place of the {0} and then finishes its work

To alter things you either need to :

Use a different flavor of WriteLine, such as WriteLine(string), by making your string first, and passing the string you made into it:

WriteLine(item.Firstname + " " + item.LastName)
WriteLine($"{item.Firstname} {item.LastName}")

In this case it is the class that calls WriteLine that gets to decide how a student is to be displayed

Use this flavor of WriteLine that accepts a format and a bunch of parameter objects but give actual strings to the parameters: WriteLine("Student FN:{0}, LN:{1}", item.FirstName, item.LastName) - item.FirstName and item.LastName are actually strings that are part of the Student, rather than being the whole Student. Even though these strings will also be passed in as objects, they're still strings at the core of their being, and calling .ToString on a string, returns the string itself, so everything works out
Create a version of the ToString() method in your Student class that returns a formatted representation of the student as a string. With this way, yourStudent goes in, has ToString() called on it, gets its chance to shine and return a pretty version of itself, and the result is inserted into the formatting string in place of {0}:

    class Student{
      override string ToString(){
        return this.LastName + ", " + this.FirstName;
      }
   }

There are some other more wacky things you could do, such as serializing to JSON, which will return a representation of the class suitable for computer consumption, but the basic thing here is that something needs to decide how your Student should be formatted and presented - and that's either the Student itself (override ToString() way), or the thing that knows about the Student.
Arguably, you could say it should be the class that holds the Student rather than the Student itself, because the Student itself can't possibly know how to format itself in all the myriad ways different things might want to see it
Comment: Hey Caius thanks for responding back to my question its good to know that I can do it like this, but I have to use the foreach loop in the program. How exactly would I go about that? I figured out the first and last name with it but am struggling on the studentID part, as 3 of the 5 students ID's are random. how would I call the ID's that are set and the random ones as well?
Comment: Just like you have been doing; I'm advocating adding a new method to your student class, it doesn't change your foreach loop at all- it just gives the WriteLine something to use that links up the names of the student. You can of course also change your WriteLine so that it uses a different way (get the name out of the item): `Console.WriteLine("Student: {0}", item);` becomes `Console.WriteLine("Student: {0}", item.FirstName);` for example
Comment: Oh ok I see what you were saying, sorry took my brain a minute to work there. Thanks Caius!
Answer: Simply update the foreach loop as:
Console.WriteLine("Student: {0}, {1}", item.FirstName, item.StudentID);

c# foreach loop list with class


Is there a two-by-two contingency table dataset where an Odds Ratio estimate would work and a Risk Ratio would fail?

Question: I am wondering if there is an example of a two-by-two contingency table dataset where an Odds Ratio estimate would work and a Risk Ratio would fail, or vice versa? In additional are there cases where a Risk Difference would fail as well? Thanks.
Answer: Depends on what you mean by "fail". You have a problems to calculate (i.e. the likelihood is maximized on the boundary of the parameter space $(0, \infty)$) the maximum likelihood estimates of the odds and risk ratio in a single 2 by 2 table, if any cell has a zero entry. In contrast the risk difference can still be calculated. Of course, there are a lot of possible approaches for still getting an odds or risk ratio estimate in these circumstances (e.g. Bayesian approaches, continuity corrections, median unbiased estimates etc.).
Once you go to stratified tables or use the estimate from one table for a new table, you run into situations that the odds ratio handles better than the risk ratio or risk difference. E.g.
$$\begin{array}
. & Yes & No \\
A & 3 & 9 \\
B & 1 & 12
\end{array}$$
The odds ratio for A versus B is 4, the risk ratio 3.25 and the risk difference about 0.17. Then you have this second table
$$\begin{array}
. & Yes & No \\
A & 48 & 1 \\
B & 12 & 1
\end{array}$$
The odds ratio for A versus B is also 4. However, if you assumed a risk ratio of 3.25 on top of the proportion of 0.923 for group B, then you would get a proportion of 3.0 for group A. This is of course nonsense, because a proportion needs to be in [0, 1,]. Similarly, if you were to add a risk difference of 0.17 to 0.923 you get a proportion for group A that is >1.
This illustrates how risk ratios and risk differences can fail in the sense that they cannot be constant across extremely different proportions for group B. At least mathematically the odds ratio does not have that problem, but of course that does not mean that the odds ratio would truly stay constant across different group B proportions in any real practical problem. You do not notice that kind of issue in 2 by 2 tables.


Utilizar maior precisão Possível no GPS Android

Question: Estou construindo uma app que ao passar por uma "linha", definida por um intervalo de latitudes e longitudes, reconhece a passagem e exibe isso em uma View.
Porém notei que ao passar pelo intervalo em uma velocidade mais alta, a bordo de um veículo, ele não reconhece a passagem.
Como posso obter essa precisão em uma velocidade maior?
package br.com.nobre.ntrack.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import br.com.nobre.ntrack.R;
import br.com.nobre.ntrack.config.Permissoes;

public class NavegacaoActivity extends AppCompatActivity {

    private GoogleMap mMap;
    private String[] permissoes = new String[]{Manifest.permission.ACCESS_FINE_LOCATION};
    private LocationListener locationListener;
    private LocationManager locationManager;
    private TextView txtLat, txtLong, txtVelocidade, txtParcial;

    private Double testeMaior;

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

        Permissoes.validarPermissoes(permissoes, this, 1);

        txtLat = findViewById(R.id.txtLatitude);
        txtLong = findViewById(R.id.txtLongitude);
        txtVelocidade = findViewById(R.id.txtVelocidade);
        txtParcial = findViewById(R.id.txtParcial);

        Double lat1, lat2;
        lat1 = -29.909756; // maior
        lat2 = -29.909811;

        Log.i("teste", "maior = " + testeMaior);
        txtParcial.setText("Não passou");

        locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                Log.i("teste de localizacao", "Localizacao: " + location.toString());
                Double latitude = location.getLatitude();
                Double longitude = location.getLongitude();
                float velocidade = location.getSpeed();

                txtLat.setText("lat: " + latitude);
                txtLong.setText("long: " + longitude);
                double velocidadeEmKm = (velocidade * 3.6);
                txtVelocidade.setText("velocidade: " + velocidadeEmKm);

                //-29.909737, -51.142835
                //-29.909846, -51.142851

                if (latitude >= -29.909846 && latitude <= -29.909737) {
                    if (longitude >= -51.142851 && longitude <= -51.142835) {
                        // esta passando na parcial teste efetuado com sucesso

                        txtParcial.setText("Passou pela parcial");
                    }
                }
            }

            @Override
            public void onStatusChanged(String s, int i, Bundle bundle) {

            }

            @Override
            public void onProviderEnabled(String s) {

            }

            @Override
            public void onProviderDisabled(String s) {

            }
        };

        // recuperar localização do usuario
        /*
         * 1 - provedor de localização
         * 2 - Tempo mínimo entre atualizações de localização (milesegundos)
         * 3 - Distância mínima entre atualizações de localização (metros)
         * Location Listner ( Para recebermos as atualizações)*/
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        for (int permissaoResultado : grantResults) {
            if (permissaoResultado == PackageManager.PERMISSION_DENIED) {
                //Alerta
                alertaValidacaoPermissao();
            } else if (permissaoResultado == PackageManager.PERMISSION_GRANTED) {
                // recuperar localização do usuario
                /*
                 * 1 - provedor de localização
                 * 2 - Tempo mínimo entre atualizações de localização (milesegundos)
                 * 3 - Distância mínima entre atualizações de localização (metros)
                 * Location Listner ( Para recebermos as atualizações)*/
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
                }
            }
        }
    }

    private void alertaValidacaoPermissao() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(getResources().getString(R.string.permissoes_negadas));
        builder.setMessage(getResources().getString(R.string.mensagem_permissoes_negadas));
        builder.setCancelable(false);
        builder.setPositiveButton(getResources().getString(R.string.confirmar_permissoes_negadas), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                finish();
            }
        });

        AlertDialog dialog = builder.create();
        dialog.show();
    }

    @Override
    protected void onStop() {
        super.onStop();
        locationManager.removeUpdates(locationListener);
    }
}

Comment: Não sei quão largo é esse intervalo que você referiu e também não sei de quanto em quanto tempo sua aplicação lê a coordenada. Mas digamos que tenha 100 metros de largura e durante o tempo que você esteve entre as coordenadas o sistema não leu ou se a unica leitura que ele fez caiu fora desse intervalo ele não reconhecerá.
Comment: Quando você esta dirigindo com o Waze e sai para uma via paralela, ele demora um longo tempo até 'perceber' que você saiu da via principal.
Comment: Outro detalhe importante o Waze ( por exemplo ) consegue um nível de acurácia bom porque ele usa outro mapa para corrigir os pontos que recebe do GPS. Se você não fizer nenhuma correção os pontos podem ficar bem espalhados, e é natural isso.
Answer: Use FusedLocationProviderClient
 e defina a prioridade LocationRequest como PRIORITY_HIGH_ACCURACY
Veja os detalhes sobre precisão nesse link
De modo resumido, a API do Google Play Services tem inteligência para obter uma localização precisa ao fundir GPS_PROVIDER + NETWORK_PROVIDER + PASSIVE_PROVIDER.
Comment: Muito obrigado!


GXT3 Grid cell rendering

Question: How can I render a grid column as multiline grid column using GXT 3 grids.
e.g
ColumnConfig<ExceptionEntry, String> name = new ColumnConfig<ExceptionEntry, String>(props.name(), 50, "Name");
name.setColumnStyle(new SafeStyles(){
        @Override
        public String asString() {
            return // what styles to use for multiline rendering;
        }
    });

name.setCell(new AbstractCell<String>() {
    @Override
        public void render(com.google.gwt.cell.client.Cell.Context context,
                String value, SafeHtmlBuilder sb) {
             ??? what needs to be done to render the column as multiline column
        }
    });

Answer: You can do that the easy and the hard way.
The easy one:
name.setCell(new AbstractCell<String>() {
    @Override
    public void render(com.google.gwt.cell.client.Cell.Context context, String value, SafeHtmlBuilder sb) {
         sb.appendHtmlConstant("
" + value + "
");
    }
});

The hard (but much better) way:
1) Create custom GridAppearance to be used instead of default one from your theme:
import com.google.gwt.core.client.GWT;
import com.sencha.gxt.theme.base.client.grid.GridBaseAppearance;

public class YourGridAppearance extends GridBaseAppearance {

  public interface YourGridStyle extends GridStyle {
  }

  public interface YourGridResources extends GridResources {

    @Source({ "com/sencha/gxt/theme/base/client/grid/Grid.css", "YourGrid.css" })
    @Override
    YourGridStyle css();
  }

  public YourGridAppearance() {
    this(GWT.<YourGridResources> create(YourGridResources.class));
  }

  public YourGridAppearance(YourGridResources resources) {
    super(resources);
  }
}

2) Copy /theme-you-use/client/grid/Grid.css to YourGrid.css and put it in the same folder where you've created YourGridAppearance class. Here is an example based on Grey theme:
@CHARSET "UTF-8";
.rowHighlight {
    border: 1px dotted #535353;
}

.rowAlt .cell {
    background-color: #FAFAFA;
}

.rowOver .cell {
    background-color: #EEEEEE;
}

.cell {
    border-color: #FAFAFA #EDEDED #EDEDED;
    border-right: 0 solid #EDEDED;
    font: 14px tahoma,arial,verdana,sans-serif;
}

.cellSelected {
    background-color: #C9C9C9 !important;
    color: #000000;
}

.cellInner {
    white-space: normal;
    line-height: 15px;
}

.columnLines .cell {
    border-right-color: #EDEDED;
}

.rowOver .cell,.rowOver .rowWrap {
    border-color: #DDDDDD;
}

.rowWrap {
    border-color: #FAFAFA #EDEDED #EDEDED;
    border-right: 0 solid #EDEDED;
    border-style: solid;
    border-width: 1px;
    overflow: hidden;
}

.rowSelected .cell,.rowSelected .rowWrap {
    background-color: #DFE8F6 !important;
    border-color: #A3BAE9;
}

.footer {
    background: #F7F7F7 none repeat scroll 0 0;
    border-top: 1px solid #DDDDDD;
    border-bottom: 1px solid #DDDDDD;
    display: block;
    overflow: hidden;
    position: relative;
}

The most important part of it is this one:
.cellInner {
    white-space: normal;
}

3) Replace default grid appearance with your custom one. To do that you have to add the following lines to your-project.gwt.xml:
<replace-with class="package.name.of.your.custom.theme.class.YourGridAppearance">
  <when-type-is class="com.sencha.gxt.widget.core.client.grid.GridView.GridAppearance" />
</replace-with>

GXT3 Grid cell rendering


How is $2^{n-k-1} \cdot 3^k = (3/2)^k \cdot 2^{n-1}$?

Question: I'm currently reading through some litterature about difference equations, and i came across a relation i just can't seem to wrap my head around.
How come:
$2^{n-k-1}\cdot 3^k=(\frac{3}{2})^k\cdot 2^{n-1}$?
The original problem in the book is:
(1*) $y(n)=a^ny_0+\sum_{r=0}^{n-1}a^{n-r-1}g(r)$
Find a solution for the equation:
$x(n + 1) = 2x(n) + 3n$ , $x(1) = 0.5$
Solution From (1*), we have
(2) $x(n) = (\frac{1}{2})\cdot2^{n-1}+\sum_{r=1}^{n-1}2^{n-r-1}3^k$
(3) $x(n) = 2^{n-2}+2^{n-1}\sum_{r=1}^{n-1}(\frac{3}{2})^k$
(4) $x(n) = 2^{n-2}+2^{n-1}\frac{3}{2}(\frac{(\frac{3}{2})^{n-1}-1}{\frac{3}{2}-1})$
(5) $x(n) = 3^n -5\cdot2^{n-2}$
Although my question is more directed to the relation $2^{n-k-1}\cdot 3^k=(\frac{3}{2})^k\cdot 2^{n-1}$, a thorough explanation of the steps in the book would be appreciated as well.
I'm truly sorry if this question has been asked before or is in any way irrelevant to the tags, but I'm pretty green to this topic, so the relevance of the tags might be off.
Comment: Note: $$\biggl(\frac{3}{2}\biggr)^k\cdot 2^{n-1}=\frac{3^k}{2^k}\cdot 2^{n-1}=3^k\cdot\frac{2^{n-1}}{2^k}=3^k\cdot 2^{n-k-1}$$
Answer: $$2^{n-k-1}\cdot 3^k=\frac{2^{n-1}}{2^k}\cdot 3^k=2^{n-1}\cdot \frac{3^k}{2^k} =\left(\frac{3}{2}\right)^k\cdot 2^{n-1}$$
Comment: You appear to have a misplaced `\cdot` ... I'll take that as a minor victory in our otherwise symmetric answers `;-)`
Comment: @DanielW.Farlow: that's right! You win! rsrsrsrs...
Comment: Thank you, that clarified it! Have a good one ^^


How can i call servlet from jsp (HTTP Status 404 – Not Found)

Question: I am making a login .JSP where on login button it called to login.java(servlet). But JSP is not able to call the servlet file and it gives an error.
Login.JSP
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>

<meta charset="ISO-8859-1">
<title>login</title>

<form action="Login" method="get">
    Enter Username:<input type="text" name="uname">

    Enter Password:<input type="password" name="upass">

    <input type="submit" value="login">
</form>

Login.java(servlet file)
package com.login;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Login
 */
@WebServlet("/Login")
public class Login extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        String uname=request.getParameter("uname");
        System.out.print("uname is"+uname);
        String upass=request.getParameter("upass");
        if (uname.equals("meet") && upass.equals("1234")) {
            response.sendRedirect("welcome.jsp");
        }
        else {
            response.sendRedirect("login.jsp");
        }
    }

}

ERROR MESSAGE
HTTP Status 404 – Not Found
Type Status Report
Message /Login
Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
Answer: Simply you can use getConextPath in jsp request
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
         pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>

  <meta charset="ISO-8859-1">
  <title>login</title>

<form action="<%=request.getContextPath()%>/Login" method="get">
  Enter Username:<input type="text" name="uname">

  Enter Password:<input type="password" name="upass">

  <input type="submit" value="login">
</form>

Wish i was helpfull; but regarding to BalusC using  Scriptlets <% ... %> are officially discouraged since JSP 2.0 which was introduced in 2003(!!). Please do not encourage starters to use bad practices. The correct practice is to use EL ${ ... } instead. –
so you can write this way and always try to use it on this way
  <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
             pageEncoding="ISO-8859-1"%>
    <!DOCTYPE html>

      <meta charset="ISO-8859-1">
      <title>login</title>

    <form action="${requestScope.getContextPath}/Login" method="get">
      Enter Username:<input type="text" name="uname">

      Enter Password:<input type="password" name="upass">

      <input type="submit" value="login">
    </form>

Its better to know the bad coding and the write coding , wish i  this help you too.
Comment: Scriptlets `<% ... %>` are officially discouraged since JSP 2.0 which was introduced in 2003(!!). Please do not encourage starters to use bad practices. The correct practice is to use EL `${ ... }` instead.
Comment: Yes @BalusC your right, it my fault.


Get node in custom token to be used in Pathauto url alias pattern

Question: I'm attempting to use a custom made token for url alias patterns. I've been able to custom tokens using node information just fine. But it just occurred to me that I don't know how I could possibly use it with url alias patterns.
function mymodule_plugins_tokens($type, $tokens, array $data, array $options, \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata){
  $token_service = \Drupal::token();
  $replacements = array();
  if($type == 'mymodule_tokens') {
    foreach($tokens as $name => $original){
      switch($name){
        case 'current_nid':
        $node = \Drupal::routeMatch()->getParameter('node');
        $title = (!empty($node)) ? $node->id() : 'This is a test';
        $replacements[$original] = $title;
        break;
      }
    }
  }
  return $replacements;
}

It works fine if I'm using it on a node page. But what if I want to use it in a url alias pattern in the pathauto module?
$node = \Drupal::routeMatch()->getParameter('node');

I know here it gets the node based on the current page it's on. But if it's used in a url alias pattern it's not on any page at the time of url alias construction.
I have a feeling this is possible since there are already tokens like [node:title] that work.  Also is there any weird thing I can do like this?
[mymodule_tokens:current_nid[node:nid]]
Where I pass a token within a token? And if I can how would I access that extra parameter within my custom token. (p.s. I understand that my example is just getting the current_nid and that there are already tokens for it. I'm just using that as an example)
Is there anyway I can get the node from my custom token to be used in a url alias pattern?
Answer: You get the node from $data:
  if (!empty($data['node'])) {
    /* @var \Drupal\node\NodeInterface $node */
    $node = $data['node'];
  }

It is the responsibility of the code which calls replace() to provide the correct context (in case of Pathauto the node for which it's building the alias).
Comment: Yes, this should work in every case. If code wants to replace a token for the current node then it has to provide this node in $data when it calls replace().
Comment: Were my previous uses of $node = \Drupal::routeMatch()->getParameter('node'); unnecessary? should $data['node'] work for every case?
Comment: Of course you could generate tokens for the current node. This would be similar to the tokens which already exist for the current user. This kind of tokens don't need a context in $data, because they use the context of the current page/route. But you can't use these tokens for Pathauto.


Quando coloco input dentro de alguma div o javascript não funciona

Question: Eu quero aplicar o css em um formulario mas quando vou colocar os inputs dentro de alguma div o javascript não funciona Veja o código:
No caso quando digito o email e a senha era para o botão ficar azul ativado.

Eu quero fazer isso no formulário:
<form id="formLog" method="post" action="website/login">

< input type="text" id="txtELog" name="txtELog" placeholder="Userlogin ou E-mail: *" />

< input type="password" id="txtPassLog" name="txtPassLog" placeholder="Senha: *" />

< input type="submit" id="btnLog" name="btnLog" value="Login" disabled="disabled" class="btnDisabled" />

</form>

Mas quando faço isso e preencho os dois campos o javascript de ativar o botão não funciona. Alguém pode me ajudar? Preciso colocar esses inputs dentro de suas respectivas divs pra estilizar o formulário.
Comment: Você que escreveu esse código? Sabe o que significa o seletor `#formLog > input` que utilizou no jQuery? Talvez valha a leitura de [Como funcionam os seletores >, + , ~ no CSS?](https://pt.stackoverflow.com/q/194920/5878)
Answer: Tem que retirar do seletor o sinal >. Quando você coloca as divs, os inputs deixam de ser descendentes diretos do seletor #formLog indicados pelo sinal >:

$(' #formLog  input').on('input', function () {
 var emptyLog = false;
 $('form input, form select').each(function () {
     if ($('#txtELog').val() == '' || $('#txtPassLog').val() == '') {
         emptyLog = true;
     }
 });
 if (emptyLog) {
  $('#btnLog').attr('disabled', 'disabled');
  $('#btnLog').attr('class', 'btnDisabled');
 } else {
  $('#btnLog').removeAttr('disabled');
  $('#btnLog').attr('class', 'btnEnabled');
 }
});
.btnDisabled{
    pointer-events:none;
    outline:none;
    border: none;
    background: gray;
}
.btnEnabled{
    outline:none;
    border: none;
    background: blue; color: white;
}

<form id="formLog" method="post" action="website/login">

<input type="text" id="txtELog" name="txtELog" placeholder="Userlogin ou E-mail: *" />

<input type="password" id="txtPassLog" name="txtPassLog" placeholder="Senha: *" />

<input type="submit" id="btnLog" name="btnLog" value="Login" disabled="disabled" class="btnDisabled" />

</form>

Caso contrário, teria que fazer assim: $('#formLog > div > input') se quisesse se referir apenas aos inputs descendentes diretos de divs dentro do #formlog.
O que é um descendente direto?
É um elemento-filho do primeiro nível da árvore:

    <-- descendente direto da div

 <-- descendente direto do span
       <-- descendente direto do span

 <-- descendente direto da div

Answer: Duas coisas que pude observar:

Os inputs estão com espaço entre a tag de abertura "< input". Deve regirar esse espaço.
Já que você quer colocar o efeito para qualquer input dentro do form em questão, deve retirar o sinal ">" e deixar somente "#formLog  input", assim qualquer input dentro de #formLog pegará o efeito.


how to detect shift keystroke in c?

Question: I try to detect shift keystrokes in C with winapi Control.ModifierKeys in C#
is there any equivalent function in C to this C# function:
if (Control.ModifierKeys == Keys.Shift ) {
  ...
}

I want to detect shift keystrokes in C.
Comment: That snippet doesn't detect key strokes, it detects key state.  What do you *really* want to detect?
Comment: He probably meant state.  That is how ModifierKeys is used in C# at least.  He wants to know if the Shift key is currently being pressed.
Answer: GetAsyncKeyState
http://msdn.microsoft.com/en-us/library/ms646293(VS.85).aspx
Comment: GetKeyState() should be used, there's an important difference.
Comment: Yes but if he wants the state of the press at the time of the function then he needs to use GetAsyncKeyState.  GetKeyState returns the state of the keys when the original event (click for example or keypress) was sent.
Answer: I believe getAsyncKeyState does pretty much exactly what you want.

how to detect shift keystroke in c?


Free Vector Spaces - Alternative Definition and Relation to Linear Independence?

Question: Recently, I have been having trouble understanding the concept of a "free vector space." Several google searches have resulted in some very vague explanations. All I have to go off of is a friend's lecture notes which denote some definitions and goes over some of the consequences of having a free vector space. These are the definitions I was given:

1) Definition of the Free Vector Space

"Let $S$ be a set, and $K$ be a field.  The free vector space generated by $S$, $K$$\langle{S}\rangle$, is the subspace of $Fun(S,K)$ (the set of all functions from $S$ to $K$) spanned by the characteristic functions $\chi_s$, for $s \in S$."
Just to clarify, the characteristic function is defined as:
$$\chi_s(x) =
\begin{cases}
0,  & \text{if $x$ $\neq$ s} \\
1, & \text{if $x$ = s}
\end{cases} $$
Since any function in $Fun(S,K)$ can be expressed as a linear combination of characteristic functions, this also means that any element within the free vector space is expressed as a linear combination of characteristic functions. That is, for any $k \in K \langle S \rangle $, $k =  a_{s_1} \chi_{s_1} + ... + a_{s_n} \chi_{s_n}$, for some $s_1, ..., s_n \in S$.
It is clear to me that these characteristic functions are linearly independent; that is, you cannot write any one of them in terms of the others.

2) "Freeness" of the Free Vector Space

"Let $S$ be a set, $K$ a field, and $V$ a $K$-vector space. Then any function $\psi \colon S \to V$ extends uniquely to a linear transformation $T_{\psi} \colon K \langle S \rangle \to V$."
The notes go on to mention that the reason why we use the term "free" is because we are "free" to define a linear transformation out of $K \langle S \rangle$ by just choosing any vectors for $S$ to be sent to.

3) Alternative Definition of the Free Vector Space

A second definition of the free vector space is also mentioned, though informally. It states that another way to think of $ K \langle S \rangle$ is to think of it as the span of $S$, where we assume that $S$ is its basis.
A final note is that the reason why definitions 1) and 3) are equivalent (and ultimately why we are able to find basis vectors for a vector space) is because the characteristic functions are isomorphic to the elements of S. That is, for each $s \in S , \, \, \, \chi_s \longleftrightarrow s$ $\, \, \,$ (he says it is a "relabeling").

Within all of this, there are a few things I understand. Definition 3) is very intuitive to me - treating the elements of $S$ as basis elements, and treating $K \langle S \rangle$ as its span seems relatively natural - much more so than having to first consider a (potentially very very large) set of functions. This leads me to my first question:
If we are interested in a vector space whose elements are some object, then why are we able to reasonably compare them to functions between those objects and some field?
I understand that using the first definition is helpful because it is more directly related to linear independence, but why are we able to take the first definition as the "main" definition, and then do some strange math to say that these functions are "essentially the same as" the elements of $S$ themselves? I assume that this has to do with the fact that $\chi_s$ seems to be a very reasonable "stand in" for $s$, within $Fun(S,K)$, but I still do not understand why this leads to the elements of $S$ being linearly independent (we are only directly saying things about their related characteristic functions).
The generality of the statement is also somewhat confusing. $S$ can be any set,  so if I were to consider the set containing the 3 primary colors, they would be fundamentally different from characteristic functions. How can I reasonably "relabel" the colors "red, blue, and yellow", to "$\chi_{red}$, $\chi_{blue}$, and $\chi_{yellow}$?" There is a section that states that it's ok to do, since a linear combination from either set would have the same structure (a sum of vectors which have been multiplied by scalars),  but it still seems problematic. I can plug things into functions, but I can't "plug" anything into the colors red, blue, and yellow. It seems like relabeling would be a problem, since I wouldn't be able to do the same things with $S$ as I could with its related characteristic functions.
My second question has to do with the definition of freeness, as well as the note the writer made:
Just what does the statement "we are free to define a linear transformation out of $K \langle S \rangle$ by choosing vectors for $S$ to be sent to" mean?
More precisely, how are we able to do this? It seems very far-fetched for us to be able to extend ANY function from $S$ to $V$. Does this statement mean that we can define the transformation however we want?
Thank you for your help - I hope you can offer some insight.
Comment: If you are familiar with the language of category theory, this is simply that the forgetful functor ${_k}\mathsf{Vect} \to \mathsf{Set}$ admits a left adjoint, called the **free vector space functor**.
Answer: The statement "we are free to define a linear transformation out of $K \langle S \rangle$ by choosing vectors for $S$ to be sent to", can be seen as follows: let $V$ be any vector space and assume we have a function $c: S \to V$, that assigns to each $s \in S$ some element in $V$, totally arbitrarily.
Then we can define a linear function $F_c: K \langle S\rangle \to V$ by
$$F_c\left(\sum_{i=1}^n k_i \chi_{s_i}\right) = \sum_{i=1}^n k_i c(s_i)$$
where we define the image of an element of the span of all of the $\chi_s$ (so we have finitely many $\{s_1,\ldots,s_n\}$ from $S$ and finitely many field elements $k_i$ as well, and the right hand sum is taken in $V$. So basically we send $\chi_s$ to $c(s)$ and extend by linearity, as usual.
Answer: I know this was asked 5 years ago, but I'll add my answer since I found this post helpful, and perhaps my intuition might aid someone else down the line
I think the easiest way to understand free Vector spaces is to give a familiar example,
$$ \mathbb{R}^n \mbox{ is a free vector space over } \mathbb{R}$$
Specifically, it can be thought of as
$$ \mathbb{R}\langle [n] \rangle $$
Where $[n]= \{i\in\mathbb{N}| 1\leq i\leq n\} $
This is the characteristic functions are the usual basis vectors, through the association
$$ \chi_k \to [0,0...1,0,...,0]^T $$
Where the $1$ occurs in the $k$'th place of the column vector.
So really a free vector space is just a way to define vector spaces so that the intuitive idea of "collections of components" that one gets from working with explicit examples, is more clear from the definition.


HP USB Graphics Adapter Drivers for Windows 7

Question: Has anyone seen Windows 7 drivers yet for the HP USB Graphics Adapter?
Comment: I should add note that I am also running 64bit as well...
Answer: DisplayLink Windows 7 Drivers
Not sure what chipset is in the USB adapter you have, but this would be my first start.
Answer: Ditto to oneguynick's answer. I don't know the HP one, but the EVGA+ adapter I have uses the DisplayLink driver. From what I've seen online, most USB display adapters are powered by DisplayLink.
Comment: Took me awhile to check back, but that WORKED!  Thanks!!


Groupby Array elements and categorize them based on date in Mongodb Query

Question: I have an array element in my DB and I want to group By and calculate the number of repetitions of different elements in this array based on different datetime. assume following collection:
{
   _id: ObjectId(7df78ad8902c)
   title: 'MongoDB Overview',
   tags: ['SQL', 'database', 'NoSQL'],
   created_at: 2021-10-03 10:05:51.755Z
},
{
   _id: ObjectId(7df78ad8902d)
   title: 'NoSQL Overview',
   tags: ['mongodb', 'database', 'PHP'],
   created_at: 2021-10-03 14:05:51.755Z
},
{
   _id: ObjectId(7df78ad8902d)
   title: 'Developing',
   tags: ['java', 'btc/usdt', 'PHP'],
   created_at: 2021-10-03 14:05:51.755Z
}
,
{
   _id: ObjectId(7df78ad8902d)
   title: 'databases for search',
   tags: ['elasticsearch', 'database', 'PHP'],
   created_at: 2021-10-03 12:05:51.755Z
}

I want to calculate the number of repetitions of different elements in tags field such as mongodb, database, noSQL based on datetime (for example hot hashtags in last hour, today or this month) in this collection. How can I solve this problem in mongo?
expected answer like .
1 - hot hashtags in last hour ['a' , 'b' , 'c']
2 - hot hastags in last 5 hours : ...
3 - today : ...
4 - this month : ...

Answer: Query

not calendar based, based on difference on milliseconds
keep only last 30 days data
facet and 4 group by
its exactly the same code 4x
The only difference is the multiply

last 30days : (now_date-created_at) <= (* 30 24 60 60 1000)
last 24h : (now_date-created_at) <= (* 24 60 60 1000)
last 120 hours(5days) : (now_date-created_at) <= (* 5 60 60 1000)
last 60 min : (now_date-created_at) <= (* 60 60 1000)
*subtraction works on dates also, and returns milliseconds

filter the date depending on what we want its 4 different filters
unwind
group by tag and count occurences
sort by count
limit 2 to keep like the 2 top hotttest tags, you can change it to any value, like limit 1 to keep only the hottest tag

*if you want calendar based like 3 October(3 days data only), query must be changed, the same is for day(query is for 24 hours) etc (in those cases we should use $hour $month etc)
Its not big change in query.
   //same month
   {"$eq" : [ {"$month" : "$$NOW"}, {"$month" : "$created_at"} ]
   //same day(assuming same month from previous filter)
   {"$eq" : [ {"$dayOfMonth" : "$$NOW"}, {"$dayOfMonth" : "$created_at"} ]
   //same hour

*we could also use the new $dateTrunc to check for same month etc.
Test code here
(Query is big but its the same thing 4x)
db.collection.aggregate([
  {
    "$set": {
      "created_at": {
        "$dateFromString": {
          "dateString": "$created_at"
        }
      }
    }
  },
  {
    "$unwind": {
      "path": "$tags"
    }
  },
  {
    "$match": {
      "$expr": {
        "$lte": [
          {
            "$subtract": [
              "$$NOW",
              "$created_at"
            ]
          },
          {
            "$multiply": [
              30,
              24,
              60,
              60,
              1000
            ]
          }
        ]
      }
    }
  },
  {
    "$facet": {
      "month-tag": [
        {
          "$match": {
            "$expr": {
              "$lte": [
                {
                  "$subtract": [
                    "$$NOW",
                    "$created_at"
                  ]
                },
                {
                  "$multiply": [
                    30,
                    24,
                    60,
                    60,
                    1000
                  ]
                }
              ]
            }
          }
        },
        {
          "$group": {
            "_id": "$tags",
            "count": {
              "$sum": 1
            }
          }
        },
        {
          "$sort": {
            "count": -1
          }
        },
        {
          "$limit": 2
        },
        {
          "$project": {
            "_id": 0,
            "tag": "$_id"
          }
        }
      ],
      "day-tag": [
        {
          "$match": {
            "$expr": {
              "$lte": [
                {
                  "$subtract": [
                    "$$NOW",
                    "$created_at"
                  ]
                },
                {
                  "$multiply": [
                    24,
                    60,
                    60,
                    1000
                  ]
                }
              ]
            }
          }
        },
        {
          "$group": {
            "_id": "$tags",
            "count": {
              "$sum": 1
            }
          }
        },
        {
          "$sort": {
            "count": -1
          }
        },
        {
          "$limit": 2
        },
        {
          "$project": {
            "_id": 0,
            "tag": "$_id"
          }
        }
      ],
      "5hour-tag": [
        {
          "$match": {
            "$expr": {
              "$lte": [
                {
                  "$subtract": [
                    "$$NOW",
                    "$created_at"
                  ]
                },
                {
                  "$multiply": [
                    5,
                    60,
                    60,
                    1000
                  ]
                }
              ]
            }
          }
        },
        {
          "$group": {
            "_id": "$tags",
            "count": {
              "$sum": 1
            }
          }
        },
        {
          "$sort": {
            "count": -1
          }
        },
        {
          "$limit": 2
        },
        {
          "$project": {
            "_id": 0,
            "tag": "$_id"
          }
        }
      ],
      "hour-tag": [
        {
          "$match": {
            "$expr": {
              "$lte": [
                {
                  "$subtract": [
                    "$$NOW",
                    "$created_at"
                  ]
                },
                {
                  "$multiply": [
                    60,
                    60,
                    1000
                  ]
                }
              ]
            }
          }
        },
        {
          "$group": {
            "_id": "$tags",
            "count": {
              "$sum": 1
            }
          }
        },
        {
          "$sort": {
            "count": -1
          }
        },
        {
          "$limit": 2
        },
        {
          "$project": {
            "_id": 0,
            "tag": "$_id"
          }
        }
      ]
    }
  }
])

Comment: ok good it helped, just be carefull with those difference, because its not calender based, for example for october that has 28 days, you cant do those, but here its not month based, its 30 days difference,24h*5 difference, 24h difference etc. Its not hard to change to be also same month/same day/same hour but this query doesnt do this.
Comment: we have many functions for those for example [month](https://docs.mongodb.com/manual/reference/operator/aggregation/month/) we have for day of month, hour of day, we have many. You could save those, but saving just the date, and calculate each time , i dont think it costs alot.
Comment: WOW. I wish I could give you more than 1milion badget. it was so great. a complicated query. it is a nice education for learning writing query in mongo . thank you so much :)
Comment: yeah but i think if we examine last 30 days (not last month) it would work. Am I right? the other point is how should I save datetime format to achieve this goal better? because inserting data is my duty and I can save date field any way I want


JSF 2.0 : How to set order of validation error

Question: I am using Jsf 2 with Hibernate Validator. It works fine, but I don't know how I can set the order of the generated errors.
For an example:
My Managed Bean
public class UserPresentation {

@NotNull(message = "EmailNullError")
@Email(message="EmailNotValidError")
String email;

@NotNull(message="passwordNullError")
String password;
//getter,setter...
}

In the frontend the passwordNullError appears before the emailNullerror in the generated ul-Tag. How can I change that?
Answer: You could bind the message labels to your inputs, using the for attribute. The validation messages will appear right behind the according inputs.
<h:inputText value="#{myBean.email}" id="email" />
<h:message for="email" />
<h:inputSecret value="#{myBean.password}" id="password" />
<h:message for="password" />

Comment: My design requires a single message component.  Is there any other solution to this?


Forward port 514 to 5514 only from specific source ip with firewalld

Question: I've been trying to find a way to forward traffic from a specific ip, eg 10.17.1.3 on port 514 to port 5514 with firewalld on CentOS
This works:
  <masquerade/>
  <forward-port to-port="5514" protocol="udp" port="514"/>
  <forward-port to-port="5514" protocol="tcp" port="514"/>

Doesn't work:
  <masquerade/>
  <rule family="ipv4">
    <source address="10.17.1.3"/>
    <forward-port to-port="5514" protocol="udp" port="514"/>
  </rule>

Which was addded with:
sudo firewall-cmd --permanent --zone=public --add-rich-rule="rule family='ipv4' source address='10.17.1.3' forward-port protocol='udp' port='514' to-port=5514"

Is there any way to achieve port forwarding only for a specific source ip with firewalld?
Answer: As always, when selecting traffic by source address, you should avoid using rich rules to select by source address, and instead create a new firewalld zone which matches traffic from the relevant source addresses.
For example:
firewall-cmd --new-zone=syslogsources --permanent
firewall-cmd --reload
firewall-cmd --zone=syslogsources --add-source=10.17.1.3
firewall-cmd --zone=syslogsources --add-forward-port=port=514:proto=udp:toport=5514

And after you have confirmed it works, save it:
firewall-cmd --runtime-to-permanent

Comment: sudo firewall-cmd --new-zone=syslogsb
usage: see firewall-cmd man page
=> Option can be used only with --permanent.

sudo firewall-cmd --new-zone=syslogsbc --permanent
=> success

sudo firewall-cmd --zone=syslogsbc --add-source=10.17.1.3
=> Error: INVALID_ZONE: syslogsbc
Comment: @willemdh Yes, you need to add `--permanent` when making the zone. You also need to reload the firewall before adding rules to the zone. See the edited answer.


Emoji inserted into MySQL

Question: I tried to add an emoji in chat box textarea with emoji image input but during the insertion time, i tried to var-dump the data, and that showed as below:

❤❤❤❤

I did not select any emojiis and inserted into the database

❤❤❤????????❤

like these, and I also did these steps

1)  ALTER DATABASE  CHARACTER SET utf8 COLLATE utf8_unicode_ci;
2)  ALTER TABLE  CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;
3) ALTER TABLE  MODIFY  VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci;
"thanks for @Timo Huovinen"

Any ways,I want to insert the emoji in database correctly, and after the insertion, the original emoji image should be listed.
Thanks in advance!!!
Comment: I'm still stuck at how you got those emoji into your question +1
Comment: @Tim that emoji is :ok_hand: these codes .. any idea to show the result
Comment: See also "question mark" in https://stackoverflow.com/questions/38363566/trouble-with-utf8-characters-what-i-see-is-not-what-i-stored
Answer: Parse the emojis as unicode characters before you insert them into your database, after that whenever you retrieve the emoji, just parse them back again.
Here's some info on that:
http://crocodillon.com/blog/parsing-emoji-unicode-in-javascript

Emoji inserted into MySQL


Firefox não está rodando o metodo .css() do Jquery, como corrigir?

Question: Estou usando esse script jasny-bootstrap.js, nesse trecho de codigo

<link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet" />

<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/jasny-bootstrap/3.1.3/css/jasny-bootstrap.css" rel="stylesheet" />

    Imagem
    <input type="file" />

O problema é que no Chrome a imagem que é inserida fica com o max-height = 68px, e quando vou no Firefox a imagem não fica com o max-lenght.(Nao redimensiona e deve redimensionar como no Chrome)
Como resolver esse probleminha?
Estou tendo a impressão que esse trecho do js não roda no Firefox
 if (preview.css('max-height') != 'none') $img.css('max-height', parseInt(preview.css('max-height'), 10) - parseInt(preview.css('padding-top'), 10) - parseInt(preview.css('padding-bottom'), 10)  - parseInt(preview.css('border-top'), 10) - parseInt(preview.css('border-bottom'), 10))

Alguma solução?
Comment: Parece estar tudo bem aqui...
Comment: @JorgeB. vc rodou no Chrome e no Firefox?
Comment: Nos dois e deu bem...
Comment: entao eh meu firefox, mas como tratar isso pra que nao ocorra no cliente ter esses erros? tipo no Chrome a imagem eh redimensionada corretamente e no firefox nao, como tratar vc sabe? @JorgeB. poderia me auxiliar?
Comment: afinal não funciona no firefox...
Comment: a questão é que no Firefox a imagem nao redimensiona, nao seta o `max-height` na tag `` que é gerada pelo jasny, @JorgeB.
Answer: Não é um bug do .css, na verdade é uma característica que é diferente no Firefox e no Webkit (ou Blink) que por padrão o Webkit possui na propriedade border: o valor 0px none rgb(51, 51, 51) em qualquer elemento, já no Firefox (gecko) o border: sempre é vazio.
Isto é um padrão (default) de CSS do Chrome (e acredito que dos navegadores baseados em Safari também).
Ou seja ao pegar com .css("border-bottom") ele retorna vazio no Firefox e o parseInt não faz a conversão de vazio, ele retorna NaN, qualquer calculo matemático com NaN vai retornar NaN, por isto no Firefox não funciona.
Como no Chrome .css("border-bottom") ele retorna 0px none rgb(51, 51, 51) o parseInt o converte pra 0 então o calculo matemático irá funcionar.
O problema não é do jQuery ou do Firefox, o problema é da biblioteca jasny-bootstrap

NOTA:
Como citei antes eu enviei um pullrequest https://github.com/jasny/bootstrap/pull/444 pra corrigirem o código e finalmente ele foi aprovado https://github.com/jasny/bootstrap/commit/feea0e59b58cab170aefa5608ee976117c4b4f4b (depois de quase 3 meses), ainda não foi lançado um "release", mas é possivel baixar diretamente do repositório os arquivos da pasta:

https://github.com/jasny/bootstrap/tree/master/dist

Uma breve solução é fazer isto:
    // if parent has max-height, using `(max-)height: 100%` on child doesn't take padding and border into account
    if (preview.css('max-height') != 'none') {
        var mh = parseInt(preview.css('max-height'), 10) || 0
        var pt = parseInt(preview.css('padding-top'), 10) || 0
        var pb = parseInt(preview.css('padding-bottom'), 10) || 0
        var bt = parseInt(preview.css('border-top'), 10) || 0
        var bb = parseInt(preview.css('border-bottom'), 10) || 0

        $img.css('max-height', mh - pt - pb - bt - bb);
    }

Comment: Correto obrigado creio eu q resolvera aqui
Comment: @TiagoFerezin finalmente eles aceitaram o pullrequest que enviei, atualizei a resposta
Answer: Inclui a referência ao jQuery antes do Bootstrap e Jasny:
<link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet" />

<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />

<link href="https://cdnjs.cloudflare.com/ajax/libs/jasny-bootstrap/3.1.3/css/jasny-bootstrap.css" rel="stylesheet" />

Com o código actual, se utilizares a consola do browser vês que ambas as bibliotecas não foram devidamente carregadas devido à falta de jQuery (requisito obrigatório):

Uncaught Error: Bootstrap's JavaScript requires jQuery
Uncaught Error: Jasny Bootstrap's JavaScript requires jQuery
Comment: infelizmente nao mudou nada
Comment: esse erro nao da no meu firefox, nao aponta nenhum erro, apenas nao atibui o style ao img q eu quero
Comment: ja alterei agora roda no Chrome e dps roda no Firefox pra ver a diferenca, eu quero que ocorre da maneira que fica no Chrome @w00t
Comment: Ok, já vi a diferença. Podes mostrar a parte do script jQuery onde fazes o tratamento da imagem?
Comment: acho que eh esse eh o q ta dentro do jasny `// if parent has max-height, using `(max-)height: 100%` on child doesn't take padding and border into account
        if (preview.css('max-height') != 'none') $img.css('max-height', parseInt(preview.css('max-height'), 10) - parseInt(preview.css('padding-top'), 10) - parseInt(preview.css('padding-bottom'), 10)  - parseInt(preview.css('border-top'), 10) - parseInt(preview.css('border-bottom'), 10))

        preview.html($img)` @w00t
Comment: Eu nao faço no meu jquery, eu to deixando o jasny fazer, porem queria saber como tratar isso.


Why does 0.00 have zero significant figures and why throw out the implied precision?

Question: Per the accepted answer here:
How many significant figures in 0.0
Supposedly, a value like 0.00 has no significant figures. However the implication of that measurement is that the true value could actually be something like .0005, we just can't measure it. But we do know, for example, that it's not ".1".
If we were to take that value and multiply it against another measurement the result would obviously be zero, and with zero significant figures it would seemingly be correct to report the result as simply "0" - because it's bad practice to report more significant figures than necessary (correct?). But that doesn't convey anything about the true precision or accuracy of the measurement. A value of "0" doesn't tell the reader that we actually do know that the value is < 0.1.  Would we not want to report it as 0.00? And if so, why wouldn't we also say that it has 2 significant figures?
In other words, saying something has zero significant figures seems to throw out valuable information. What is the downside of handling 0 as an edge case.
FWIW - I have seen other sources explicitly say that zero values should be treated differently, but I consider those to be less reliable than this site.
Edit:
As for how I imagine handling it, it seems 0 values would be an edge case where scientific notation may sometimes be required? e.g. The measurement 0.00010 has 2 sigfigs (or in SN, 1.0e-4). A measurement with the same apparatus that reports 0.00000 should seemingly also have at least 2, but we cant determine that from the string. When ambiguous perhaps it must be written as 0.0e-4 or 0.00e-3 depending on the edge case convention? I realize the exponent is arithmetically irrelevant for the value 0, but it seems like there should be a way to convey both the precision and the uncertainty?
Just spit balling. I may be wrong about everything here!
Answer: The answer in the cited question say the right thing if you measured to 0,00 0,005 is not excluded than that is your error not 0,00 or if you know it better maybe 0,001?
Comment: How would you know that 0.005 is not excluded from the value "0"? In fact how would you know that *any* value is excluded? The uncertainty might be extremely high. The true value could be 10 million. You have no way of knowing. And according to that answer,"0" is a perfectly valid representation, because 0.00 has no sigfigs.
Comment: I don' understand. If you measure something  for example a mass or a length,  you have to know how exact your measurement is. if your measurement is 0,00g and not 0.000g you imply it could be ±0,005  otherwise you would give more exact values. So you have to say, what you mean with m=0,00g probably that your scale or measuring instrument can not measure 0,001g?
Comment: 0.00g means the apparatus can only measure to the hundredths place. That it is the limit of its precision. But according to significant figure rules, 0.00 can be written as "0". Which makes no sense to me.
Comment: This means you have m=0±0,005 g  what you should write and not m=0,00 g but writing m=0,00±0,005 is not wrong
Comment: I don't think you should write that unless you actually know it.
Comment: Because there is such a thing as "implied uncertainty" , and that's basically what Im referring to here.
Comment: I stop here, but don't understand you if your scale can only measure up to 0.00 you have ti admit of a possible error of 0,005.  if you know more you can also have 0,00±0,002 so what is the "implied uncertainty"
Comment: Im saying you *dont* have to write the uncertainty. You should be able to write 0.00 and the uncertainty is implied. And when you write 0.00 you run into the significant figures problem which is the core of my question.


Why isn't this code reversing user inputted text?

Question: System.out.println("type something to get it back reversed...");
Scanner sc1 = new Scanner(System.in);

String x = sc1.nextLine();//user input

for(int i = x.length(); i > 0; i--)
{
System.out.print(x.substring(i));
}

In this code, I want to take user-inputted text and output it in reverse order (i.e. dog = god) with a for-loop and the substring method. The above code is non-functional.
For example...
-when I input "dog", I get "gog".
-when I input "computer", I get "rerteruterputermputeromputer"
It never outputs the first letter of the text. I'd be very grateful if somebody could help me out and explain this to me :)
Comment: You know `substring(i)` will give everything from `i` to the end of the string? Maybe you want `charAt(i)`. Also, your `for` loop as the wrong endpoints.
Comment: I know how to use the charAt function, but for this particular assignment I have to use substring.
Answer: See the API for the String class. The String.substring(int index) method creates a substring from the parameter index to the end of the String (so if x is dog, the x.substring(0) results in 'dog'. Perhaps you wish to use the two parameter substring method. Also note the indexes of the loop, starting at length - 1 and ending at 0
for ( int i = x.length()-1; i >= 0; i-- ){
    System.out.print(x.substring(i, i+1));
}

Comment: What's the difference between ending at the end of the string when I use the String,substring(int index) method and ending at "i+1" in the two parameter substring method?
Comment: As explained in the answer, the single parameter substring method returns a String that starts at index and ends at the end of the String. The two parameter substring methods let's you specify the end index of the returned String
Answer: substring(i) returns everything in your string from i to the end. To get the character at position i in a string, use charAt(i).
Also, the last index of the string is x.length()-1. The first is zero. So your loop should be something like:
for (int i = x.length()-1; i>=0; --i) {
     System.out.print(x.charAt(i));
}

Answer: As copeg explained, substring() returns all characters after the character i. An easier solution would be to use charAt():
for(int i = x.length()-1; i >= 0; i--) {
    System.out.print(x.charAt(i));
}


Como validar campos numéricos no javascript?

Question: Preciso monta um código em HTML x Javascript,  com dois campos para digitação de valores numéricos e um botão de
calcular. Ao pressionar o botão calcular, a aplicação deverá emitir na tela o resultado da soma dos dois valores digitados. não estou conseguindo fazer a validação no javascript.
Comment: Se possível clique em [edit] e poste seu código.
Comment: Provavelmente o que tu queres não é validação e sim converter os valores para *int* ou *float*.
Comment: e como faço isso
Answer: Por padrão, todos os valores dos inputs vêm em como string, veja:

document.getElementById('check').addEventListener('click', function() {
  var field = document.getElementById('input');

  // Mostra o valor e em seguida o tipo:
  alert(field.value);
  alert(typeof field.value);
});
<input id="input" type="number" value="44" />
<button id="check">Clique</button>

Desse modo, precisamos transformar o valor do campo em um número.
var numberInString = '20';
var number = Number(numberInString);

console.log(typeof number); // number

Assim, creio que o que o senhor precisa seja:

document.getElementById('calc-sum').addEventListener('click', function() {
  var num1 = document.getElementById('num-1');
  var num2 = document.getElementById('num-2');

  // Transformar os valores em números:
  num1 = Number(num1.value);
  num2 = Number(num2.value);

  // Calcular a soma:
  var sum = num1 + num2;

  // Mostrar a soma:
  document.getElementById('sum').innerText = 'A soma é: ' + sum;
});
Valor 01:
<input id="num-1" type="number" />

Valor 01:
<input id="num-2" type="number" />

<input type="button" id="calc-sum" value="Calcular soma">

Nota:
Para converter as strings para números, usei o construtor Number().
Mas também poderia-se ter usado os métodos parseInt() ou parseFloat().
Comment: valeu mesmo conseguir
Comment: nulo + nulo não é zero
Answer: Partindo do principio que o resultado da soma de (vazio + vazio) ou (nulo + nulo) ou ( e + e ) ou ( espaços + espaços ) não é zero, temos

    function validarNum() {
        var x, texto;

        // Obtem os valores dos campos de entrada com id = "numero"
        x = document.getElementById("numero1").value;
        y = document.getElementById("numero2").value;

        z = (parseFloat(x)+parseFloat(y));

        if (isNaN(z)) {
            texto = "Sr. Burro, preencha os campos corretamente";
        } else {
            texto = (parseFloat(x)+parseFloat(y));
        }
        console.log(texto);
    }
    <input id="numero1">

    <input id="numero2">

    <button type="button" onclick="validarNum()">Somar</button>
Comment: Gostei do `Sr. Burro` :D
Comment: Removi aquela resposta lá dos bodes. Achei que não valia a pena porque o problema deve ser essencialmente no PHP: https://pt.stackoverflow.com/q/291375/8063
Answer: Como dito na resposta do @Luiz Felipe, é preciso converter o valor dos campos para tipo numérico. No caso aqui usei parseFloat().
Além disso, você pode usar um avaliador de curto-circuito para converter algum o campo que foi deixado vazio em 0, para evitar o NaN.
Exemplo:

function calcular(){
   var val1 = parseFloat(document.body.querySelector("#valor1").value) || 0;
   var val2 = parseFloat(document.body.querySelector("#valor2").value) || 0;
                                                                       // ↑
       // caso o campo esteja vazio ou não seja um número, o valor assume 0
   console.log(val1+val2);
}
Insira os dois valores (deixe um em branco para testar a soma):

<input id="valor1">
<input id="valor2">

<button type="button" onclick="calcular()">Calcular</button>
Comment: muito obrigado.
Comment: muito bom!sou nova nesse mundo de programação rsrs
Comment: @LeoCaracciolo É só para evitar o NaN.
Comment: @LeoCaracciolo Concordo contigo. Mas como coloquei na resposta, é apenas para converter o nulo em zero, foi só uma sugestão.


Spud Murphy tune calls for "Red Mute" on trumpet and trombone parts

Question: In my 25 years of playing, I've never heard of a "red mute". Any ideas? My bandleader said it meant a cup, but later in the song, it had us use plungers while still muted (the notation was pretty explicit), so I don't think cup is the right choice.
The arrangement was from 1942 if that helps.
Comment: The buzz-wow was popular back in the day... it had vent holes at the front of a cup mute to which one could attach buzzing paper etc.  a plunger in front of that might be what is being called for.
Comment: I've never heard of the buzz-wow. A kazoo mute sounds very interesting.
Comment: I've seen references to a Wallace red mute — but their trumpet mutes are blue (horns and euphoniums are red) — and a Montreal red mute, but can't find actual evidence of either one. In both cases, however, they are straight mutes. So I'd put my money on straight. What's the tune? Maybe there's a recording that would give a hint.
Answer: I found a few candidates on the Intarwebzz.
Here's one possible plunger-ish item,

Overall, though, I suspect this was a Murphy-specific nickname for some mute.  It is possible that the intent (based on some alleged history I found somewhere) that the players were playing into such a mute mounted on their stands, and thus adding a plunger mute to the horn itself would allow you to play with both mutes at once.
Comment: I think using "hat" or "derby" was very standard by the early '40s. Also, adding a plunger to a hat seems very odd to me.


Double integral with three variables

Question: I have a difficulty calculating the volume of a solid that is between $$z=0,y=0,x=0,
x+y+z=2 , y^2=1-z$$ .
How can I work this with double integral cause draw this its difficult.
Comment: Do you know how to graph $x+y+z  = 2$ and $y^2 = 1 - z$?
Comment: What have you done so far in terms of solving the problem? Depending on what order of variables you use, there are different ways in which the problem resolves.
Comment: I think my graph is write but i cant sketch the D region in the xy plane.In my graph $$1-y^2$$ is inside $$2-x-y$$ am i right? @MathNewbie
Comment: Well if they're asking for the volume of the solid that's in the first octant and lies above $z = 1-y^2$ and below $z = 2-x-y$, then sure, that would be the solid you want to look at.
Comment: It asks about the general volume between all this.I really cant figure it out and it gives as a result $$V=49/60$$ if this helps you what it wants.
Comment: @user3247715 i can help you with theese lectures https://www.youtube.com/playlist?list=PLGqzsq0erqU7h6_bpE-CgJp4iX5aRju28
Answer: Warning: Solution assumes diagram is drawn but OP is encouraged to draw it out, it's not too hard as long as you go step-by-step.
The best way to do this is to draw it so that the $yz$-plane is parallel to your piece of paper. Then draw your $x+y+z = 2$ plane. After that, draw more parabolas, $z = 1-y^2$, at different points on the $x$-axis with $x \geq 0$. Try to imagine a long mountain ($z = 1- y^2$) getting cut off by the plane, $ x+y+z = 2$.
Once you've got your diagram, use ideas of 'slices' (learnt from double integrals) to construct a triple integrals. This is how I view triple integrals, i.e. extend ideas from double integrals.
Imagine you are chopping a cucumber, slice by slice with a sharp knife. Then triple integrals is can be viewd like this:
$$\underbrace{\int \int}_{\text{area of each slice}} \overbrace{\int}^{\text{how far you cut}}. \tag{1}$$
Similarly,
$$\overbrace{\int}^{\text{how far you cut}}\underbrace{\int \int}_{\text{area of each slice}}. \tag{2}$$
With a diagram, this construction is extremely easy. The area of each slice can be obtained from computing the double integral of the parabola,
$$\int_0^1 \int_0^{1-z} dydz.$$
How far we cut is where the long mountain generated by $z = 1- y^2$ is cut,
$$\int_0^{2 - y - z} dx.$$
Use $(1)$, reason why is left for you ponder, to yield
$$\int_0^1 \int_0^{1-z} \int_0^{2-y-z} dydz dx = \dots = \frac{49}{60}.$$
Computation verified via Wolfram Alpha Triple Integral widget.
Remark: This is ONE way to find the volume through integration, there are many variations to this method.

Double integral with three variables


What does the minimum x that satify $x=24n+12=15m+6=11k+2$?

Question: My attempt so far was: let $x=24n+12=15m+6=11k+2$
find $x$ as the form $x=24*15*a+24*11*b+15*11*c$
$$2\equiv 24\cdot 15\cdot a\quad (mod\quad 11)\quad \Rightarrow 1\equiv 4\cdot a\Rightarrow \quad a=3\\ 6\equiv 24\cdot 11\cdot b\quad (mod\quad 15)\quad \Rightarrow \quad 2\equiv 8\cdot 11\cdot b\quad (mod\quad 5)\quad \Rightarrow 2\equiv 3\cdot b\quad (mod\quad 5)\quad \quad $$ and I stack here after finding $a$
Comment: Are  $m,n,k$ positive integers?
Comment: @1ENİGMA1,yes they are
Comment: $15m-24n=6$, $11k-24n=10$, $11k-15m=4$. So Diophantine equation is useful.
Answer: $\!x\equiv 12\pmod{\!24}\!\iff x/3\,\equiv\ \ \  4\,\pmod{\! 8}$
$\!\!\left.\begin{align}
&x\equiv \  6\!\!\pmod{\!15}\!\iff x/3\,\equiv\ \ \  2\!\!\!\pmod{ 5}\\
&x\equiv \  2\!\!\pmod{\!11}\!\iff x/3\,\equiv -3\!\!\!\pmod{\!\!11}\\
\end{align}\right\}\!\!\!\iff\!\dfrac{x}3\equiv -3\pmod{\!55}\!\iff\! \dfrac{x}3 = \color{#0a0}{-3\!+\!55j}$
$\!\!\!\bmod \color{#c00}8\!:\, 4\equiv \dfrac{x}3\equiv \color{#0a0}{-3\!+\!55}\color{#c00}j\equiv 5\!-\!j\!\!\iff\! \color{#c00}{j\equiv 1}\!\iff\! \dfrac{x}3=-3\!+\!55(\color{#c00}{1\!+\!8i})\!\iff\!\! x\equiv 156\!+\!1320i $
Comment: $\bmod 11\!:\,\ \dfrac{x}3 \equiv \overbrace{\dfrac{2}3\equiv \dfrac{-9}3}^{\Large 2 \ \ \equiv\ \ -9}\equiv -3,\ \,$ and $\,\ 2\equiv -3\pmod{\!5}\,\ $ [for completeness]
Answer: \begin{align}
   24n + 12 &= 15m + 6 \\
   8n + 4 &= 5m + 2 \\
   5m - 8n &= 2 \\
\end{align}
Since $10-8=2$ we see that $(m,n)=(2,1)$ is a particular solution. So, in general
$(m,n) = (2+8t, 1+5t)$.
Then
\begin{align}
   15m + 6 &= 11k + 2 \\
   15(2+8t) + 6 &= 11k + 2 \\
   120t + 36 &= 11k + 2 \\
   11k - 120t &= 34 \\
\end{align}
Noting that $120+34 = 154 = 14 \times 11$, we see that $(k,t) = (14,2)$ is a particular solution. So, in general, $(k, t) = (14+120u, 2+11u)$.
So, in general,
$$\begin{array}{l}
   m = 2+8t = 88u + 18 \\
   n = 1+5t = 55u + 11 \\
   k = 120u + 14
\end{array}$$
We then find that
$$\begin{array}{l}
   x = 24n + 12 = 1320 u + 276 \\
   x = 15m + 6 = 1320 u + 276 \\
   x = 11k + 2 = 1320 u + 156
\end{array}$$
The smallest positive value of $x$ is $1320$.
If you want to use congruences, then
\begin{align}\
   x = 24n + 12 &\iff x \equiv 12 \pmod{24}
                &\iff \left\{\begin{array}{l}
                         x \equiv 4 \pmod 8 \\
                         x \equiv 0 \pmod 3
                       \end{array} \right.\\
   x = 15m + 6  &\iff x \equiv 6 \pmod{15}
                &\iff \left\{\begin{array}{l}
                         x \equiv 1 \pmod 5 \\
                         x \equiv 0 \pmod 3
                       \end{array} \right.\\
   x = 11k + 2  &&\iff x \equiv 2 \pmod{11}
\end{align}
Which simplifies to
\begin{align}\
   x &\equiv 4 \pmod{8} \\
   x &\equiv 1 \pmod{5} \\
   x &\equiv 0 \pmod{3} \\
   x &\equiv 2 \pmod{11}
\end{align}
We find $N = 8\times 5\times 3 \times 11 = 1320$; so
$\dfrac N8 = 165, \dfrac N5 = 264, \dfrac N3 = 440$,
and $\dfrac{N}{11} = 120$. We compute
\begin{array}{r|cccc|l}
    & \pmod 8 & \pmod 5 & \pmod 3 & \pmod{11}\\
\hline
   165 & 5 & 0 & 0 & 0 \\
   264 & 0 & 4 & 0 & 0 \\
   440 & 0 & 0 & 2 & 0 \\
   120 & 0 & 0 & 0 & -1 \\
\hline
    660 & 4 & 0 & 0 & 0 &5\times 4 \equiv 4 \pmod 8\\
   -264 & 0 & 1 & 0 & 0 &4\times -1 \equiv 1 \pmod 5\\
      0 & 0 & 0 & 0 & 0 &2\times 0 \equiv 0 \pmod 3\\
   -240 & 0 & 0 & 0 & 2 &-2\times -1 \equiv 0 \pmod{11}\\
\hline
\end{array}
Adding, we get $x \equiv 660-264+0-240 \equiv 156 \pmod{1320}$
Comment: It can be done more simply with a couple optimizations - see my answer.


Allow editing of user content by account creator

Question: I have to create a set of user roles and permissions for sets of teams.
Users with a "coordinator" role would be able to create and manage a set of subordinate accounts.
The 'coordinator' role should also be able to edit content created by one of their own subordinates - but no one others.
If the coordinator were to change, it should be possible to assign their existing permissions and privileges in regards to their subordinates to a new user.
Is this easy to do with Drupal 8?
Answer: Your question looks like a perfect fit for the Group module, which can be used to create collections of content (nodes) that can be accessed by sets of users and with variations of access levels, such as none, read only, edit, etc.
Have a look at the answer to "What are the alternatives for the Organic groups module?" for a brief introduction to the Group module.
For this specific question, here is a blueprint of how it could be used/configured:

Group Type: Teams
Group Roles (refer to "What are the various roles supported by the Group module?" for more details):

Coordinator.
Team Member (or whatever fits), used for those who have access to a Team's content.

Groups: 1 such group for each team (simple as that ...).
Optional (not sure if you want this): If a user creates a new group, then automatically assign the "Group Owner"-role to the user who created the group.
Group permissions: grant permission to the user with role "Group Owner" to perform actions like "Add members" or "Invite members to join".

Special case: "If the coordinator were to change" (as in your question), then simply tune the permissions to grant the "Coordinator" role to another appropriate user (how easy can it be ...).
To use the Group module from within a custom module, start from its Development guide and/or have a look at its API for D7 or API for D8.
Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".
Other questions tagged with the group tag.

PS: Even though this question is related to D8, this answer applies for either D7 ...


How to hide the unflag link text once the flag is set?

Question: I have a node flag abuse and I want to remove/hide unflag link text "non-abuse" once the abuse flag is set.
How to do this in Drupal? Since I am new to Drupal, I can't think of a  solution for this.
Note: I'm using this inside the Panels module.
Answer: In Drupal 7 you can use The Flag API (JavaScript) for this

The flagGlobalAfterLinkUpdate event : This event is triggered immediately after a flag link has been updated. (Flag links appear in
  two flavors: "Bookmark this!" and "Unbookmark this!", and when we
  speak of "update" we mean this change in appearance).

    (function ($) {
        $(document).bind('flagGlobalAfterLinkUpdate', function(event, data) {
            if (data.flagName == 'yourFlagName' && data.flagStatus == 'flagged') { //dont forget to add your flag name
                var flgName = '.flag-'+data.flagName;
                $(flgName).hide('slow');
            }
        });
    })(jQuery);

Comment: Thanks for your reply! Can u please tell me where should i attach this code?
Comment: Inside your theme JS file(sites/all/themes/YourTheme/js/ or in your custom module .js file). You can add it in any of your custom javascript file. But make sure, .js file  should load on those pages.
Comment: I put the above code in sites/all/themes/myTheme/js folder but its not working. Unflag link text "non-abuse" is still displaying once the flag is flagged.How can i hide it?
Answer: In the flag settings page under FLAG ACCESS you have Roles that may use this flag Just un-check UNFLAG option for all the roles.
Comment: I have tried with it but still unflag text is getting displayed once flag is flagged.
Answer: So u  are using Panels. It would be better to add a visibility criteria on the flag link block.
For that, go to that block on the panels page -> Click on Visibility rule -> Click on Add a new Rule -> Check on Content is flagged.

So when u hit save it would show you all the flags that are there.
In my case it shows this

So select the desired flag and check the Reverse(Not) checkbox.
Hit save and it would serve your purpose.
Comment: Yeah! I have set the same in panel page and unflag link text is invisible only after the page is refreshed,without refreshing the page it is still visible once the flag is flagged.I have used views_flag_refresh module for this in my view but still i need refresh the page to make unflag link text invisible.
Answer: I am new to Drupal Javascript, but try this.  https://www.drupal.org/docs/7/api/javascript-api/managing-javascript-in-drupal-7
Declare JS in root theme .info file - put mycustomjs.js in theme root folder

(function ($) {

Drupal.behaviors.exampleModule = {
    attach: function (context, settings) {
      // Code to be run on page load, and
      // on ajax load added here
    }
  };
}(jQuery));


Precedência de operadores

Question: Estou com uma dúvida em relação a precedência de operadores em Java. Tenho o seguinte código:
int x = 2;
long y = 1 + x * 4 - ++x;

Visualizando a tabela de precedência aqui.
Ao meu ver a expressão deveria ser resolvida da seguinte forma:
1 + x * 4 - 3
1 + 3 * 4 - 3
1 + 12 - 3
y=10

Ao contrário do que coloquei, a resposta dada pelo programa em execução é y=6. Gostaria de saber porque ele realizou a multiplicação antes do incremento?
Pela tabela de precedência, incremento ao meu ver deveria ser realizado primeiro.
Answer: Seu erro foi supor que a sub-expressão ++x seria avaliada antes da sub-expressão x * 4. No momento que esta expressão é avaliada, x ainda vale 2, de modo que a resolução correta é:
(1 + (x * 4)) - (++x)   [x=2]
(1 + (2 * 4)) - (++x)   [x=2]
(1 + 8) - (++x)         [x=2]
9 - (++x)               [x=2]
9 - x                   [x=3]
9 - 3                   [x=3]
6                       [x=3]

A precedência dos operadores refere-se somente a "onde colocar os parênteses" na expressão. A avaliação, contudo, ocorre da esquerda pra direita, tal como tudo mais na linguagem de programação (ex.: ordem de avaliação dos argumentos de uma função, ordem de execução das instruções, etc).
Answer: Por que também existe a associatividade que é da esquerda para a direita. Ele não analisa todos os operadores e escolhe qual vai executar primeiro. Ele vai fazendo isto com os operandos, normalmente em duplas, da esquerda para a direita na maior parte dos casos. Só muda a direção quando a associatividade é inversa como é o caso, por exemplo, dos operadores de atribuição.
Então a multiplicação não está se misturando com com a operação de incrimento, ela é executada antes de tomar conhecimento que haverá este operação.
Tabela de precedência com associatividade.
O ideal é evitar usar operadores que causem efeitos colaterais em expressões maiores, normalmente o operador de incremento é melhor usado de forma isolada ou quando seu isolamento fica claro.
Comment: Acho que eu entendi o que você quis dizer. De fato, uma expressão sem efeitos colaterais poderia ser avaliada na ordem "folhas primeiro, subindo em direção à raiz" (i.e. operações mais precedentes sendo aplicadas antes das menos precedentes), e o resultado seria o mesmo que "galho da esquerda primeiro, galho da direita depois". Com efeitos colaterais, os resultados são diferentes. Mas note que isso é uma convenção arbitrária imposta pela linguagem de programação, pois a forma de incluir parênteses segundo a precedência e associatividade seria a mesma em ambos os casos.
Comment: Ainda que os operadores de soma e subtração associassem à direita, a ordem de execução relativa entre `x*4` e `++x` ainda seria a mesma. `1 + ((x * 4) - (++x))`. E nesse caso particular, até o resultado seria o mesmo (não seria o caso se o primeiro operador fosse um `-`)
Comment: Sim, neste caso sim, mas o que ele está imaginando é que não há nenhuma associatividade e a expressão é avaliada como um todo. Ele acha que porque o incremento é precedente ele deve ser avaliado primeiro mesmo estando na direita, e depois ir para os outros operadores.
Comment: Sim, concordo..
Answer: A expressão é da esquerda para a direita. Sendo assim:
int x = 2;
long y = 1 + x * 4 - ++x;

1 + 2 * 4 - ++x;
1 + 8 - ++2;
1 + 8 - 3;
9 - 3;
6

Precedência de operadores