Calculate the power of a paired t-test in R manually

Question: As an exercise I wanted to perform a paired t-test manually in R to refresh a lecture I had in the past. Everything went well, but then I thought about calculating the power of this paired t-test and that's where the trouble began.
I know that the power is the area under the alternative distribution minus the area of the type II error ($\beta$), which is delimited by the $\alpha$ significance level. So basically, in this example I need to find $P(X ≤ \alpha)$ of the alternative distribution that is centered around the observed mean difference I calculated, but to be frank I'm not sure how to construct that distribution. I tried to use the same procedure as for the t-statistic under the null, but that doesn't make sense, since the expected mean and the observed mean would be the same, thus the whole term would just equal 0 (1-pt((expMean - obsMean)*stdError, df). And as far as I know, t-distributions are only used under the assumption that the null hypothesis is true. From here on I'm just getting more confused and I think that I'm missing something obvious.
I used the pwr.t.test function from the pwr package to compare my result.
It would be very helpful if somebody could help me to do such tests manually, as most solutions I found elsewhere skip the part I'm trying to do manually and simply use some sort of power calculator.
The code I used:
# data
aP <- c(0.5331039, 0.4578532, 0.3129205, 0.5144858, 0.8149759, 0.4136268)
aM <- c(0.2750040, 0.5056830, 0.4828734, 0.4439654, 0.2738658, 0.3081768)

# difference between P and M
Diff <- aM - aP

# INIT t test
obsMean <- mean(Diff)
expMean <- 0
stdError <- (sqrt(length(Diff))/sd(Diff))
n <- length(aP)
df <- n - 1
alpha = 0.05

# T-statistic

T_stat <- (obsMean-expMean)*stdError; T_stat

# critical value
crit_values <- qt(c(0.025,0.975),df) # lower bound = -2.570582

p_value <- 2*(pt(T_stat, df)); p_value
p_value < alpha

# comparison
t.test(aM, aP, paired = TRUE, alternative = "two.sided")

# INIT power
obsMean <- mean(Diff)
expMean <- mean(Diff)

# power???

power <- 1-pt((expMean - obsMean)*stdError, df); power

# comparison

cohensD <- (mean(aM)-mean(aP))/(sqrt((sd(aM)^2+sd(aP)^2)/2))

pwr.t.test(n = 6,d = cohensD, type = "paired", alternative = "two.sided")

# power = 0.4210006
```

Comment: There are three "approaches" to this: (1) Use 'power and sample size' procedure in statistical software (or if you trust the site, an online calculator). (2) Simulation, which you attempt in your Question. (3) Use of non-central t distribution, where the non-centrality parameter depends on the size of difference you want to detect. // Some of the Q*As in the right margin may be relevant. Or search this site for something like `power of t test, non-centrality`// Not clear which of the three approaches you want to learn and which are only for verification.
Answer: Remember that a paired t test is a one-sample test on
differences $D_i = X_i-Y_i,$ for $i=1,2, \dots, n$ and
$D_i$ are independently $\mathsf{Norm}(\mu_D, \sigma_D).$
Consider a test of $H_0:\mu=0$ vs. $H_a:\mu > 0$ at the 5% level with $n = 25.$ You seek the power of the test against the specific alternative $\mu = \mu_a = 2 > 0.$
In order to find the power, you need to have an educated guess of the value of $\sigma.$ With $\alpha = 0.05, n = 25, \sigma = 3,$ it is possible to find $P(\mathrm{Rej\;} H_0\,|\, \mu=\mu_a).$ [Of course, if you
knew the exact value of $\sigma,$ then you would be doing a z-test instead of a t-test.]
Minitab software: Here is relevant output from a recent release of Minitab. [R and other statistical software programs have similar procedures. @dariober's Answer (+1) gives a brief mention of that--for a two-tailed test.]
The power for the specified parameters is $\pi = 0.944.$ [The probability of Type II error is $\beta = 1 - \pi = 0.065.]$
Power and Sample Size

1-Sample t Test

Testing mean = null (versus > null)
Calculating power for mean = null + difference
α = 0.05  Assumed standard deviation = 3

            Sample
Difference    Size     Power
         2      25  0.944343

Simulation. With 100,000 iterations, we can
anticipate about two place accuracy. The approximate
result from the following simulation in R is $\pi = 0.945.$
set.seed(2020)
pv = replicate(10^5, t.test(
         rnorm(25, 2, 3), alt="g")$p.val)
mean(pv <= 0.05)
[1] 0.9449

Using non-central t distribution.
The critical value for a (one-sided) test of $H_0: \mu = 0$ vs. $H_a:\mu > 0$ at the 5% level with $n = 25$ is
$c = 1.7109.$ That is, we reject $H_0$ if
$T_0 = \frac{\bar D - 0}{S_D.\sqrt{n}} \ge c.$
c = qt(.95, 24);  c
[1] 1.710882

We seek $P\left(T_a=\frac{\bar D - \mu_a}{S_D/\sqrt{n}}\ge c\right) = 0.9443,$ where $T_a$ has a noncentral t distribution
with degrees of freedom $\nu = n-1 = 24$ and noncentrality
parameter $\delta = \sqrt{n}(2)/3 = 10/3.$ [Notice that the third paramter of the R CDF function df is the non-centrality parameter.]
del = 5(2)/3
1 - pt(c, 24, del)
[1] 0.9443429

Answer: I'm cheating here... I just looked up the code for pwr.t.test and I extracted the relevant parts to produce the power of a paired, two-sided t-test:
Your input:
aP <- c(0.5331039, 0.4578532, 0.3129205, 0.5144858, 0.8149759, 0.4136268)
aM <- c(0.2750040, 0.5056830, 0.4828734, 0.4439654, 0.2738658, 0.3081768)

cohensD <- (mean(aM)-mean(aP))/(sqrt((sd(aM)^2+sd(aP)^2)/2))

pwr.t.test(n = length(aP), d = cohensD, type = "paired", alternative = "two.sided", sig.level= 0.05)
# power = 0.4210006

To manually reproduce:
n <- length(aP)
tsample <- 1 # 1 because type is paired
tside <- 2
sig.level <- 0.05
d <- cohensD

nu <- (n - 1) * tsample
qu <- qt(sig.level/tside, nu, lower = FALSE)
pt(qu, nu, ncp = sqrt(n/tsample) * d, lower = FALSE) +
    pt(-qu, nu, ncp = sqrt(n/tsample) * d, lower = TRUE)

# [1] 0.4210006

EDIT Here's an annotated version of the code above:
We want to calculate the power of a paired t-test with given type 1 error $\alpha = 0.05$ and effect size (as Cohen's d) determined by the sample pairs aP, aM. So the input is:
aP <- c(0.5331039, 0.4578532, 0.3129205, 0.5144858, 0.8149759, 0.4136268)
aM <- c(0.2750040, 0.5056830, 0.4828734, 0.4439654, 0.2738658, 0.3081768)

sig.level <- 0.05
cohensD <- (mean(aM)-mean(aP))/(sqrt((sd(aM)^2+sd(aP)^2)/2))

First, we need to find the critical value of the t-statistics that incorrectly accepts the null hypothesis in 5% of the cases. Since the test is two-sided, this means finding the values of $x$ that define the two shaded tails in the probability density function pictured below, each shaded area being 2.5% of the total area:

For this we can use the quantile function qt with $n - 1$ degrees of freedom:
df <- (length(aP) - 1)
qu <- qt(sig.level/2, df, lower = FALSE)

# Code for plot
x <- seq(-6, 6, length.out= 100)
y <- dt(x, df= df)
plot(x, y, type= 'l', lwd= 1.5, xlab= 'Value of T', ylab= 'Density')
polygon(c(x[x > qu], qu), c(y[x > qu], 0), col= "grey", border= 'black')
polygon(c(x[x < -qu], -qu), c(y[x < -qu], 0), col= "grey", border= 'black')

We can verify that the critical value qu (and -qu) defines 2.5% of the area by integrating the PDF between -Inf and -qu and between qu and Inf:
integrate(dt, -Inf, -qu, df= df) # -> 0.025 with absolute error < 6.1e-05
integrate(dt, qu, Inf, df= df) # -> 0.025 with absolute error < 6.1e-05

Now we assume the null hypothesis is false and difference between means is not zero but has the desired Cohen's d. So we are looking at the t-distribution with non-centrality parameter that makes it skewed in the direction of the effect size. This is how the R documetatiion describes the NCP:

The most used applications are power calculations for t-tests:
Let T= (mX - m0) / (S/sqrt(n)) where mX is the 'mean' and S the
sample standard deviation ('sd') of X_1, X_2, ..., X_n which are
i.i.d. N(mu, sigma^2) Then T is distributed as non-central t with
'df'= n - 1 degrees of freedom and non-centrality parameter
'ncp' = (mu - m0) * sqrt(n)/sigma.

So we have:
ncp <- sqrt(length(aP)) * cohensD

We want to know the percentage area of the t-distribution with this NCP and degrees of freedom that falls outside the critical values -qu and qu from above. I.e. we want the shaded areas below (the area on the right tail is practically invisible):

right <- pt(qu, df, ncp = ncp, lower = FALSE)
left <- pt(-qu, df, ncp = ncp, lower = TRUE)
right + left
[1] 0.42 # As per pwr.t.test()

# Code for plot
x <- seq(-12, 5, length.out= 200)
y <- dt(x, df= df, ncp= ncp)
plot(x, y, type= 'l', lwd= 1.5, xlab= 'Value of T', ylab= 'Density')
polygon(c(x[x > qu], qu), c(y[x > qu], 0), col= "grey", border= 'black')
polygon(c(x[x < -qu], -qu), c(y[x < -qu], 0), col= "grey", border= 'black')
abline(v= c(-qu, qu), lty= 'dashed', col= 'blue')

Again we can verify by integrating the PDF:
integrate(dt, -Inf, -qu, df= df, ncp= ncp) # -> 0.42 with absolute error < 1.3e-05
integrate(dt, qu, Inf, df= df, ncp= ncp) # -> 6.9e-05 with absolute error < 2.8e-08

Hope this helps (and check it's correct)!
Comment: It would presumably help the OP if you would unpack what the code is doing & what that means.  Can you use that to clear up the OP's confusion & any mistaken assumptions they're making?
Comment: I didn't say it's a bad answer.  I think it's the start of a good answer. However, although implementation is often mixed with substantive content in questions,
we are supposed to be a site for providing information about statistics (machine
learning, etc.) not code. It can be good to provide code as well, but you should try to
elaborate your substantive answer in text for people who don't read R
well enough to recognize & extract the answer from the code.
Comment: @gung-ReinstateMonica I agree, it's not a great answer. But since the OP is specifically asking for the R code to manually reproduce power, I thought this is better than nothing (I'll try to find some time to explain).
Comment: @gung-ReinstateMonica - I edited my answer with some explanation


Using \partcombine in lilypond SATB scores

Question: I have a choral piece which compiles without issue until I add the PianoStaff. I'm trying to use \partcombine to also produce a PianoStaff so that the piece is visible for piano.
I'm basing my changes on http://lilypond.org/doc/v2.18/Documentation/notation/multiple-voices#automatic-part-combining
\score {
  <<
    \new ChoirStaff \with {midiInstrument = "flute"} <<
      \new Staff <<
        \new Voice = "soprano" <<
          \global
          \sopranonotes
        >>
        \new Lyrics \lyricsto "soprano" \sopranowords
      >>
      \new Staff <<
        \new Voice = "alto" <<
          \global
          \altonotes
        >>
        \new Lyrics \lyricsto "alto" \altowords
      >>
      \new Staff <<
        \new Voice = "tenor" <<
          \global
          \tenornotes
        >>
        \new Lyrics \lyricsto "tenor" \tenorwords
      >>
      \new Staff <<
        \new Voice = "bass" <<
          \global
          \bassnotes
        >>
        \new Lyrics \lyricsto "bass" \basswords
      >>
    >>
    \new PianoStaff <<
      \new Staff <<
        \clef treble
        \partcombine \sopranonotes \altonotes
      >>
      \new Staff <<
        \clef bass
        \partcombine \tenornotes \altonotes
      >>
    >>
  >>
  \layout { }
  \midi { }
}

When I add the PianoStaff I get
choir.ly:366:9: error: unknown escaped string: `\partcombine'

        \partcombine \sopranonotes \altonotes
choir.ly:366:9: error: string outside of text script or \lyricmode

        \partcombine \sopranonotes \altonotes

Comment: Cheers. I've posted the whole `choir.ly` at https://github.com/timburgess/High_Country_Baxter  Once the cause is deduced, I can edit the original question
Answer: In your question there is a link to the v2.18 documentation, which uses \partcombine.
But your code is written in version 2.23.  And, according to the 2.23 documentation of the corresponding page:  The up to date syntax is \partCombine (with a capital C).


Dificuldade com Permissão Location Android

Question: Estou a tentar colocar a funcionar um projecto open-source encontrado na internet mas estou com alguns problemas ao tentar implementar as permissões para o Location agora exigidas pelo compileSdkVersion 23 e buildToolsVersion "23.0.1" que quero utilizar.
O código em que estou a usar pode ser encontrado aqui: https://github.com/vyshane/rex-weather
/**
 * Implement an Rx-style location service by wrapping the Android LocationManager and providing
 * the location result as an Observable.
 */
public class LocationService {
    private final LocationManager mLocationManager;

    public LocationService(LocationManager locationManager) {
        mLocationManager = locationManager;
    }

    public Observable<Location> getLocation() {
        return Observable.create(new Observable.OnSubscribe<Location>() {
            @Override
            public void call(final Subscriber<? super Location> subscriber) {

                final LocationListener locationListener = new LocationListener() {
                    public void onLocationChanged(final Location location) {
                        subscriber.onNext(location);
                        subscriber.onCompleted();

                        Looper.myLooper().quit();
                    }

                    public void onStatusChanged(String provider, int status, Bundle extras) {
                    }

                    public void onProviderEnabled(String provider) {
                    }

                    public void onProviderDisabled(String provider) {
                    }
                };

                final Criteria locationCriteria = new Criteria();
                locationCriteria.setAccuracy(Criteria.ACCURACY_COARSE);
                locationCriteria.setPowerRequirement(Criteria.POWER_LOW);
                final String locationProvider = mLocationManager
                        .getBestProvider(locationCriteria, true);

                Looper.prepare();

                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    ActivityCompat#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for ActivityCompat#requestPermissions for more details.
                    return;
                }
                mLocationManager.requestSingleUpdate(locationProvider,
                        locationListener, Looper.myLooper());

                Looper.loop();
            }
        });
    }
}

O meu problema está no 'this' da permissão, o qual tem como erro o seguinte:

checkSelfPermission(android.content.Context,String)in
  ContextCompat cannot be applied
to(anonymous
  rx.Observable.OnSubscribe,String)

Eu não sei como colocar isto a funcionar, se alguém me puder dar uma ajuda agradecia.

Eu usei o add permission check automático e deu o seguinte:
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    ActivityCompat#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for ActivityCompat#requestPermissions for more details.
                    return;
                }

Só que dá erro no "this" e eu não sei como resolver isso, e o erro decorrente é:

checkSelfPermission(android.content.Context,String)in ContextCompat cannot be applied
  to(anonymous rx.Observable.OnSubscribe,String)
Answer: A dificuldade não está no uso de permissões mas sim no entendimento do que representa a palavra chave this.
ActivityCompat.checkSelfPermission(Context, String) recebe no 1º parâmetro um objecto do tipo Context.
O código está usando this como argumento para esse parâmetro:
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)

this, dentro de um método de instância ou construtor, refere-se ao objecto actual.
Para o poder usar em ActivityCompat.checkSelfPermission() esse objecto tem de ser do tipo Context.
A chamada ao método está a ser feita dentro de um método de uma classe(interface) anónima do tipo Observable.OnSubscribe.
Usando this neste contexto, está a passar um objecto do tipo Observable.OnSubscribe quando é esperado um tipo Context, daí o erro:

checkSelfPermission(android.content.Context,String)in ContextCompat cannot be applied
  to(anonymous rx.Observable.OnSubscribe,String)

Para a classe LocationService poder usar o método ActivityCompat.checkSelfPermission() terá de ter disponível um Context.
Uma forma possível de o disponibilizar é passá-lo ao construtor,
public class LocationService {
    private final LocationManager mLocationManager;
    private final Context mContext;

    public LocationService(Context context, LocationManager locationManager) {
        mLocationManager = locationManager;
        mContext = context;
    }

    ...
    ...
}

que poderá ser utilizado no método ActivityCompat.checkSelfPermission() assim:
if (ActivityCompat.checkSelfPermission(mContext,
           Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
    ActivityCompat.checkSelfPermission(mContext,
           Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED){
    ...
    ...
}

Answer: Nas condições do Android 6.0(Api level 23) existe o Requesting Permissions at Run Time que trata-se da questão das permissões, que é bem interessante você dar lida e aprender mais. Você tem que usar o requestPermissions para liberar a permissão para utilizar a localização:
ActivityCompat.requestPermissions((Activity) context, new String[]{
                                Manifest.permission.ACCESS_FINE_LOCATION},
                        REQUEST_PERMISSION_LOCALIZATION);

Dê uma olhada nesta resposta, que vai te esclarecer melhor.


Detecting if Underscore.js is loaded

Question: This is a borderline question, but I figured it was worth asking. Is the below the most concise way to check if underscore.js is loaded, and are there any draw-backs to this approach.
typeof _  == "function" ? console.log('yes') : console.log('no');

Honestly my "real" question is as follows. Basically this is a plugin that is going to be used on alot of front-end frameworks. Some will have underscore and some will not. In order to make it universal and to use the methods provided by underscore I want to check for underscore and provide fallback if not present while electing to use it when I can.
Is this bad practice and should I not even bother with using underscore when it is present?
NOTE: Unfortunately lodash.js is not an option because I foolishly shimmed underscore.js into the require config, and people don't seem to understand the necessity of AMD compatible modules.
Comment: You shouldn't bother. Make underscore a dependency of your project and use it, or don't, and don't. You can't have it both ways; there is literally no benefit to doing so.
Comment: Well, all the test tells you that `_` is a function, not whether it is underscore.js or not.
Comment: Underscore minified is tiny.  It costs you nothing to just leave it loaded.
Comment: The environments will vary, and there is a major memory improvement when it's methods are used compared to standard JavaScript as I am dealing with very large arrays (millions) with nested objects.
Comment: @meagar I'm not sure you are understanding. It's not a project, it's a plugin for other projects which may or may not use things like composer. There is def a benefit to checking. Like when one plugin wants to load underscore even though another plugin may have already loaded it. Same thing goes for Fontawesome, Bootstrap, etc. IMO you should always check, for the sake of plugin sanity.
Answer: Given that Underscore is exported as a function, it's correct to say that performing a type check is the most concise way of checking if Underscore is available in memory.
If I get it right - for some weird reason, I gotta say -, you want to implement a feature checking so contexts that doesn't have specific method implementations will gracefully degrade.
You could simply check for Underscore and for the feature you want. Since each feature is a property of Underscore you can check if it's defined or not through type checking as well:
if(typeof _ === 'function') {
  if(typeof _.reduce !== 'undefined') {
    // fallback goes here
  }
}

Just keep in mind that depending on the feature you're trying to fallback you might lose Underscore's chaining capabilities. I would double check that.
Comment: Yeah after reading the comments I figured I also needed to check the methods exist on the function as well. Thanks though.
Answer: I also wanted to test if Lodash was loaded and this piece of code works both for Lodash and Underscore:
(function () {
    if (_.VERSION) {
    console.log('underscore loaded');
  }
})();

https://jsfiddle.net/2x0g8xyt/
Comment: like this JS throws the error (Uncaught ReferenceError: _ is not defined), better is to check like in accepted answer also for "_" as a function with typeof.

Detecting if Underscore.js is loaded


How to get the java.lang.reflect.Type of an instantiated generic type?

Question: I understand that it's not possible to do something like SomeClass<T>.class at compile time, since it's not instantiated. However, is there a way to express something like List<SomeClass>.class? The compiler wouldn't let me. But this information should be available at compile time. I could do List.class but it's too generic.
Context: I'm using Gson to serialize a class and I need to do some customization for a field which happens to be a generic type List<T>. Gson allows me to register an adapter for a certain type:
public GsonBuilder registerTypeAdapter(Type type, Object typeAdapter)

My List<T> can only be instantiated with two concrete type parameters, so I'm planning on writing two type adapters.
Answer: No, doing anything like Class<GenericType>.class is impossible.
Code like this Class<GenericType>.class has to be run either in the method/constructor or in the init/static init block. The problem is that the bytecode itself has (almost) no knowledge about generic types of the original object, so smth like:
public Class<?> getFieldClass() {
    return List<SomeClass>.class;
}

Does not work, since there is no information about List's generic type in runtime, so javac just does not let you compile that.
This is done mostly because of the backward compatibility of Java (see 4.7 Section). However, there are some meta-info about generics that is available in runtime. This is not info about the locals as we saw, but this is the info about the generics in the definition of the Type's (class, interface, enum, etc), information about the fields (like your field in object), methods and e.t.c. This information is accessible via reflection descriptors such as java.lang.reflect.Field, java.lang.reflect.Method, and so on.
The problem is that this meta-information is static. For method for instance, it just describes the generic signature, like what is the generic type accepted/returned. You cannot access any actual runtime type by using reflection.
So in your case, I suggest you rethink your class design or rethink the approach. In your current case, you just cannot get the actual generic class in runtime for List<T>, you just cannot.
Comment: Yes, JVM is very different from C# in terms of generics. Java and C# took different approaches to implement generics, therefore this difference. In Java you have type erasure therefore `List` is the same as `List` in runtime, but in the C# the generic info is not erased at compile time, so getting the parametrized type class is possible
Comment: Thanks for the explanation. Looks like JVM is quite different from .NET runtime in this regard. I also did some debugging into gson code after posting the question. It doesn't seem to know the instantiated generic at runtime of the field either. It simply treats it as `List`, which matches exactly your explanation. Oh well... I guess I'll just have to write some boilerplate code. Not the end of the world though.


Throw a dice 4 times. What is the probability `6` be up at-least one time?

Question: First time I approach a probability question (:

Throw a dice 4 times. What is the probability 6 be up at-least one time?

Intuitively, I would say: $\frac{1}{6}\times4$.
I would explain as: If you throw one time, probability is $\frac{1}{6}$.
If you do it 4 times, then multiply by 4.
According to the answers I'm wrong.
Can you explain please? thanks in advance.
Comment: But suppose you throw it 7 times. Then the probability = 1/6 x 7 > 1?
Comment: What are the odds of not getting 6 on a given roll: $5/6$. Now since each roll is an independent event, the probability is $(5/6)^n$, where $n$ is the number of rolls.
Answer: Expanding the comment of Vladimir Vargas about binomial distribution you can, alternatively, use the complementary probability to take zero 6's in the four throws:
$$P(X\ge 1)=1-P(X=0)=1-\binom{4}{0}\left(\frac16\right)^0\left(1-\frac16\right)^4=1-\left(\frac56\right)^4=\frac{671}{1296}\approx52\%$$
Answer: Throw a dice six times - are you certain to get at least one six?
The mean number of sixes in four throws is indeed $\frac 23$. But there are combinations with $2, 3 \text{ or } 4$ sixes, and these reduce the number with just one six (apply the same argument to six throws, where it is more intuitive).
If you get no sixes in four throws, there are $5$ possibilities for each throw, and therefore $5^4=625$ possibilities with no six out of the $6^4=1296$ possibilities in total. So you get the probability by taking the $1296-625 = 671$ possibilities which must include at least one six, out of the $1296$ possibilities altogether.
Answer: Use the binomial distribution:
$$\mathbb P (\mbox{"obtaining $x$ times 6 in $n=4$ random experiments"})=\binom{n}{x}p^xq^{n-x},$$
where $p$ is the probability of obtaining '$6$' and $q$ is $(1-p)$.
PS: The probability of obtaining '6' at least one time is the sum of the probabilities of getting '6' one time, getting '6' two times,..., getting '6' four times.
Answer: Consider the complement problem, there is a 5/6 probability of not rolling a six
for any given die, and since the four dice are independent, the probability of not rolling a six is (5/6)^4 = 5^4/6^4 = 625/1296. The probability of rolling at least one six is therefore
1 − 625/1296 = 671/1296 ≈ .517.
Comment: why someone put a dislike? What is wrong?


Deriving Inverse of Cumulative Distribution function

Question: let $f(x)$ be a probability distribution, and $g(x)$ be the cumulative distribution of that probability distribution (CDF)
By definition, CDF is:
$ g(x)=\int_{-\infty}^{x} f(x) dx $
Given $g(x)$, I want to find $f(x)$:
$f(x)=???$ in terms of $g(x)$, aka the inverse of this integral.
Is analytic solution possible for any f(x)?
Inverse function of a finite integral confuses me.

If we assume $f(x)=\frac{\mathrm{d} }{\mathrm{d} x} g(x)$, then does the equation balance out?
$ g(x)=\int_{-\infty}^{x} \frac{d}{dx} g(x) dx $
$g(x)=\int_{-\infty}^{x} g(x) $ ???
$g(x)=[g(x)]_x - [g(x)]_{-\infty}$ ???
since $[g(x)]_{-\infty}$ equals to zero???, hence:
$g(x)=[g(x)]_x$???
It feels right and wrong at the same time. It's probably wrong, I'm so confused.
Comment: No, an analytical solution is not always possible. Also note that a CDF outputs values between 0 and 1, so the InverseCDF is only valid for inputs between 0 and 1. See https://reference.wolfram.com/language/ref/InverseCDF.html for some general background.
Comment: I'm struggling to understand which concepts I need to understand. Is it 0) Does analytical inverse of a finite integral exist?  1) How to find analytical inverse of a finite integral?  2) How does it matter that f and g are PDFs or can they be arbitrary functions?  3) Do I need to study the derivation of what things?
Comment: I think this is a good question. I am also interested in learning more about this topic. I suggest you try browsing through StackExchange for similar questions, learn what the best way is to pose questions on this website and ask a new one. StackExchange can be difficult for beginners, as there are many rules etc. But I can assure you that it's worth the effort.
Answer: This is the Fundamental Theorem of Calculus,
We know that $$\frac{d}{dx} g(x) = \frac{d}{dx}\int_{-\infty}^x f(t) \, dt = f(x)$$

Using the property that  that integrations are anti-derivatives,
\begin{align}
\int_{-\infty}^x \frac{d}{dt}g(t) \, dt = g(x) - \lim_{t \to -\infty}g(t)
=g(x)\end{align}


Can't remove component (React JS)

Question: I use this starter pack https://github.com/wellyshen/react-cool-starter
There Inserted component UserList to Home container
when I try just comment this field with import. import UserList from '../../components/UserList';  I have error,I need remove this component
[webpack-isomorphic-tools] [error] asset not found: ./src/components/UserList/styles.scss
==>   Rendering routes error: TypeError: Cannot read property '_style' of undefined

I just remove import, why it's happens?
UserList component
import React from 'react';
import { Link } from 'react-router-dom';

import styles from './styles.scss';

type Props = { list: Array<Object> };

const UserList = ({ list }: Props) => (

User List

      {list.map(user => (

          <Link to={`/UserInfo/${user.id}`}>{user.name}1111</Link>

      ))}

);

UserList.defaultProps = {
  list: {
    id: '',
    name: '',
  },
};

export default UserList;

SCSS USERLIST
@import '../../theme/variables';
.UserList {
  color: $color-white;

  ul {
    padding-left: 17px;

    li {
      margin-bottom: 0.5em;
    }
  }

  a {
    color: $color-white;
  }
}

Comment: Can we see `src/components/UserList/styles.scs` and your UserList component, please?
Comment: updated, please check
Comment: But you already found a solution, correct?
Comment: yes I found....
Answer: Problem was in Utils/html.js
there was requere require('../components/UserList/styles.scss')._style +

Can't remove component (React JS)


PHP how to multiple rows of form via checkboxes

Question: My current form includes many rows (100s) each with several values the user can choose and they click submit for each. I would like instead to give them the option to submit multiple rows at a time by using a checkbox with one submit button.
My current code is:

    <form id='form$y' action=".htmlspecialchars($_SERVER["PHP_SELF"])." method='post''/>
    <input type='hidden' form='form$y' name='id' value='$id' />

        <input style='height:18px' form='form$y' type='date' name='date value='$date'/>

        <select name='status' form='form$y' required/>
          <option>$status</option>
          <option value='option1'>option1</option>
          <option value='option2'>option2</option>
        </select>

        <input form='form$y' type='text' name='comment' value='$comment'/>

        <input  type='submit' value='Save' />
        </form>

";

As you can see, each row is its own form. I imagine I should be using only one total form if I'm employing check-boxes instead of individual submits? Where do I go from here? Where doe the submit button belong?
I suppose I should replace the submit column with something like this:

    <input type='checkbox' name='check_list[]' value='value$y'>

I'd appreciate if someone can give me an example (based on my code) of how this should work. I did read what is already there on SO but I couldn't quite get anything to work.
Answer: Keep the Submit Button with the form
In PHP
if(!empty($_POST['check_list'])){
   // $_POST[check_list] will be an array with selected values only.
   // Do whatever you want do with the $_POST[check_list] array.
}

Answer: Use one form -
HTML
<form method="post">

    <input type='hidden' name='id[]' value='$id' />
    <input type='checkbox' name='check_list[]' value='value$y'>

        <input style='height:18px' ftype='date' name='date[]' value='$date'/>

        <select name='status[]' required/>
          <option>$status</option>
          <option value='option1'>option1</option>
          <option value='option2'>option2</option>
        </select>

        <input type='text' name='comment[]' value='$comment'/>

.......

</form>

PHP
if(!empty($_POST)) {
   if(count($_POST['check_list']) > 0 && !empty($_POST['check_list'][0])) {
       foreach($_POST['check_list'] as $key => $checked) {
          $id = $_POST['id'][$key];
          // rest of the data and processings
       }
   }
}

Comment: Thanks, that does work except for one problem. I have the `required` validation on the fields and because it's all one form its requiring info for every row. Previously, because each row was its own form with its own submit button the validation was only required if entering in data for that row.
Comment: You have to modify the validation in this case.


How to obtain confidence limits of predicted values in ARIMA?

Question: How can one obtain confidence limits of predicted values in ARIMA?
Answer: One idea would be to use the forecast package in R:
<code>library(forecast)
fit <- auto.arima(WWWusage)
fit
f <- forecast(fit,h=20)
f
plot(f)
</code>
You can also give auto.arima parameters to use, rather than allowing it to fit its own.  I'm not sure how to obtain confidence intervals for the historic period-- you could try 'rolling' through the dataset, producing 1-step ahead forecasts+confidence intervals.
Comment: Why would you want confidence intervals (or prediction intervals) for the historic period?
Comment: @Rob Hyndman: I don't know, but I wasn't 100% sure what Sharma D was asking for, so I answered it both ways.  Out of curiosity, how exactly does your forecast package calculate confidence intervals for arima models?  I recall reading somewhere that is some cases a simulation is used, but it's been a while since I've read the documentation.
Comment: Actually, the `forecast()` function just calls the `predict.Arima()` function which uses the psi method as explained by @IrishStat. For linear ARIMA models, there is no need to resort to simulation. For some nonlinear ETS models, simulation is used.
Comment: Thanks, Information provided was very much helpful. its very much easy in R than in SPSS. Regards
Comment: @RobHyndman in epidemic surveillance, for example, I'm currently want to use the CI to establish a threshold, e.g. when the count exceed that we flags it as an alarm. Does it make sense to do 'rolling' through the data set to obtain that?
Answer: The confidence limits for an ARIMA forecast are based upon the PSI WEIGHTS . The PSI WEIGHTS are easily computed by representing the ARIMA MODEL as a pure MOVING AVERAGE MODEL. One should not be dependent upon software ( any software ! ) for answers.


How to render specific block from template without rendering entire region

Question: I'm attempting to render a specific block on a page without rendering the region. I'm assuming the machine name of the block is 23 based on the URL I get when configuring the block.
example.org/admin/structure/block/manage/block/23/configure

I'm attempting to grab the block using the information I've found here
https://www.drupal.org/node/26502
My attempt at it is
$block = module_invoke('block','blockview',23);
print render($block['content']);

But I'm not having any luck.
Comment: possible duplicate of [Printing a block in node.tpl.php](http://drupal.stackexchange.com/questions/58987/printing-a-block-in-node-tpl-php)
Comment: -1 from me, because themes should never require certain blocks to be available, or modules enabled. Rendering region is the designed way to do it and shortcuts like this may hurt future developers.
Answer: Almost there it's block_view not blockview
$block = module_invoke('user', 'block_view', '2');
print render($block['content']);

Comment: Yep sorry, I tried to check it right after you answered but it told me I had to wait a bit.
Comment: oh wow, I was a lot closer than I realized. Thanks!
Comment: Glad it helped, would you make the question as answered.


Possible input focus bug in Mobile Safari?

Question: I am using the following plugin to create a virtual keyboard within a phonegap application:
http://mottie.github.com/Keyboard/mobile.html
This is working 100% fine apart from the cursor NOT appearing ONLY in Mobile Safari.
Try it, point your iOS device to that URL and watch how there's no cursor at all.
However, when you open that URL within any other desktop browser (including desktop Safari) the cursor blinks away like it's meant to.
My question is whether there's anything I can do to display the cursor in mobile safari or whether it's a bug/or requirement by Apple. Also keep in mind we don't want the native keyboard to show at all so tapping in the input field is out of the question as it spawns the native keyboard.
We want to use the virtual keyboard ONLY within our application.
UPDATE:
We are 99.9% away from submitting our application to the AppStore and we just don't want to deploy without the cursor blinking. It just looks horrible and from a usability perspective we're not even sure Apple would approve such functionality.
Our test devices are running: 5.1.1 (9B206).
EDIT:
As this may be a bug with the actual library itself. I have posted an issue on Github as well:
Mobile Safari not display caret/cursor
Answer: Unfortunately it looks like it's a bug within Mobile Safari and there is no current fix unfortunately:
Mobile Safari not display caret/cursor


Attack from anonymous proxy

Question: We got attacked by some very-bored teenagers registering in our forums and posting very explicit material using anonymous proxy websites, like http://proxify.com/
Is there a way to check the registration IP against a black list database?  Has anyone experienced this and had success?

Sorry, it didn't link my account from StackOverflow to here :(
Anyway, I used Proxify.com and got an IP of 184.108.40.206, unfortunately, Spamhaus doesn't list that IP?
Comment: And you know these are bored teenagers because...?
Answer: [ not tested, just some thoughts ]:
what you can try to do is to check ips of posters against couple of rbl servers [ just as it is done with e-mail ]. list of some rbls that can help you: http://spamlinks.net/filter-dnsbl-lists.htm#proxies. problem is such approach will introduce significant delay and degrade user experience. you can combine it together with local geoip database [ eg from maxmind ] and apply the check only to those who are coming from 'suspicious' directions.
there are also paid services that will keep updated list of proxies - eg killabot. if you are willing to pay there should be no problem with modifying their wordpress protection script and using for your website.
Comment: Its only a matter of time before you are hacked though Wordpress.
Comment: @The Rook - well - i'm talking about using this mechanizm with whatever custom application mmgn has. nothing more nothing less; besides i believe if you keep things updated [ both your php ecosystem and the blog engine itself ] - you are pretty safe. sure - if you lag behind you will get owned sooner or later.
Answer: Many proxies are tracked by the Spamhaus project.   Specifically the SBL and XBL should be used for this purpose. You can use Squid to deny hosts that are on these black lists.
There are also for pay services.  And you could even check the "x-forwarded-for" header,  but "anonymous proxies" wont' set this variable.  Further more this is an attacker controlled variable and can never really be trusted.

Attack from anonymous proxy


NSXMLParser Asynch -How do I properly Release?

Question: OK. I'm using NSXMLParser like so:
myParser = [[[BMLT_Parser alloc] initWithContentsOfURL:[NSURL URLWithString:uri]] retain];
[myParser setDelegate:self];
[myParser performSelectorInBackground:@selector(parse) withObject:nil];

I have my own subclass in order to do things like have a memory pool and some instance data. Basically, it's OK to think of BMLT_Parser as the same as NSXMLParser.
Note that I am calling it asynchronously, so there's no simple deallocation after a synchronous call.
What I have done, is declare the following delegate function:
- (void)parserDidEndDocument:(NSXMLParser *)parser  ///< The parser in question
{
    [myParser release];
    myParser = nil;
}

myParser is an instance variable of the parser. Basically, myParser == parser in the callback.
Now, the problem is that Instruments tells me that the parser is leaking. Parsers leak badly, because they pack a lot of luggage.
How else should I dealloc asych parsers? I strongly suspect that I simply need to be directed to an "M", so that I can "RTFM".
Thanks!
Answer: myParser = [[[BMLT_Parser alloc] initWithContentsOfURL:[NSURL URLWithString:uri]] retain];

In the above code, u r firstly  allocating memory for myParser by alloc, and again u r  retaining .Here, u r doing wrong as u should retain only when u have take ownership of an object.But through alloc u will get ownership of the object"myParser".
And when u have used the object, u need to release that.
you should do like something this..
myParser = [[BMLT_Parser alloc] initWithContentsOfURL:[NSURL URLWithString:uri]];
[myParser setDelegate:self];
[myParser performSelectorInBackground:@selector(parse) withObject:nil];
[myParser release];

Again, in the delegate definition, you r firstly releasing the object then setting that to nil.This is quite meaningless ,as if u don't have memory for any object, how can we set any value to that. write something like this..
- (void)parserDidEndDocument:(NSXMLParser *)parser  ///< The parser in question
    {
    if(_myParser)
        {
          [_myParser release];
        }
    }

Comment: I'm not exactly sure why you're doing that in the callback. I'll think on it some more. On another note, Instruments in Xcode 4.1/Lion completely blows chunks. I have to force quit it about 4 times out of 5.
Comment: there is no need to have ownership of the object "myParser".
Comment: OK. I got it. This wasn't 100% of my problem, but it was 95% of it.


How do I show this set is not in this $\sigma$-algebra?

Question: How do I show that set $$F= \{ f\in C[0,1]  \text{ such that  } \sup_{t \in [0,1]} f(t) < 1\} $$ is not in the $ \sigma$-algebra $ \mathcal{B} $ generated by the sets from   $$\{ f \in C[0,1], f(t_1) \in A_1, \ldots, f(t_n) \in A_n\} $$ where $ n \geq 0,t_i \in [0,1], A_i $ are intervals on $\mathbb{R}$ ?
Comment: Suppose that $ F \in \mathcal{B} $ so $ F^c \in \mathcal{B} $ also, i.e. set $$\{ f\in C[0,1], \exists t \in [0,1]: f(t) \geq 1 \} \in \mathcal{B}$$
But I don't image a set in $ \mathcal{B} $ have which form so that I can show a contradiction.
Thanks you for your help.
Answer: Proof by contradiction. Each set in $\mathcal{B}$ is of the following form:
$$\{f \in C[0,1]: f(t_i) \in M_i \, \text{for $i \in \mathbb{N}$}\}$$
where $\{t_i\}_{i=1}^\infty$ is a sequence in $[0,1]$ and $\{M_i\}_{i=1}^\infty$ is a sequence of Borel measurable sets. Suppose that there exists $B \in \mathcal{B}$ such that $B = F$. Then $B \cap F = B$ so $M_i \subset (-\infty,1)$ for all $i$. In fact, $M_i = (-\infty,1)$ since $F$ contains the family of constant functions $f(t) = c$ with $c \in (-\infty,1)$. Thus $B$ must have the form
$$\{f \in C[0,1]: f(t_i) < 1 \, \text{for $i \in \mathbb{N}$}\}$$
and the statement $B = F$ amounts to the following: there exists a sequence $\{t_i\}_{i=1}^\infty$ such that $f(t_i) < 1$ for all $t_i$ implies $f(t) < 1$ for all $t \in [0,1]$. This is false and gives the desired contradiction, as we now show.
Claim: Given any sequence $\{t_i\}_{i=1}^\infty$, there is a continuous function $f$ such that $f(t_i) < 1$ for all $i$, but $f(t) = 1$ on a set of positive measure.
Proof: We use a construction inspired by the proof that the set of rationals has measure zero. We begin with the constant function $f = 1$ and subtract tent-shaped bumps centered on each $t_i$. The first bump has height $1$ and support $\epsilon/2$ for any $\epsilon > 0$ we choose, say $\epsilon = 0.1$. The bumps after it have support $\epsilon/2^i$ and height $1/4^i$, which ensures that the tent slope decays as $1/2^i$. The sequence of functions obtained by partial sums of this series is uniformly Lipschitz and has a pointwise limit everywhere, so the limiting function exists everywhere and is Lipschitz as well. This function is less than 1 on a set of measure $\leq \epsilon$ encompassing all the $t_i$, and is equal to 1 everywhere else.


Erro na inicialização do AVD - Android Studio

Question: Quando o emulador do android é iniciado ocorre o seguinte erro:
07-22 15:14:14.669    2387-2488/com.android.systemui E/JavaBinder﹕ Uncaught remote exception!  (Exceptions are not yet supported across processes.)
    java.lang.RuntimeException: android.os.DeadObjectException
            at android.os.Parcel.writeException(Parcel.java:1389)
            at android.os.Binder.execTransact(Binder.java:410)
     Caused by: android.os.DeadObjectException
            at android.os.BinderProxy.transact(Native Method)
            at android.content.IIntentReceiver$Stub$Proxy.performReceive(IIntentReceiver.java:124)
            at android.app.ActivityThread$ApplicationThread.scheduleRegisteredReceiver(ActivityThread.java:866)
            at android.app.ApplicationThreadNative.onTransact(ApplicationThreadNative.java:395)
            at android.os.Binder.execTransact(Binder.java:404)**

07-22 15:14:23.703      690-948/? E/NetlinkEvent﹕ NetlinkEvent::FindParam(): Parameter 'TIME_NS' not found
07-22 15:14:23.732      690-948/? E/NetlinkEvent﹕ NetlinkEvent::FindParam(): Parameter 'TIME_NS' not found
07-22 15:14:28.823      690-948/? E/NetlinkEvent﹕ NetlinkEvent::FindParam(): Parameter 'TIME_NS' not found
07-22 15:14:28.837      690-948/? E/NetlinkEvent﹕ NetlinkEvent::FindParam(): Parameter 'TIME_NS' not found**

Comment: JcSaint, já tentou excluir a maquina virtual e criar novamenteo com um nome diferente?
Comment: Essa é a primeira máquina da instalação. Ao olhar o SDK Manager percebi que os packages ArmEABI v7 e Intel x86 Atom, estão quebrados (Broken) vou deletar e reinstala-los.
Answer: O recomendado é você deixar todo o seu Android SDK atualizado com os últimos pacotes disponibilizados.
Aqui no blog do Felipecosse tem um link que explica perfeitamente as configurações iguais a dos celulares que tem na lista! Basta seguir e vai tudo dar certo!
http://felipecosse.com.br/2011/06/30/criacao-do-emulador-android-adv-com-configuracoes-iguais-ao-celular/
Espero ter ajudado!
Answer: Adicione no arquivo app >> manifest >> AndroidManifest.xml
dentro da div application a seguinte tag:
android:debuggable="true"

obs: Não se esqueça de retirá-la quando for publicar o App.
Answer: Experimente verificar os itens do seu SDK.
Baixar atualizações, e, se nada funcionar, excluir o plugin da IDE e instalar novamente.
Além disso, eite dar mais de 768 de memória pra uma VM porque pode ocorrer de ela crashar mesmo.
Answer: Delete e recrie sua maquina virtual, se não funcionar tente atualizar seu SDK.
Se ainda assim não funcionar baixe outro SDK, o seu pode estar faltando arquivos.


Loader not working in Chrome

Question: I want to display a loader.
For doing this I am using the following code:
function loadnextview() {
      document.getElementById("savePop").style.display = 'block';
      $.ajax({
         type: "POST",
         url : url,
         data : {jid : jid},
         async : false,
         success : function(response){
              document.getElementById("savePop").style.display = "none";

          });
}

This works, for me in firefox but in Chrome the loader doesn't show up.
Only if a time out is added then the loader shows up. But I  do not want to add
a timeout as it will delay the process.
Thanks in Advance.
Comment: perhaps Chrome is just too fast :)
Comment: A `setTimeout` of 10 ms wouldn't be much of a delay now, would it?
Comment: try to apply alert in your ajax success.
Comment: You need to fix up your curly braces, they don't match.
Comment: `async : false`? Kinda defeating the purpose of Ajax
Comment: @asprin: setting async to false shows the loader.. but is this correct way? Because the process is not in a synchronous fashion. I wanted this behaviour also.
Comment: The loader should show up irrespective of the value of `async`
Answer: Use Hide() and Show() Function from JQuery, instead of Javascript Styling.
Use This JS Code for Solution.
function loadnextview()
{
      $("#savePop").show();
      $.ajax({
         type: "POST",
         url : url,
         data : {jid : jid},
         async : false,
         success : function(response){
            $("#savePop").hide();
            }
          });
}

Comment: if you are Testing this Code on Local Machine then you will not see the Loader because its too fast process. if you want to Test it then Comment the Line from my Function
//$("#savePop").hide();
and use it.

Loader not working in Chrome


How do i create a three column responsive footer

Question: i need assistance trying to build a three column footer in a website with wordpress. I cant seems to get the positioning of the columns right no matter how hard i try. I actually created a child theme to override the original footer that came with the theme. Can somebody help look at my code and kindly profer solutions please

Links

Our Curriculum

Why Choose us

Apply Online

News

Events/Calendar

Links

Our Curriculum

admission procedure

apply online

news

upcoming events

                Copyright &copy <?php echo date('Y'); ?> vidniel Tech

THE CSS
#footerwrap{
    width: 100%;
    position:relative;
}

#menu-footer{
    width:30%;
    float:left;
    display:inline-block;
    margin:0 20px 0 0;
}

.clear {clear:both}

#social-footer{
    width:30%;
    float: right;
    display:block;
    margin:0 20px 0 0;

}

#copyright-footer{
    width:30%;
    float:right;
    display:inline;
    margin:0 20px 0 0;
}

Banky
Comment: you need to elaborate further preferably create a codepen or js fiddle and then describe what is happening.....
Answer: Not sure what exactly you're trying to accomplish, but you should be able to overwrite all of your CSS with the below:
#footerwrap{
    width: 100%;
    position:relative;
}
#menu-footer, #social-footer, #copyright-footer{
  width:30%;
  margin:0 20px 0 0;
  display:inline-block;
  vertical-align:top;
}
@media (max-width: 750px){
  #menu-footer, #social-footer, #copyright-footer{
    width:100%;
    margin:0;
  }
}

This includes a media query for smaller screens to stack your footer below 750px.
Comment: Thanks for your assistance.hasnt worked though.im trying to overwrite d footer of the tesseract theme using a child theme for my project.i want the footer to be in 3 columns with each of d 3 classes been justified in each of d columns.column 1 will have a vertical menu while 2 will have social and contact links.col 3 will have copyright,Policy & Terms.Right now the 1st 2 columns are superimposed on each other and the 3rd not well positioned.thats my challenge now


Model validation after fitting a negative binomial GLM in R

Question: Ok, I have searched and searched and just have no clue where to start.  First, what I would like to do is produce a QQ-plot (or even a readable residual plot) to look at the fit of my model.  I guess I just don't understand how the parameters that go into qnbinom() are obtained from the output of MASS::glm.nb().  I am attempting to use probplot() from package e1071, but am unsure of the inputs needed.  It would be great if someone having experience with fitting negative binomials could lend a hand.
Secondly, I came across a residual plot here: http://www.stat.cmu.edu/~hseltman/Rclass/R8.R
I can make it to work, but I don't know how to interpret it or if I am using it correctly.  Has anyone else used this?
At the moment I am relying on the AIC and plots of fitted vs. actual values to assess the fit of my model and I would like something a little better!
Edit:
Hopefully this will clarify what I am asking.  With qnbinom(p, size, prob, mu, lower.tail = TRUE, log.p = FALSE), how do I (or is it even possible to) get the p, size, prob, mu from the output of a glm.nb fit model?  From my research, I have found that size is the dispersion parameter, but other than that I'm not sure where to go.  I know theta goes in there somehow, just not sure how to get it in the form needed.
Edit 2: Ok, once I have a distplot(), is there a guide to interpreting it?  I am fairly positive I have a bad fit because I have a curved plot with a red line going through it (with many points on the tails far from the red line).  The prob: ML = 0.011, is this rejecting that the distribution is from the negative binomial specified?
Comment: Regarding your edit: you only need size and prob OR size and mu. In the former case size is the parameter for target for number of successful trials, in the latter it is the dispersion parameter, namely theta! Both versions are related by prob = size/(size+mu). You can extract theta from the glmnbobject by object$theta and the mean you get by exp(coef(object)). See the example below. If you have a regression model, getting the mean is a bit trickier, you need to put in all the values for the x as well. Is the latter where the problems lie? See below for an example.
Comment: @Momo thanks for the detailed explanation.  I do understand I have a model which requires transformation.  This is a regression model with multiple predictors (some factors, others continuous predictors), so taking exp(coef()) just gives me a list.  Would I just multiply those all together?  Wish this distributuon was covered more thoroughly in one of my courses, but we (and our book) stopped with the Poisson and Binomial...  So, I've been left scouring the internet for info.  For the p in qnbinom(), what is supposed to be used?  I don't understand what probabilities are needed.  Thanks!
Comment: After a little research, do I get p by using ppoints(data)?  (obtained from: http://stats.stackexchange.com/questions/4987/understanding-a-quantile-quantile-plot)
Comment: One more question: In the output of summary(model), it shows sometihng like the following: (Dispersion parameter for Negative Binomial(10.1883) family taken to be 1). I thought this meant the dispersion parameter was 1, while theta was 10.1883. You seemed to imply both are the same. Am I wrong in that interpratation? Also, I found this post useful, for anyone that might reference this in the future: http://intellinexus.wordpress.com/2010/11/29/creating-a-q-q-plot/
Comment: You can find an explanation below what to do with getting the mean from the model with predictors, the second edit. But that will give you the same as fitting the intercept only model exp(coef(glm.nb(y~1))), which is the mean mu. p are the probabilities for which you want the quantiles which you must supply and does not come from glm.nb or nayone else. If you want to know the 95% Quantile, supply 0.95.
Comment: About the dispersion confusion: Given theta, the negative binomial distribution is an exponential family with a single parameter hence the dispersion parameter is set to 1 (as in the Poisson or Binomial). In the model with unknown theta, theta is also a dispersion parameter (called that way in R's nbinom) but you may call it shape parameter to avoid confusion.
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/2938/discussion-between-momo-and-user1228982)
Comment: Not enough reps to enter chat, but your comment cleared things up for me.  I couldn't find anywhere that really clarified the parameter naming in R when using nbinom, which was causing some headaches.  Thanks so much!
Comment: `glm.nb` provides the respective fitted means as: > unique(m1$fitted.values) [1] 17.95455 15.22500
Answer: You might find distplot() from the vcd package useful either for the original data (edit: you can't use it on residuals). This plots Friendly's "negativebinomialness plots" and provides how well the negative binomial model fits
distplot(response, type = "nbinomial", ...)
To obtain the parameters: glm.nb uses the "Gamma mixture of Poisson" representation. It is actually a log-linear model that is fitted, so you should get the mean as $\exp(X\beta)$.
For example, let's say your data come from a negbin with mean 5 and theta of 1 (in the alternative representation as described above). Then you can get the mean estimate simply by
set.seed(10)
df <- data.frame(y=rnbinom(100,size=1,mu=5))
m0 <- glm.nb(y~1,data=df)
m0
exp(coef(m0))
m0$theta

which are in this case 5.1 for the mean (pretty close) and 1.6 for the dispersion parameter (pretty far off).
If you fit a model for the conditional mode, you interpret it accordingly as in every other log linear model, see this discussion on stack exchange.
EDIT: If you want to know how to get the mean in a negbin regression model you need to sum up the linear predictor $X\beta$.
For example: I take the quine data and fit
m1 <- glm.nb(Days~Sex,data=quine)

now males are 1 females are 0. To get the mean for males you write
> exp(coef(m1)[1]+coef(m1)[2]*1)
[1] 17.95455

and for females
> exp(coef(m1)[1]+coef(m1)[2]*0)
[1] 15.225

Now to get the mean you must weight this with the occurence of all females and males which is
> table(quine$Sex)
 F  M
80 66

and hence the mean is
> (80/(66+80))*15.225+(66/(80+66))*17.95455
[1] 16.45685

This is confirmed by
> nb0 <- glm.nb(Days ~ 1, data = quine)
> exp(coef(nb0))
(Intercept)
[1] 16.4589

(apart from rounding errors).
Comment: Ok, so I could really just use the mean() function on my original data for mu...  that's what I was thinking but for some reason it seemed too simple.  I think I skipped over this line: nb0 <- glm.nb(Days ~ 1, data = quine)   of your explanation previously because I thought what you had might not apply to a data set with multiple predictors.  I now see what you were intending.  Thanks for all of your help!
Comment: Thanks Momo, I understand that the negative binomial is a mixture, it's just using the numbers I am given in the glm.nb output that is giving me trouble. I saw the post you mentioned, but didn't see what I was looking for. distplot looks promising, however when I tried to use it I get an error which I can't make sense of:
Error in nfreq[count + 1] <- freq : only 0's may be mixed with negative subscripts
Any ideas on that?  I had to add a constant to my dependent variaable to make the numbers positive (they should not have been negative  in the first place) Not sure if that would mess it up?
Comment: What exactly is the problem in the output? I don't quite know what it is you need to know. You get a linear predictor which you need to to take exp($X\beta$) because your model is $log(\mu)=X\beta$ with mu being the expected count. So in fact you fit this model: $mu=exp(\beta_0)*exp(\beta_1x_1)...$. This is how to interpret them, as a loglinear model.  Regarding distplot, I don't know the error, but perhaps you are right it might only take the dependent variable as an input (which must be 0 or positive integer), hence residuals may be not allowed. Can't you just use the dep. variable though?
Comment: I think my main problem is how the parameters are named in different functions vs the output from glm.nb().
Comment: Like I said: mu is exp(coef(glm.nb(y~1))) with y being the dependent variable. size is theta. prob is (size/size+mu).


Error installing MySQL: Unable to update security settings

Question: Get this error while trying to install MySQL (as a administrator):

I've chosen for just one account, the root-account.
Can anybody help me?
Answer: Please check root access and firewall.
To fix this :
<code> Ran it on a machine with full root acces
 Added all MySQL items to firewall list and ran reconfiguration of the MySQL
</code>
Comment: Thanks a lot.I've less knowledge about configuring Windows, how can I add items to the firewall list?


auto.arima not giving the best model according to information criteria

Question: I'm using auto.arima to get the best model for the MASS dataset deaths. However, auto.arima does not seem to give the best model by measures of AIC, AICc, or BIC. auto.arima code below:
> data(deaths, package='MASS')
> deaths
      Jan  Feb  Mar  Apr  May  Jun  Jul  Aug  Sep  Oct  Nov  Dec
1974 3035 2552 2704 2554 2014 1655 1721 1524 1596 2074 2199 2512
1975 2933 2889 2938 2497 1870 1726 1607 1545 1396 1787 2076 2837
1976 2787 3891 3179 2011 1636 1580 1489 1300 1356 1653 2013 2823
1977 3102 2294 2385 2444 1748 1554 1498 1361 1346 1564 1640 2293
1978 2815 3137 2679 1969 1870 1633 1529 1366 1357 1570 1535 2491
1979 3084 2605 2573 2143 1693 1504 1461 1354 1333 1492 1781 1915

> library(forecast)
> auto.arima(deaths)
Series: deaths
ARIMA(1,0,0)(2,0,0)[12] with non-zero mean

Coefficients:
         ar1    sar1    sar2  intercept
      0.4418  0.3098  0.5078  2058.2234
s.e.  0.1345  0.0973  0.0998   175.8665

sigma^2 estimated as 79455:  log likelihood=-515.07
AIC=1040.13   AICc=1041.04   BIC=1051.51

If I instead fit a ARIMA(2,1,1)x(1,1,1) model, it is better by all measures:
> Arima(deaths, order=c(2,1,1), seasonal=c(1,1,1))
Series: deaths
ARIMA(2,1,1)(1,1,1)[12]

Coefficients:
         ar1      ar2      ma1     sar1     sma1
      0.2729  -0.3270  -1.0000  -0.2985  -0.9999
s.e.  0.1356   0.1396   0.1305   0.1426   1.0106

sigma^2 estimated as 39753:  log likelihood=-413.08
AIC=838.17   AICc=839.79   BIC=850.64

Comment: What's the question?
Answer: It is not true that auto.arima is not giving you the best model in terms of information criteria (at least in your example). auto.arima did indeed select a model with higher criteria values than those generated by some other model -- but these criteria values are not comparable. Information criteria cannot be directly compared for models that have different dependent variables from the perspective of calculating the model's likelihood (see Rob J. Hyndman's blog post "Facts and fallacies of the AIC", point 4). In your example, the first model's dependent variable (from the perspective of the model's likelihood) is levels of the original variable while the second model's dependent variable (from the same perspective) is first differences of the original variable; hence, the information criteria are not directly comparable. (Another example could be modelling the variable in levels against modelling its logarithm.)
Also note that auto.arima first determines whether regular or seasonal differencing is needed by using tests (KPSS or alternatively ADF or PP for regular differencing and OCSB or alternatively Canova-Hansen fo seasonal differencing). Given that, it selects optimal AR, MA, SAR and SMA orders based on the information criterion of choice (AICc or alternatively AIC or BIC) using a local search procedure.
Comment: Thank you, Richard. Your explanation and the link to Rob Hyndman's blog is very helpful.
Answer: Period 38 is a clear outlier. auto.arima isn't looking for outliers.  Perhaps use tsoutliers package?  Read up on Tsay's work
Here is the model from Autobox. AR2 and AR12 with two outliers.  One at period 38 and one at 50. Note that the seasonal differencing is also applied to the outliers.
Adjusted variance 36960.8

[(1-B**12)]Y(T) = -131.29
+[X1(T)][(1-B**12)][(-  249.03    )]        :PULSE             4/  2    38
+[X2(T)][(1-B**12)][(-  452.25    )]        :PULSE             5/  2    50
+     [(1-  .318B** 1+  .373B** 2)(1+  .840B** 12)]**-1  [A(T)]


.map returns length of the resulting arrays for each iteration?

Question: var king = [1,2,3,4];
var kong = [55,77];
var thor = king.map(function(num) { return num + 1 });
var pan = king.map(function(num) { return kong.push(num) });

console.log(kong); // [55, 77, 1, 2, 3, 4]
console.log(thor); // [2, 3, 4, 5]
console.log(pan); // [3, 4, 5, 6] ??

I thought I understood what .map was doing, but after playing around with it, I found a result that confused me. For the result of console.log(pan), I was expecting:
[[55, 77, 1], [55, 77, 1, 2], [55, 77, 1, 2, 3], [55, 77, 1, 2, 3, 4]]

However, the result is:
[3, 4, 5, 6]

It looks like it's returning the length of each resulting array? Confused.
Answer: From the MDN:

The push() method adds one or more elements to the end of an array and returns the new length of the array.

You have an array of lengths.
Here's an implementation of what you seem to want (not changing kong because it always feels better to be functional):
var pan = king.reduce(function(arr, num) {
  arr.push((arr[arr.length-1]||kong).concat(num));
  return arr
}, []);

Comment: Ah. It was push() that I didn't understand correctly. Thanks.
Answer: You can use concat() instead.

var king = [1,2,3,4];
var kong = [55,77];
var pan = king.map(function(num) { return kong = kong.concat(num) });

console.log(pan);
Answer: push returns array length. So you have array of lengths.
You can achieve what you expect by:
var pan = king.map(function(num) {
    kong.push(num);
    return kong.slice(); // create array copy!
});

And do not forget to copy array, otherwise you will get an array with same array as elements.
Answer: Solution that is non destructive to kong

var king = [1, 2, 3, 4];
var kong = [55, 77];

var pan = king.map(function(_, i) {
  return kong.concat(king.slice(0, i + 1));
});
console.log(pan);
Answer: map applys the function you specify to each of the elements in the array. So the answers it is giving you are correct for the first array
Answer: You don't need to manually push the elements inside a map. The map operation applies your function on every element of the array and returns a new array based on results.
To be honest that's the whole purpose of the map method.


How do I attach CSS styles to all the pages?

Question: i have a theme installed his name is 'businessplus_lite' i want to add some custom style to my sub theme , but i can't see any css applicable , can anyone help me please !

.info.yml

name: mysub-theme
type: theme
description: 'my sub-theme Commissions'
core: 8.x
base theme: businessplus_lite

libraries:
  - my-sub-theme-name/my-sub-theme-style

libraries.yml

my-sub-theme-style:
  css:
    component:
      css/components/style.css: {}

Comment: Change `component` to `theme` and maybe add a `version`. Simply try to do it exactly the same as it's described in the docs: https://www.drupal.org/docs/8/theming/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme
Comment: it doesn't work bro :(
Comment: And of course you have activated the theme, set it as default and flushed cached at least twice, before checking a page in that theme via browser, right?
Comment: yeah of course bro , i have have doing all that
Comment: I'm not your bro. But good to know. Better add these information to your question.
Answer: Please try using below code
info.yml :
name: mysub-theme
type: theme
description: 'my sub-theme Commissions'
core: 8.x
base theme: businessplus_lite

libraries:
  - mysub-theme/my-sub-theme-style

mysub-theme.libraries.yml :
my-sub-theme-style:
  version: 1.x
  css:
    theme:
      css/style.css: {}

Comment: it doesn't work bro :(


How do I track the status of a node.js request?

Question: I have a node.js application that generates an image, we'll say "Image A", and then uses "Image A" to generate another image, we'll call "Composition A". If the node server receives 4 image requests at around the same time for Composition A, Composition B, Composition C, etc. all of which will require image A (the exact same image). At the moment, in this scenario the server is regenerating "Image A" 4 times causing a really inefficient image request times.
I'm trying to figure out the most efficient way to only generate "Image A" once, and use it for the subsequent 4 image requests coming in at around the same time. The problem i'm running into is that the server requests are separate.
My plan is to try and set something up like "For server request #2 for image Composition B, wait for server request #1 Image A to be complete, then use that image instead of regenerating it. I'm not sure how to specifically use the node event system to check if the first request has finished, before continuing on with the subsequent requests.
Illustration of current setup:
Frontend:

Server:
Request #1:
Generate Image A --> Generate Composition A (using Image A)
Request #2:
Generate Image A --> Generate Composition B (using Image A)
Request #3:
Generate Image A --> Generate Composition C (using Image A)
Request #4:
Generate Image A --> Generate Composition D (using Image A)
Comment: You could just cache ImageA
Comment: Thanks for the response. If I were to cache Image A in Request #1, how could I tell request #2 to check if there is another request going on, and if there is, wait for it to finish, so it can use image A in the cache
Answer: If identifier of the Image A is same across all the requests, why not pass the identifier as query param in the Composition Image URL, as follows:
<img src="compositionA?generatedImageId=<image-id>" />
<img src="compositionB?generatedImageId=<image-id>" />
<img src="compositionC?generatedImageId=<image-id>" />
<img src="compositionD?generatedImageId=<image-id>" />

If the identifier is unique in application, then, a LRU cache can be implemented on server. I will not go into code level details. But, I will give an outline of a possible solution.

Maintain a cache
One first call of a request, look into the cache.
Nothing will be there, as the cache is empty.
In that case, do the computation & cache the result mapped to the identifier.
Subsequent calls will utilize the previously computed value.

In this case, as the calls are happening simultaneously & the computation is asynchronous, a Promise of computation needs to be cached. This way, on first call, the promise can be cached immediately. Then the subsequent calls will wait on that promise. Once the promise is resolved for the first call, the remaining requests are served immediately.
Management(life time, expiry, etc.) of cache is a problem that needs to be dealt separately.
There can be different libraries found for that use case.
You can configure them for your needs.
Comment: I do have a query param that I pass, but I'm not sure how to use it to solve my issue. I don't know how to tell the server "check and see if multiple requests that have this query key are happening at the same time"
Answer: You need to do request 1 separately first and then do all the other requests.
For request 1, you should store it in cache like use a redis cache. And pass the cache key to every subsequent requests to fetch image A.
Comment: Thanks for the suggestion. This does seem like a viable method but I'd like to be able to handle this server side instead of forcing the client to get one url, wait until it's back and then send the other requests.
Comment: Okay.  So instead of waiting for the response, why don't u set some timeout for the other requests so that the first request would have by that time stored it in the cache.


Searching for a user details (including custom fields) in People Administration Page

Question: I want to search people on my people page in admin. I searched around and found this great plugin :-
User search to People Admin - This helps me search user through their email, usernames perfectly.
The only problem is that I want to search users through additional User fields I added later into the admin. As an example, each person has a Full Name as a custom field but this module is unable to search through it.
Any idea how I can achieve that?
Thanks
Answer: I recommend using Views.  With this you can create a searchable, sortable and filterable display using any format you desire, and including any fields you want.

You need Views if
You like the default front page view, but you find you want to sort it
  differently. You like the default taxonomy/term view, but you find you
  want to sort it differently; for example, alphabetically. You use
  /tracker, but you want to restrict it to posts of a certain type. You
  like the idea of the 'article' module, but it doesn't display articles
  the way you like. You want a way to display a block with the 5 most
  recent posts of some particular type. You want to provide 'unread
  forum posts'. You want a monthly archive similar to the typical
  Movable Type/Wordpress archives that displays a link to the in the
  form of "Month, YYYY (X)" where X is the number of posts that month,
  and displays them in a block. The links lead to a simple list of posts
  for that month. Views can do a lot more than that, but those are some
  of the obvious uses of Views.


PHP - Count how many days ago

Question: In my database I have a bunch of Last Login dates for my users. They are written like this:
Last Login: Apr 08 2015, 22:53:49 CEST
And:
Last Login: Apr 08 2015, 22:53:49 CET
So both CEST and CET at the end can occur.
What I'd like to do is however, is to see how many days ago that was (rounded). Is there any way I can do that with this format? It has to be in this format. I'd like to echo out the following on my website:
Last Login: Apr 08 2015, 22:53:49 CEST (46 days ago)
I can't find any examples for this format. Most of them are in milliseconds or so. Is this even possible?
I only need the days. Hours and minutes are not important.
It's basically this:
$date=date('d M Y');
Comment: Is all the entry will have same format i.e., `Last Login: Apr 08 2015, 22:53:49 CEST` ?
Comment: Yes, or "CET" at the end. It varies. But all in the database have the same format. I think first step would be to just get the "Apr 08 2015" part, and then convert that somehow
Comment: Writing answer for you :)
Comment: By the way, "Last Login:" is not included in the date. Thats just in my echo. In the database, the date looks like this only: `Apr 08 2015, 22:53:49 CET`
Answer: Step 1 :
Remove the Last part of your date i.e., CET or CE
$Date = substr($Date, 0, strpos($Date, " "));

It will the character after last spaces
Step 2
Find the Difference between current date and the extracted date by
$interval = $datetime1->diff($datetime2);

And here's the entire code :
<?php
$Date = "Apr 08 2015, 22:53:49 CES";
$Date = substr($Date, 0, strpos($Date, " CE"));
$now  = date('Y-m-d');
$datetime1 = new DateTime($Date);
$datetime2 = new DateTime($now);
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
?>

If you want to print the different message if there is 0 days difference then just check if there is 0 day difference and handle it
if ($interval->format('%R%a')=="-0")
{
    echo 'Last Login Today';
}
else
{
    echo $interval->format('%R%a');
}

Comment: That works! But how can I remove the "Last Login:" part? That's just in my echo. The actual dates are only: `Apr 08 2015, 22:53:49 CET` for example
Comment: If you see the answer i will remove the entire part and have only the content between first `:` and `,` i.e., `Apr 08 2015` So here the `Last Login` is removed. You saying about this one or what ??
Comment: In the $Date you wrote the string with "Last Login:" I only want: `$Date = "Apr 08 2015, 22:53:49 CES"`
Comment: So, in your database you will have only this `Apr 08 2015, 22:53:49 CES` ?
Comment: Yes, but I echo it on my website with "last login"
Comment: Thank you so much! :) By the way, is there a way to see if it's 0 days.  And it it's 0 days ago print "Last Login: today" ... Like: `if ($interval->format('%R%a days') == 0) { echo "Last Login: today"; }` Would this work? I don't know if it's an integer
Comment: I see your new code, but it echo "30 days", it was "46" before no?
Comment: Yes, just a min, i am checking it .. wil update in few seconds
Comment: Thanks I have updated the answer.. Now it should give the same result :)
Comment: You are amazing! I wish I can be as good as you one day! Thank you so much!!
Comment: Also do you want to print something else if there is 0 days different ?
Comment: I fixed it, I just checked if $interval == 0, then I echo "Last Login: Today" :)

PHP - Count how many days ago


How to Call a method in UI thread from another running thread in UWP?

Question: I want to call Update(int i) from inside of the Thread. I used to use BeginInvoke(), but it isn't available in UWP.
public class Viewmodel
{
 Viewmodel()
 {
   //start task
   var mainTask = Task.Factory.StartNew(() =>
   {
     MyThread();
   });
 }
 private void MyThread()
 {
    int i;
    while(condition)
    {
      //do somethings
      Update(i)
    }
 }
 private Update(int i)
 {
   //do somethings
 }
}

Answer: The below should work.
Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
    // update your UI here
    Update(i)
});

Comment: Since the original question mentioned running in a view-model class, you could use `this.Dispatcher` instead. Relying on `MainView` will cause breaks if the app ever has more than one view.
Comment: Where would I use this code, inside Task when I  would want to call `Update()`?
Comment: @AmirHusseinNargesian you can just put this inside Update() function and add your logic  within the Dispatch handler.
Answer: You can use the below code to run your code :
await Window.Current.Dispatcher.RunAsync(CoreDispatcherPriority.High/* the rank */,
() =>
{
    // run the code
});

And I have another way to do it
  await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal /*the rank*/, () => { // run the code  });

See https://stackoverflow.com/a/38175976/6116637
Comment: [The documentation](https://learn.microsoft.com/en-us/uwp/api/Windows.UI.Core.CoreDispatcherPriority) clearly says not to use the value `High`.
Comment: @PeterTorr-MSFT Thx, but I want to say you can set the rank in this.


Similarity between triangles; Double variables are a pain in the

Question: So, I have two classes, Point and Triangle, the latter having three Point members. I want to verify the similarity between two triangles.
This is the code that I came up with:
the Triangle.h:
class Triunghi
{
public:

Punct *A, *B, *C;
....

The Point.cpp:
double Point::distance(Point& a){
return sqrt((X - a.X)*(X - a.X) + (Y - a.Y)*(Y - a.Y));
}

the Triangle.cpp:
double Triangle::sideAB(){
return A->distance(*B);
}

//same thing for sideAC(), sideBC()

bool Triangle::similar(Triangle& tr){

double a[3] = { sideBC(),
    sideAC(),
    sideAB() };
double b[3] = { tr.sideBC(),
    tr.sideAC(),
    tr.sideAB() };

sort(a, a + 3);
sort(b, b + 3);

double aux1 = a[0] / b[0], aux2 = a[1] / b[1], aux3 = a[2] / b[2];

if (aux1 == aux2 && aux2 == aux3) return true;
return false;
}

The code works, but for:
triangle1: A(1,0) B(0,1) C(0,0)
triangle2: A(3,0) B(0,3) C(0,0)
it says that the triangles aren't similar. I know it's because I'm using double and whatnot.
I tried the multiplication way:
if(a[0]*b[1] == a[1]*b[0] && a[2]*b[1]==a[1]*b[2]) return true;

It doesn't work, same problem.
Also tried with comparing the angles; didn't work.
Any other ideas? I know I could use trunc() and I think it might work, but I want to know if there is a smarter way of doing this.
Thank you!
Comment: In the real world, coordinates aren't simple integer numbers, and what's more, they are inaccurate. You must learn to live with inaccurate data and practice error analysis. That said, the double data type provides far more accuracy than is needed for practical applications (except for very ill-posed problems, not the case here).
Answer: Equality is generally not what you want to test when you're dealing with floating point values. In almost all cases, you care more about "approximately equal". While there is no "approximately equal" operator in C++, you can simulate it. You just need to see if if the values are close enough. See the example for std::numeric_limits::epsilon for a possible implementation.
Answer: As Joseph Mansfield describes above.  Use greater than or less than with the std::numeric_limits::epsilon found in <limits>.  As so:
double eps = std::numeric_limits::epsilon
if((std::fabs(a[0]*b[1] - a[1]*b[0]) < eps) && (std::fabs(a[2]*b[1] - a[1]*b[2]) < eps))
     return true;


Primitive $6^{th}$ root of unity

Question: Why does any extension of $\mathbb{Q}$ that contains a root of $x^6+3$ have to contain a primitive $6^{th}$ root of unity? The roots of this equation are $\{\sqrt[6]{3}e^{\pi i/2},\sqrt[6]{3}e^{5\pi i/6},\sqrt[6]{3}e^{7\pi i/6},\sqrt[6]{3}e^{3\pi i/2},\sqrt[6]{3}e^{11\pi i/6},e^{13\pi i/6}\}$. A primitive $6^{th}$ root of unity has the form $\frac{1}{2}+\frac{\sqrt{3}}{2}i$...
I don't see how to get $\frac{1}{2}+\frac{\sqrt{3}}{2}i$ from $\sqrt[6]{3}e^{\pi i/2}$, for example.
Answer: Let $\alpha$ be such a root, then $\beta=\alpha^3$ satisfies $\beta^2+3=0$, hence ${1+\beta\over 2}={1+\alpha^3\over 2}$ is a $6^{th}$ root of $1$.
You can even verify this directly:

$$(1+\beta)^6 = 1+6\beta+15\beta^2+20\beta^3+15\beta^4+6\beta^5+\beta^6$$

Now use that $\beta^2=-3$ to reduce this to:
$$(1+5\cdot(-3)+15\cdot(-3)^2+(-3)^3)+\beta(6+20\cdot(-3)+6\cdot(-3)^2)$$
$$=(1-45+135-27)+\beta(6-60+54)= 64+0\beta $$
$$= 2^6.$$
And this is primitive as if we only cube things we get

$$(1+\beta)^3 = 1+3\beta + 3\beta^2+\beta^3 = 1-9 + \beta(3-3) = -8=-2^3.$$
Comment: $(1+\beta)^3=-8$ is easier and proves primitivity.
Comment: @lhf true, but if I'm already verifying, I find it's satisfying to see it all the way when it's not extremely cumbersome. Thanks for the feedback!
Comment: @lhf ah, good point. That is an excellent reason to change it. Much appreciated!
Comment: I don't understand. Why do we automatically have $\frac{1+\beta}{2}$ a $6^{th}$ root of $1$. And why does cubing show it is primitive?
Comment: @FTem I verified it above, so there's your proof it's a $6^{th}$ root. But it only cubes to $-1$ so the smallest power we can raise it to and get $1$ is 6, that is definition primitive.
Comment: Actually, you'd also have to prove that it squares to something other that $1$...
Comment: @lhf $\alpha$ has degree 6.

Primitive $6^{th}$ root of unity


Coin Probability question regarding binomial

Question: Question: A biased coin is flipped and the odds of getting tails is 2 to 1. If the coin is flipped 60
times; what is the variance of this experiment?
Solution:
Since odds of tails is 2 to 1 odds:
P(Tails)= $ \frac{2}{2+1} $
By complement rule:
P(Heads) = 1-P(Tails) = 1-$ \frac{2}{3} $ = $ \frac{1}{3} $
Binomial where n = 60, p=$ \frac{2}{3} $ and q=$ \frac{1}{3} $
Therefore, variance is (60)$ \frac{2}{3} $$ \frac{1}{3} $= $ \frac{40}{3} $
I am confused as to why the probability of tails is $ \frac{2}{2+1} $ , can someone explain this to me?
Also, why is this considered a binomial distribution?
Answer: We know that $\underbrace{P(\texttt{tail})}_{x}+\underbrace{P(\texttt{head})}_{y}=1$
And you have given the ratio of the probabilities: $\frac{P(\texttt{tail})}{P(\texttt{head})}=\frac21=2$
Solving the first equation for x: $x=1-y$
Inserting the expression for $x$ into the second equation.
$\frac{1-y}{y}=2$
$1-y=2y$
$1=3y$
$y=\frac13$
Thus the probability for tail is $1-\frac13=\frac23$

$\underline{\text{Another Approach}}$:
We have in total $2+1=3$ parts. $2$ parts belong to the probability of getting head.
Now you take the ratio of $2$ parts (head) and $3$ parts (total): $P(\text{head})=\frac23$.
Similar can be made for $P(\text{tail})$. Or you use $P(\texttt{tail})+P(\texttt{head})=1$
Answer: A probability is the ratio between success and all possible outcomes. Odds are the ratio between success and failure. So odds of 2 to 1 means that tails:heads = 2:1. To convert this to probability, we have to take success divided by total. Success is 2, total is 2+1=3, giving the probability as being 2/3.
A Bernoulli trial is when something can have one of two results, with a fixed probability. When several independent Bernoulli trials are performed, the distribution of results is known as a binomial distribution. Since the coin is flipped 60 times, each flip is a Bernoulli trial, and all 60 flips together give a binomial distribution.
Note that if you take the binomial H+T and raise it to the number of trials, you get (H+T)$^{60}$. Expanding that out gives you a sum of terms in which the value of each term is equal to the probability of getting that number of heads and tails, if the probabilities are substituted into H and T. For instance, one of the terms is 60TH$^{59}$. If you substitute (2/3) in for tails and (1/3) for heads, then the expression 60TH$^{59}$ evaluates to the probability of getting one tails and 59 heads.


Installing OpenCV 3.1.0 with CMake on Windows 7, opencv_ffmpeg.dll invalid hash

Question: I'm trying to install OpenCV 3.1.0 with MSVC2015 compiler using CMake. I get an error saying that the file hash is different from the expected hash. I have no access to internet on the PC this needs to be installed on. I tired to install it successfully on a PC with internet to see if I could copy those files to the PC without internet. But that didn't work as CMake deletes the files, and tries to do it it's own way. I also tried this solution, but it didn't work.
Here is the error message:
CMake Warning at cmake/OpenCVUtils.cmake:872 (message):
  Download: Local copy of opencv_ffmpeg.dll has invalid MD5 hash:
  d41d8cd98f00b204e9800998ecf8427e (expected:
  89c783eee1c47bfc733f08334ec2e31c)
Call Stack (most recent call first):
  3rdparty/ffmpeg/ffmpeg.cmake:10 (ocv_download)
  cmake/OpenCVFindLibsVideo.cmake:206 (include)
  CMakeLists.txt:536 (include)

Downloading opencv_ffmpeg.dll...
CMake Error at cmake/OpenCVUtils.cmake:895 (file):
  file DOWNLOAD HASH mismatch

    for file: [C:/OpenCV/opencv/sources/3rdparty/ffmpeg/downloads/89c783eee1c47bfc733f08334ec2e31c/opencv_ffmpeg.dll]
      expected hash: [89c783eee1c47bfc733f08334ec2e31c]
        actual hash: [d41d8cd98f00b204e9800998ecf8427e]
             status: [6;"Couldn't resolve host name"]

Call Stack (most recent call first):
  3rdparty/ffmpeg/ffmpeg.cmake:10 (ocv_download)
  cmake/OpenCVFindLibsVideo.cmake:206 (include)
  CMakeLists.txt:536 (include)

CMake Error at cmake/OpenCVUtils.cmake:899 (message):
  Failed to download opencv_ffmpeg.dll.  Status=6;"Couldn't resolve host
  name"
Call Stack (most recent call first):
  3rdparty/ffmpeg/ffmpeg.cmake:10 (ocv_download)
  cmake/OpenCVFindLibsVideo.cmake:206 (include)
  CMakeLists.txt:536 (include)

I would like to be able to install this without internet, but it proves very diffucult. Does anyone have any solutions to this?
Thanks in advance.
Comment: There is a quite complete and nice tutorial [here](https://www.youtube.com/watch?v=akAAAvGyLn0)
Answer:
I found sub-string ffmpeg.dll in opencv\sources\3dparty\ffmpeg\ffmpeg.cmake:
set(FFMPEG_BINARIES_COMMIT "8aeefc4efe3215de89d8c7e114ae6f7a6091b8eb")
set(FFMPEG_FILE_HASH_BIN32 "89c783eee1c47bfc733f08334ec2e31c")
set(FFMPEG_FILE_HASH_BIN64 "35fe6ccdda6d7a04e9056b0d73b98e76")
set(FFMPEG_FILE_HASH_CMAKE "8606f947a780071f8fcce8cbf39ceef5")
set(FFMPEG_DOWNLOAD_URL https://raw.githubusercontent.com/Itseez/opencv_3rdparty/${FFMPEG_BINARIES_COMMIT}/ffmpeg/)

ocv_download(PACKAGE ...)

Download files:
https://raw.githubusercontent.com/Itseez/opencv_3rdparty/8aeefc4efe3215de89d8c7e114ae6f7a6091b8eb/ffmpeg/{opencv_ffmpeg.dll,opencv_ffmpeg_64.dll,ffmpeg_version.cmake}
and copy it to:
opencv\sources\3rdparty\ffmpeg\downloads\%HASH%\

Then cmake.exe -G "CodeBlocks - MinGW Makefiles" .
and mingw32-make.exe
Comment: @MartinGottweis, you can download these binaries from opencv repo: https://github.com/opencv/opencv_3rdparty/tree/ffmpeg/master_20170418


Trying to understand/prove an equivalence of the definition of a pair of "jointly normal" rvs

Question: It is well-known that the following is one of the equivalent definitions of "jointly normal":
Definition 1. Let $(X_1,X_2)$ be a random vector. Then $X_1$ and $X_2$ are said to be jointly normal if and only if there exist real numbers  $\mu_1, \mu_2, \alpha_1, \ldots, \alpha_k, \beta_1,\ldots, \beta_k$ and independent random variables $Z_1,Z_2, \ldots , Z_k$ (for some $k \geq 1$), each of which has a standard normal distribution, such that
$$
\begin{align*} X & = \sum_{i=1}^k \alpha_i Z_i + \mu_1 \\
 Y & = \sum_{i=1}^k \beta_i Z_i + \mu_2.
\end{align*}  $$
I think (not entirely sure, correct me if I'm wrong) the following statement ("Definition 2") is equivalent to Definition 1:
Definition 2. Let $(X_1,X_2)$ be a random vector. Then $X_1$ and $X_2$ are said to be jointly normal if and only if there exist real numbers  $ \alpha_1, \ldots, \alpha_k, \beta_1,\ldots, \beta_k$ and independent random variables $Z_1,Z_2, \ldots , Z_k$ (for some $k \geq 1$), each of which has a normal distribution, such that
$$
\begin{align*} X & = \sum_{i=1}^k \alpha_i Z_i  \\
 Y & = \sum_{i=1}^k \beta_i Z_i.
\end{align*}  $$
Notice that, in contrast to Definition 1, in Definition 2 the rvs $Z_i$ need not necessarily have the standard normal distribution (any normal is fine).
I want to show the equivalence of the two definitions given above. It is obvious that Definition 2 implies Definition 1. I have not been able to show that Definition 1 implies Definition 2; I do have some partial results, namely under the extra assumptions that $k=2$ and $\alpha_1 \beta_2 - \alpha_2 \beta_1 \neq 0$ I managed to prove it. Of course the general idea is to "absorb" the $\mu$s inside the rvs, but unfortunately I haven't been able to do it. Can someone point out a proof or sketch? Thanks a lot. Alternatively, if someone knows a reference where this is shown, that would also be great!
Answer: We have equivalence of the two definitions provided that any of the $Z_i$ in Definition 2 is allowed to be a degenerate normal variable with standard deviation zero, i.e., a constant.  Notice that under Definition 1 it's possible to achieve a jointly normal distribution $(X,Y)$ where both $X$ and $Y$ are nonzero constants. But this is never possible if every $Z_i$ in Definition 2 is required to be nondegenerate normal.
So given that we can take $Z_{k+1}=1$ in Definition 2, the proof that Definition 1 implies Definition 2 is trivial.
Comment: Thank you. In general, a degenerate rv is considered normal in this context, right? E.g., the theorem that a random vector is jointly normal iff any linear combination of its components is normal, also presupposes this I believe. (Indeed, if we e.g. were to pick all coefficients to zero, then we'd get that the constant 0 r.v. would have to have the normal distribution.)
Comment: Yes, under every definition of "jointly normal" that I know of, the (univariate) components of a jointly normal random vector are allowed to be constant.
Comment: @herbhofsterd Since the problem seems to be solved, you might want to [mark one of the answers as accepted](https://math.stackexchange.com/help/someone-answers) by clicking the check mark (✓) icon next to the answer on the left. Doing so will mark the question as answered, and will also award both you and the author of the answer a few reputation points.  Once you gain enough rep (15 points is enough), you can also vote up any answers you find helpful.


Why do long distance triathlon (ironman) races have the running course through paved roads?

Question: After looking through a number of ironman (*) running race courses, it seems all of them are laid out to run through cities, which implies paved/asphalt roads. Is that because this way it makes it easier (better) for spectators? Or is there another explanation? From my limited experience (hobby long distance runner/cyclist and occasional swimmer) it sure feels like it's much better to run on trails and dirt roads than on paved ones....
(*) I'm referring to the distances, not the brand
Answer: Usually it is a logistics issue. Consider the same question, as to why almost all marathons are usually pavement/road based.
It is very hard to find 26.2 Miles of trails.
Then consider the case of an Ironman distance race, where the prospective host city must find suitable swimming for 2.4 Miles, and 112 Miles of bike route that can be secured/closed.
Then require it to be on trails?  Good luck finding such a place.
Ironman Wisconsin in Madison, WI has a multiple mile segment run on sort of dirt trails.  My memories of that race from 2003 are sufficiently faint that I do not remember which segment was on dirt, but I remember the dirt trail.
Ironman Couer D'Alene, Idaho had a sort of trail/path segment on the run as well, same faded memory excuse on more details.
I recall reading that the old Roth Challenge Ironman distance race was mostly run on trails. This memory was in the context of the Hoyts, (A father son team, where the son has Cerberal Palsey, and his dad has done many marathons and ironman distance races) and a complaint that his running time was terrible due to the off road nature taking a toll on his running wheel chair he was pushing.
On a side note, the Hoyts are just amazing.
Comment: thanks for the examples too! It was ignorant of me not to consider the special need runners - thanks for reminding me! Plus I was hoping there would be a historic explanation, not just logistics/convenience :) I'll leave the question open for some more time in case more answers are forthcoming
Answer: A long off-road course is difficult to design.  You have to find a course that is wide enough to handle large crowds and in good enough condition to avoid injury.  Finding a suitable course that is marathon-length is very difficult.
The XTERRA off-road races manage to do this, although they are not Ironman length.  Nationals next weekend in Utah is 1.5K swim/28K mountain bike/10K trail run.  XTERRA also holds trail run-only races as long as 25K.