What do normal residuals mean and what does this tell me about my data?

Question: Pretty basic question:
What does a normal distribution of residuals from a linear regression mean? In terms of, how does this reflect on my original data from the regression?
I'm totally stumped, thanks guys
Answer: Linear regression in fact models the conditional expected values of your outcome. That means: if you knew the true values of the regression parameters (say $\beta_0$ and $\beta_1$), given a value of your predictor X, filling that out in the equation
$$
E[Y|X] = \beta_0 + \beta_1 X
$$
will have you calculate the expected value for $Y$ over all (possible) observations that have this given value for $X$.
However: you don't really expect any single $Y$ value for that given $X$ value to be exactly equal to the (conditional) mean. Not because your model is wrong, but because there are some effects you have not accounted for (e.g. measuring error). So these $Y$ values for a given $X$ values will fluctuate around the mean value (i.e. geometrically: around the point of the regression line for that $X$).
The normality assumption, now, says that the difference between the $Y$s and their matching $E[Y|X]$ follows a normal distribution with mean zero. This means, if you have an $X$ value, then you can sample a $Y$ value by first calculating $\beta_0 + \beta_1 X$ (i.e. again $E[Y|X]$, the point on the regression line), next sampling $\epsilon$ from that normal distribution and adding them:
$$
Y'=E[Y|X] + \epsilon
$$
In short: this normal distribution represents the variability in your outcome on top of the variability explained by the model.
Note: in most datasets, you don't have multiple $Y$ values for any given $X$ (unless your predictor set is categorical), but this normality goes for the whole population, not just the observations in your dataset.
Note: I've done the reasoning for linear regression with one predictor, but the same goes for more: just replace "line" with "hyperplane" in the above.
Comment: This confusingly implies the *errors* $\epsilon$ are the *residuals* in a regression--but they are not.  This is an issue because many people fail to distinguish the concepts.
Comment: @MSIS That sounds right.
Comment: This is a great explanation! One question though: e being normally distributed would mean that you assume that the most likely values for e are between -1 and +1 (after they were standardized)? So you basically use a normal distribution instead of, say, a poisson distribution, because the normal distribution better models how these values behave in real life?
Comment: I'm aware that linear regression can be equivalently derived in multiple ways, one of which is this MLE estimate type motivation. But how would you arrive at a similar reason for normality of residuals, starting from the motivation of trying to minimize sum of squared errors?
Comment: @whuber: So then the residuals are then the errors in the linear approximation obtained  from the sample data, not from the " actual" regression line which is unknowable?
Answer: Normality of the residuals is an assumption of running a linear model. So, if your residuals are normal, it means that your assumption is valid and model inference (confidence intervals, model predictions) should also be valid. It's that simple!
Comment: The normality assumption is about unobservable error (hence the need for an assumption), not about observable residuals.
Comment: Yeah, but you use the residuals to test your assumption about the unobservable error.
Comment: I do not agree that normal residuals guarantee a valid regression model. Suppose you have a circular Gaussian model with X and Y error that are equal. Then the regression line confidence interval is $-\infty \text { to } \infty$. That is hardly the only counter example, there are many more.
Comment: Thank you. Your answer is helpful.
Answer: It could mean a lot or it could mean nothing.  If you fit a model to get the highest R-Squared it could mean that you have been foolish.  If you fit a model to be parsimonious in that the variables are necessary and needed and care for identifying outliers then you have done a good job.  Take a look here for more on this http://www.autobox.com/cms/index.php?option=com_content&view=article&id=175
Answer: In some cases, the assumption that the data is approximately linear allows us to use OLS to minimize the number of observations in the data out that are far from a straight line.
Then the residual is the difference between the true value and fitted value, and we hope this difference is appproximately zero.
But in most real-life cases, the appropriate data is not linear, so we can use some treatment methods or some methods of estimation such as robust tools.
Comment: This answer doesn't really address the question, presumably why it was downvoted.


indirectly convex

Question: Let g:$\mathbb{R^2}$$\rightarrow$$\mathbb{R}$ be defined by g(x)=Max{$x_1$,$x_2$} at each x=($x_1$,$x_2$)$\in$ $\mathbb{R}$. Determine whether or not g is indirectly convex on $\mathbb{R^2}$.
definition:
let f:$\mathbb{R^n}$$\rightarrow$$\mathbb{R}$ be a function. We say that f is indirectly convex if there exist F:$\mathbb{R^n}$$\rightarrow$$\mathbb{R}$ and h:$\mathbb{R}$$\rightarrow$$\mathbb{R}$ such that F is convex, h is increasing with $f=h \circ F$.
Comment: Don't you mean $f=h\circ F$?
Comment: yes, that is exactly right.
Comment: And $g(x) = \max\{x_{1},x_{2}\}$ instead of $x_{i}$?
Comment: yes that is true too
Comment: Convexity seems to imply indirect convexity. So why not $F=g$ and $h(x)=x$?
Answer: Convexity implies direct convexity, and $g$ is convex. So simply choosing $F=g$ and $h(x)=x$ will suffice.
EDIT: coffeemath makes a fair point: what if you don't know that $\max$ is convex; that is, what if you have to prove it? I omitted that because in my experience, $\max$ is one of the first functions you get to put in your "atomic convex function toolbox." But if you can't do that yet, his approach is simple: $\max\{a,b\}=\tfrac{1}{2}(a+b+|a-b|)$, which is the sum of a linear function $a+b$ and a convex function $|a-b|$, scaled by a positive constant. Hence it is convex.
Comment: Yes, and $g$ convex follows from $\max(a,b)=1/2(a+b+|a-b|).$ And +1
Comment: Good stuff. In my experience $\max$ is treated as one of the "basic" convex functions. But if it's not, coffeemath's expression is a great way to show it.
Answer: Indirect convex implies convex sub-level sets $V_a = \lbrace x | f(x) \leq a \rbrace$ and that higher level curves contain lower ones.  This could be the exact condition, and it is true for $g(x)$.

indirectly convex


Translation not working for custom user roles

Question: I am using the i18n module. I created 2 custom roles: venue user and customer user. When I log in as administrator user, the translation is working fine; when we log in either as venue user or customer user, the translation does not work.
How can I solve this problem?
Answer: You need to grant translation related permissions for the two roles you have created. For changing the permissions, go to <code>/admin/people/permissions</code>, then set the translation related permissions for the two roles.
If you want the two roles to translate content, then you need to grant Translate content permission for the roles.
Comment: I have already given the permission but its work only for admin user not anyone login . Or without login its working fine .


Truncated BCH expansion

Question: Is it true that once a term in the Baker-Campbell-Hausdorff expansion is zero, then all the following terms must also be zero?
For example, it is not immediately obvious to me that if
$[Y, [X, [X, Y]]]=0 $, then a term such as $[Y,[Y,[Y,[Y,X]]]]$ is zero too. Is there an easy way to see it?
Answer: It isn't true.  For a semi-random example, take
$$ X = \pmatrix{17 & 3\cr 6 & 9\cr},\ Y = \pmatrix{0 & 1\cr 2 & 3\cr} $$
Then $[Y,[X,[X,Y]]] = 0$ but
$$[Y,[Y,[Y,[Y,X]]]] = \pmatrix{1156 & 867\cr 1734 & -1156}$$

Truncated BCH expansion


'Implicit' synchronization in java?

Question: when I have a method like
public void unsynchronizedMethod(){
  callSynchronizedMethod();
  //dosomestuff after this line
}

does it mean that all content, after calling callSynchronizedMethod() in the unsynchronizedMethod()-Method, is implicitly synchronized?
Answer: No. The lock is released at the end of callSynchronizedMethod().
Answer: Synchronization is defined in a straightforward manner:

For a synchronized method: within the execution of that method
For a synchronized block: within the execution of that block

Here are the relevant excerpts from Java Language Specification 3rd Edition:
JLS 14.19 The synchronized Statement

A synchronized statement:

acquires a mutual-exclusion lock on behalf of the executing thread,
executes a block,
then releases the lock.

While the executing thread owns the lock, no other thread may acquire the lock.

synchronized methods is semantically identical to a synchronized statement applied to the whole method (§JLS 18.104.22.168. The lock is obtained from either this (if it's an instance method) or the Class object associated with the method's class (if it's a static method; you can't refer to this in a static context).
So to answer the original question, given this snippet:
public void unsynchronizedMethod(){
  callSynchronizedMethod();

  doSomeUnsynchronizedStuff(); // no "implicit synchronization" here
}

Note that this is by design: you should always strive to minimize synchronization to only critical sections. Outside of those critical sections, there is no lingering effect from earlier synchronization.
See also

Effective Java 2nd Edition, Item 67: Avoid excessive synchronization

Related questions

 What is the difference between a synchronized method and synchronized block in Java ?
 synchronized block vs synchronized method?
Answer: No, it's not.
Synchronized means that only one thread at a time will execute the code.
But after callSynchronizedMethod() the threads could run again over the code in different order, all at at the same time.
Answer: No, there wont be an implicit synchronisation. Synchronized works within a block or function scope. Anything outside a synchronized block is not synchronized.
The following example code shows that. If the methods where synchronized it would always print 0.
class example extends Thread{
   //Global value updated by the example threads
   public static volatile int value= 0;
    public void run(){
    while(true)//run forever
       unsynchMethod();

   }
   public void unsynchMethod(){
     synchronizedMethod();
    //Count value up and then back down to 0
    for(int i =0; i < 20000;++i)
       value++;//reads increments and updates value (3 steps)
    for(int i = 0; i < 20000;++i)
       value--;//reads decrements and updates value (3 steps)
      //Print value
      System.out.println(value);
   }
   //Classlevel synchronized function
   public static synchronized void synchronizedMethod(){
      //not important
   }
   public static void main(String... args){
    example a = new example();
    example b = new example();
    a.start();
    b.start();
   }

}

My Results, should have been 0 if synchronized:
4463
6539
-313
-2401
-3012
...

'Implicit' synchronization in java?


Loop em Python pedindo reentrada de dados

Question: Estou com um problema em meu código em Python, ele está dando loop. Toda vez tenho que inserir a lista novamente para mostrar os resultados.
Alguém poderia me ajudar?
Segue o código:
import numpy as np
import pandas as pd
import statistics as st
from collections import defaultdict

lista = []

def vetor(lista):
    print('\nREGRAS NA FORMAÇÃO DA LISTA:\n'
          '1.Um dos valores tem que estar repetido\n'
          '2.O conjunto de dados deve apresentar, pelo menos, 6 valores únicos.\n'
          '3.NÃO É PERMITIDO escolher todos os números iguais.\n'
          '4.A LISTA POSSUI APENAS 12 ELEMENTOS\n')

    for i in range(0, 12):
        elementos = int(
            input('Elemento inserido no índice {}: '.format(i)))
        lista.append(elementos)
    return (lista)

print('A sua lista é: ', vetor(lista))
print('A média dos índices é: {:.4f} '.format(np.mean(vetor(lista))))
print('A moda é: {:.4f} '.format(st.mode(lista)))
print('A Mediana é: {:.4f} '.format(st.median(vetor(lista))))
print('A variância amostral é: {:.4f}'.format(st.pvariance(vetor(lista))))
print('O desvio padrão amostral é: {:.4f}'.format(st.stdev(vetor(lista))))
print('O coeficiente de variação é: {:.4f}'.format(st.variance(vetor(lista))))

Answer: Mude o nome da função vetor para algo que deixe claro o intento de ler dados do usuário e armazene os resultados numa variável, garantindo que essa função seja chamada uma e somente uma vez. Por exemplo:
import numpy as np
import statistics as st

def ler_dados():
    lista = []
    print('\nREGRAS NA FORMAÇÃO DA LISTA:\n'
          '1.Um dos valores tem que estar repetido\n'
          '2.O conjunto de dados deve apresentar, pelo menos, 6 valores únicos.\n'
          '3.NÃO É PERMITIDO escolher todos os números iguais.\n'
          '4.A LISTA POSSUI APENAS 12 ELEMENTOS\n')

    for i in range(0, 12):
        elemento = int(input('Elemento inserido no índice {}: '.format(i)))
        lista.append(elemento)
    return lista

lista = ler_dados()
print('A sua lista é: ', lista)
print('A média dos índices é: {:.4f} '.format(np.mean(lista)))
print('A moda é: {:.4f} '.format(st.mode(lista)))
print('A Mediana é: {:.4f} '.format(st.median(lista)))
print('A variância amostral é: {:.4f}'.format(st.pvariance(lista)))
print('O desvio padrão amostral é: {:.4f}'.format(st.stdev(lista)))
print('O coeficiente de variação é: {:.4f}'.format(st.variance(lista)))

Answer: Você está chamando a função todas as vezes em que faz um print() nas ultimas linhas. Ou seja cada na primeira vez você vai chamar a função para "printar" 'A sua lista é: ', depois você chama ela de novo para "printar" 'A média dos índices é: {:.4f} '.
Você deveria salvar isso em um variavel assim no .format() você à colocaria. Por exemplo:

valores = vetor(lista)

def vetor(lista):
    #código

print('A sua lista é: ', valores)
print('A média dos índices é: {:.4f} '.format(np.mean(valores)))
#continuação do código


C++: The choices of initializing a member class with no implicit default constructor (more constraints in question body)

Question: boost::posix_time::time_duration has three constructor overloads, and no implicit constructor. I need to make some calculations in a class which has some time_duration members before I can initialize them. All of this implies that without a default constructor I do not have the luxury of preparing input for my class members in my composing class constructor.
The pattern might be described as follows (which is eroneous):
class X {
public:
    x(int i,int j){}
};

class Y {
  x _x;
public:
    y() {i = 1+1; j=1-1; _x(i,j);}
};

int main()
{
    return 0;
}

I would like some relevant ways of constructing Y (with motivation), where

X does not have a default constructor.
X cannot be altered directly (but can be subclassed).
The generated code is deterministic (no unnecesary expensive constructs malloc/vtables etc).
crucial point The class Y has n X members and m possible calculations. Where n >1 and m > 1. So elegance is important.
Unit testing considerations are important.

At this point I am leaning towards either subclassing , or calling functions to do the calculations and calling these functions in the initialization list (if that is even possible). You can comment on these approaches :D.
Comment: Is `time_duration` assignable? The version I have installed is both default-constructible and assignable, but is kind of old. If it's assignable, and you don't want to calculate the correct value in the initializer list, then just initialize it to some dummy value like `seconds(0)`, and assign the correct value in the constructor. If you're calculating multiple durations from multiple inputs, then doing it all in functions called from the initializer list might result in some duplicated work, so reasonable to avoid that.
Answer: Sorry if I misunderstood your question, but isn't Boost.Optional a solution to your problem ? That's probably the best way to achieve a default uninitialized state without going for pointers and dynamic allocation.
However, although that would work, it's probably not ideal. My solution of choice would probably be, if possible, to move the calculations in free functions in an anonymous namespace :
namespace {
    x computeX()
    {
        int i, j = /* ... */;
        return x(i, j);
    }
}

y::y()
  : _x(computeX())
{
    /* ... */
}

Comment: Indeed (+1) That hit me when I was driving to work today :D. I'm not familiar with the details, AFAIK optional will enlarge the composing class -- at least if it uses a variable for state, no ?
Comment: @Hassan: yes, there is an additional boolean in each `boost::optional`


Find closed form solution using generation function for the binomial coefficients

Question: I don't have any idea how to start this problem. Could you give a hint?
Find closed form solution using generation function for the binomial coefficients:
$$a_n:=\sum_{k=0}^{n}\binom{n}{k}^2(-1)^k$$
Comment: $$\sum_{k=0}^n{n\choose k}^2={2n\choose n}=\frac{(2n)!}{n!^2}$$
Comment: Show that $a_n=0$ when $n$ is odd, and $(-1)^n \binom{2 n}{n}$ when n is even.  The resulting series expansion may look familiar to you.
Comment: I could get for odd case,  but cannot get for even case.  Can you help me,  please?
Answer: Note that:  $a_n=\sum_{k \geq 0} \binom{n}{k}^2(-1)^k=\sum_{k \geq 0} \binom{n}{k} (-1)^k \times\binom{n}{n-k}  $, since $\binom{n}{n-k}=\binom{n}{k}$, this is readily a convolution (of the coefficients of $(1-x)^n$ and the coefficients of $(1+x)^n$).
Looking closely, this is $$a_n=[x^n]\left\{(1-x)^n (1+x)^n\right\} = [x^n]\left\{(1-x^2)^n\right\}$$
Thus it follows that if $n$ is odd, then $a_n = 0$, because $(1-x^2)^n$ has only even powers of $x$. And, if $n$ is even, then $a_n = \binom{n}{n/2} (-1)^{n/2}$ by the Binomial Theorem.
Notation: $[x^n]\left\{p(x)\right\}$ denotes the coefficient of $x^n$ in $p(x)$.
Answer: This is one of these hypergeometric sums where it is not easy to make progress without using Sister Celine's method / Zeilberger's algorithm, which is not difficult to implement, at least in its basic form.
This algorithm produces the following recurrence for your sum:
$$n a_n+4(n-1) a_{n-2} = 0.$$
Note that we have $a_0=1$ and $a_1=0.$
Re-write the recurrence so that it becomes apparent that it produces a product:
$$a_n = -4\frac{n-1}{n} a_{n-2}.$$
This implies that for $n$ odd, we have $a_n = 0,$ and for $n$ even, we have
$$a_n = (-4)^{n/2} \prod_{k=1}^{n/2} \frac{2k-1}{2k}
= (-4)^{n/2} \prod_{k=1}^{n/2} \frac{(2k-1)2k}{(2k)^2}
= (-4)^{n/2} n! \frac{1}{4^{n/2}} \prod_{k=1}^{n/2} \frac{1}{k^2}\\
= (-1)^{n/2} \frac{n!}{(n/2)!^2} = (-1)^{n/2} {n\choose n/2}.$$
Now the generating function of the central binomial coefficients is well known and given by
$$\frac{1}{\sqrt{1-4z}}
=\sum_{n\ge 0} {2n\choose n} z^n.$$
To match up the coefficient $z^n$ with ${n\choose n/2}$ we evidently have to replace $z$ by $z^2$ in this generating function (which also has the nice effect of producing zero values for odd indices of $a_n$ as required), getting
$$\frac{1}{\sqrt{1-4z^2}}
=\sum_{n\ge 0} {2n\choose n} z^{2n}.$$
Finally add in the sign, noting that $i^{2n} = (-1)^n,$ where $i$ is the imaginary unit, for the end result
$$\frac{1}{\sqrt{1-4(iz)^2}} = \frac{1}{\sqrt{1+4z^2}}.$$
Addendum. In order to verify the recurrence put
$$F_{n,j} = (-1)^j {n\choose j}^2$$
and check that
$$F_{n,j}\frac{n}{n-1} - (F_{n-1,j}-F_{n-1,j-1}) \frac{2n-1}{n-1}
+ (F_{n-2, j} +2 F_{n-2,j-1} + F_{n-2,j-2}) = 0.$$
This equation is the output from Sister Celine. Now adding over $j$ this becomes
$$a_n\frac{n}{n-1} - (a_{n-1}-a_{n-1}) \frac{2n-1}{n-1}
+ (a_{n-2} +2 a_{n-2} + a_{n-2}) = 0$$
which is
$$a_n\frac{n}{n-1} + 4 a_{n-2} =0,$$
precisely the recurrence we are trying to verify.
Comment: I don't know how I could have overlooked the convolution hiding in plain sight here. Upvoting the convolution answer.
Answer: $\newcommand{\+}{^{\dagger}}%
 \newcommand{\angles}[1]{\left\langle #1 \right\rangle}%
 \newcommand{\braces}[1]{\left\lbrace #1 \right\rbrace}%
 \newcommand{\bracks}[1]{\left\lbrack #1 \right\rbrack}%
 \newcommand{\dd}{{\rm d}}%
 \newcommand{\isdiv}{\,\left.\right\vert\,}%
 \newcommand{\ds}[1]{\displaystyle{#1}}%
 \newcommand{\equalby}[1]{{#1 \atop {= \atop \vphantom{\huge A}}}}%
 \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}%
 \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}%
 \newcommand{\ic}{{\rm i}}%
 \newcommand{\imp}{\Longrightarrow}%
 \newcommand{\ket}[1]{\left\vert #1\right\rangle}%
 \newcommand{\pars}[1]{\left( #1 \right)}%
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\pp}{{\cal P}}%
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,#2\,}\,}%
 \newcommand{\sech}{\,{\rm sech}}%
 \newcommand{\sgn}{\,{\rm sgn}}%
 \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}%
 \newcommand{\verts}[1]{\left\vert #1 \right\vert}%
 \newcommand{\yy}{\Longleftrightarrow}$
$\ds{%
a_{n} \equiv \sum_{k = 0}^{n}{n \choose k}^{2}\pars{-1}^{k}: {\large ?}}$

\begin{align}
a_{n} &= \sum_{k = 0}^{n}{n \choose k}\pars{-1}^{k}
\sum_{\ell = 0}^{n}{n \choose \ell}\delta_{\ell, k}
=
\sum_{k = 0}^{n}{n \choose k}\pars{-1}^{k}
\sum_{\ell = 0}^{n}{n \choose \ell}\oint_{\verts{z} = 1}{\dd z \over 2\pi\ic}\,
{1 \over z^{\ell - k + 1}}
\\[3mm]&=
\oint_{\verts{z} = 1}{\dd z \over 2\pi\ic}\,{1 \over z}
\sum_{k = 0}^{n}{n \choose k}\pars{-z}^{k}
\sum_{\ell = 0}^{n}{n \choose \ell}\pars{1 \over z}^{\ell}
=
\oint_{\verts{z} = 1}{\dd z \over 2\pi\ic}\,{1 \over z}\,\pars{1 - z}^{n}
\pars{1 + {1 \over z}}^{n}
\\[3mm]&=
\oint_{\verts{z} = 1}{\dd z \over 2\pi\ic}\,{1 \over z^{n + 1}}\,\pars{1 - z^{2}}^{n}
=
\oint_{\verts{z} = 1}{\dd z \over 2\pi\ic}\,{1 \over z^{n + 1}}
\sum_{\ell = 0}^{n}{n \choose \ell}\pars{-z^{2}}^{\ell}
\\[3mm]&=
\sum_{\ell = 0}^{n}{n \choose \ell}\pars{-1}^{\ell}
\oint_{\verts{z} = 1}{\dd z \over 2\pi\ic}\,{1 \over z^{n - 2\ell + 1}}
=
\left\lbrace%
\begin{array}{ccl}
0 & \quad\mbox{if} & n\,\,\,\mbox{is}\,\,\,{\it odd}
\\[2mm]
\pars{-1}^{n/2}{n \choose {n \over 2}} & \quad\mbox{if}
& n\,\,\,\mbox{is}\,\,\,{\it even}
\end{array}\right.
\end{align}

$$\color{#0000ff}{\large%
\sum_{k = 0}^{n}{n \choose k}^{2}\pars{-1}^{k}
=
\left\lbrace%
\begin{array}{ccl}
0 & \quad\mbox{if} & n\,\,\,\mbox{is}\,\,\,{\it odd}
\\[2mm]
\pars{-1}^{n/2}{n \choose {n \over 2}} & \quad\mbox{if}
& n\,\,\,\mbox{is}\,\,\,{\it even}
\end{array}\right.}
$$
Comment: Very nice technique.
Comment: @MarkoRiedel It's always straightforward. Thanks.
Answer: Let define $$a_n=\sum_{k=0}^n(-1)^k\binom{n}{k}^2=\sum_{k=0}^n t_k.$$
Observing the ratio
$$
\frac{t_{k+1}}{t_k}=\frac{(-1)^{k+1}\binom{n}{k+1}^2}{(-1)^k\binom{n}{k}^2}=-\frac{(k-n)^2}{(k+1)^2}=\frac{(k-n)(k-n)}{(k+1)(k+1)}(-1)
$$
we see that $a_n$ can be expressed with the hypergeometric function $_2F_1$ as
$$
a_n=\;_2F_1\left(\matrix{-n,\;-n\\1}\Bigg|-1\right).
$$
Using the Kummer's identity  for $b-a+c=1$ and $b$ negative integer
$$ _2F_1\left(\matrix{a,\;b\\c}\Bigg|-1\right)=2\cos\left(\tfrac{\pi b}{2}\right) \frac{\Gamma(|b|)\Gamma(b-a+1)}{\Gamma\left(\frac{|b|}{2}\right)\Gamma\left(\frac{b}{2}-a+1\right)}
 $$
one has
$$
a_n
=2\cos\left(\tfrac{\pi n}{2}\right) \frac{\Gamma(n)}{\Gamma\left(\tfrac{n}{2}\right)\Gamma\left(\frac{n}{2}+1\right)}
$$
and observing that
$$
\frac{\Gamma(n)}{\Gamma\left(\tfrac{n}{2}\right)\Gamma\left(\frac{n}{2}+1\right)}
=\frac{(n-1)!}{(n/2-1)!(n/2)!}=\frac{n/2}{n}\frac{n!}{(n/2)!(n/2)!}
=\frac{1}{2}\binom{n}{n/2}
$$
we obtain finally

$$
a_n=\frac{(-1)^{n/2}\left[1+(-1)^n\right]}{2}\binom{n}{n/2}
$$
Comment: But, when `n` is odd, you answer is not 0 as expected.
Comment: when $n$ is odd $(-1)^n=-1$ so $1+(-1)^n=0$ and $a_n=0$. When $n$ is even $(-1)^n=1$ so $1+(-1)^n=2$ and $a_n=(-1)^{n/2}\binom{n}{n/2}$, or if you prefer,putting $n=2\nu$, $a_{2\nu}=(-1)^{\nu}\binom{2\nu}{\nu}$.


How to open a new file, but not the same file in vim

Question: For instance, how do I open a file I am going to use as the template for a file, but open it up as an unsaved buffer maybe? I don't know what methods I should use but I want to be able to save it right after as the file it's supposed to be.
My situation is for a jekyll blog where I have a basic post template and want to open that in vim from the command line so I can begin the post and then :w *filename.md*
Comment: What's wrong with just doing what you said? Or beforehand just copying the file?
Comment: I don't know how to open the file in vim so I can just easily save in another file. Without having to switch to editing a file like using `:e filename.md` after writing the new file.
Answer: One method is to use the :read command or :r for short. e.g. :r template.md to read in the contents of template.md into the current buffer.
Pros:

Can read in multiple templates
Any buffer can be used, including unsaved or even a scratch buffer
Do not have to worry about saving over the template.md file on accident
Can be combined with the :! method to read in the output of a shell command. e.g. :r!ls
Use a range with :r to read in a template at a specific point in the buffer. e.g. :10r template.md will read in template.md after line number 10.

Cons:

May have an extra blank line. This can be easily deleted via :0d_ or whatever your favorite method to delete a line.

Example workflow:

create buffer and read in template
:new
:r template.md|0d_

edit buffer
save buffer
:w a-great-new-file.md

For more help see:
:h :r
:h :r!
:h :range

Answer: Use the saveas command. Assuming you have a template for posts named template.md, open template.md, make some edits, then instead of using :w, do :sav newPost.md.
No need to switch buffers: now your buffer will contain the file newPost.md, and template.md will remain unchanged on the filesystem.
Comment: Perfect, I knew there had to be something simple for this kind of situation.
Answer: $ vim template.md
(edit)
:saveas filename.md

or
$ cp template.md filename.md && vim filename.md

or… I'm not sure I understand your problem.
The normal workflow is to open a template and "Save As…". In Vim and every other editor. What's wrong with that?
Or are you looking for a templating or snippet-expansion plugin?
Comment: A template system would work for more complicated things, but I am looking for a more simple solution to the problem. Maybe that is what I need though.


The latest version of python module in two linux distributions are different. why?

Question: At this moment, 4.7.0 was released 12 hours ago.
I see a list of multidict's versions differently in alpine and ubuntu. Why can't I see 4.7.0 in alpine??
$ docker run -i -t alpine:edge /bin/sh

# apk add py3-pip
# pip3 install multidict==

Collecting multidict==
  ERROR: Could not find a version that satisfies the requirement multidict== (from versions: 1.0.0a0, 1.0.1, 1.0.2, 1.0.3, 1.1.0b1, 1.1.0b2, 1.1.0b4, 1.1.0b5, 1.1.0b6, 1.1.0b7, 1.1.0b8, 1.1.0, 1.2.0, 1.2.1, 1.2.2, 2.0.0, 2.0.1, 2.1.0, 2.1.1, 2.1.2, 2.1.3, 2.1.4, 2.1.5, 2.1.6, 3.0.0, 3.1.0, 3.1.1, 3.1.3a0, 3.1.3, 3.1.4a1, 3.1.4a2, 3.1.4a3, 3.2.0a3, 3.2.0, 3.2.1a0, 3.3.0, 3.3.1, 3.3.2, 4.0.0, 4.1.0, 4.2.0, 4.3.0, 4.3.1, 4.4.0a0, 4.4.0a1, 4.4.0a2, 4.4.0a3, 4.4.0a4, 4.4.0a5, 4.4.0a6, 4.4.0a7, 4.4.0a8, 4.4.0a9, 4.4.0a10, 4.4.0a11, 4.4.0a12, 4.4.0a13, 4.4.0a14, 4.4.0a15, 4.4.0a16, 4.4.0a17, 4.4.0a18, 4.4.0a19, 4.4.0a20, 4.4.0a21, 4.4.0a22, 4.4.0a23, 4.4.0a24, 4.4.0a25, 4.4.0a26, 4.4.0a27, 4.4.0a28, 4.4.0a29, 4.4.0a30, 4.4.0a31, 4.4.0a32, 4.4.0a33, 4.4.0a34, 4.4.0a35, 4.4.0a36, 4.4.0a37, 4.4.0a38, 4.4.0a39, 4.4.0a40, 4.4.0a42, 4.4.0, 4.4.1, 4.4.2, 4.5.0, 4.5.1, 4.5.2, 4.6.0a2, 4.6.0a3, 4.6.0, 4.6.1)
ERROR: No matching distribution found for multidict==
$ docker run -i -t ubuntu /bin/bash

# apt install python3-pip
# pip3 install multidict==

Collecting multidict==
  Could not find a version that satisfies the requirement multidict== (from versions: 1.0.0a0, 1.0.1, 1.0.2, 1.0.3, 1.1.0b1, 1.1.0b2, 1.1.0b4, 1.1.0b5, 1.1.0b6, 1.1.0b7, 1.1.0b8, 1.1.0, 1.2.0, 1.2.1, 1.2.2, 2.0.0, 2.0.1, 2.1.0, 2.1.1, 2.1.2, 2.1.3, 2.1.4, 2.1.5, 2.1.6, 3.0.0, 3.1.0, 3.1.1, 3.1.3a0, 3.1.3, 3.1.4a0, 3.1.4a1, 3.1.4a2, 3.1.4a3, 3.2.0a3, 3.2.0, 3.2.1a0, 3.3.0, 3.3.1, 3.3.2, 4.0.0, 4.1.0, 4.2.0, 4.3.0, 4.3.1, 4.4.0a0, 4.4.0a1, 4.4.0a2, 4.4.0a3, 4.4.0a4, 4.4.0a5, 4.4.0a6, 4.4.0a7, 4.4.0a8, 4.4.0a9, 4.4.0a10, 4.4.0a11, 4.4.0a12, 4.4.0a13, 4.4.0a14, 4.4.0a15, 4.4.0a16, 4.4.0a17, 4.4.0a18, 4.4.0a19, 4.4.0a20, 4.4.0a21, 4.4.0a22, 4.4.0a23, 4.4.0a24, 4.4.0a25, 4.4.0a26, 4.4.0a27, 4.4.0a28, 4.4.0a29, 4.4.0a30, 4.4.0a31, 4.4.0a32, 4.4.0a33, 4.4.0a34, 4.4.0a35, 4.4.0a36, 4.4.0a37, 4.4.0a38, 4.4.0a39, 4.4.0a40, 4.4.0a42, 4.4.0, 4.4.1, 4.4.2, 4.5.0, 4.5.1, 4.5.2, 4.6.0a2, 4.6.0a3, 4.6.0, 4.6.1, 4.7.0)
No matching distribution found for multidict==

updated
for now, you can see like below. why version 4.7.0 is not found in alpine?
alpine
Collecting multidict==
  ERROR: Could not find a version that satisfies the requirement multidict== (from versions: 1.0.0a0, 1.0.1, 1.0.2, 1.0.3, 1.1.0b1, 1.1.0b2, 1.1.0b4, 1.1.0b5, 1.1.0b6, 1.1.0b7, 1.1.0b8, 1.1.0, 1.2.0, 1.2.1, 1.2.2, 2.0.0, 2.0.1, 2.1.0, 2.1.1, 2.1.2, 2.1.3, 2.1.4, 2.1.5, 2.1.6, 3.0.0, 3.1.0, 3.1.1, 3.1.3a0, 3.1.3, 3.1.4a1, 3.1.4a2, 3.1.4a3, 3.2.0a3, 3.2.0, 3.2.1a0, 3.3.0, 3.3.1, 3.3.2, 4.0.0, 4.1.0, 4.2.0, 4.3.0, 4.3.1, 4.4.0a0, 4.4.0a1, 4.4.0a2, 4.4.0a3, 4.4.0a4, 4.4.0a5, 4.4.0a6, 4.4.0a7, 4.4.0a8, 4.4.0a9, 4.4.0a10, 4.4.0a11, 4.4.0a12, 4.4.0a13, 4.4.0a14, 4.4.0a15, 4.4.0a16, 4.4.0a17, 4.4.0a18, 4.4.0a19, 4.4.0a20, 4.4.0a21, 4.4.0a22, 4.4.0a23, 4.4.0a24, 4.4.0a25, 4.4.0a26, 4.4.0a27, 4.4.0a28, 4.4.0a29, 4.4.0a30, 4.4.0a31, 4.4.0a32, 4.4.0a33, 4.4.0a34, 4.4.0a35, 4.4.0a36, 4.4.0a37, 4.4.0a38, 4.4.0a39, 4.4.0a40, 4.4.0a42, 4.4.0, 4.4.1, 4.4.2, 4.5.0, 4.5.1, 4.5.2, 4.6.0a2, 4.6.0a3, 4.6.0, 4.6.1, 4.7.1)
ERROR: No matching distribution found for multidict==
Ubuntu
Collecting multidict==
  Could not find a version that satisfies the requirement multidict== (from versions: 1.0.0a0, 1.0.1, 1.0.2, 1.0.3, 1.1.0b1, 1.1.0b2, 1.1.0b4, 1.1.0b5, 1.1.0b6, 1.1.0b7, 1.1.0b8, 1.1.0, 1.2.0, 1.2.1, 1.2.2, 2.0.0, 2.0.1, 2.1.0, 2.1.1, 2.1.2, 2.1.3, 2.1.4, 2.1.5, 2.1.6, 3.0.0, 3.1.0, 3.1.1, 3.1.3a0, 3.1.3, 3.1.4a0, 3.1.4a1, 3.1.4a2, 3.1.4a3, 3.2.0a3, 3.2.0, 3.2.1a0, 3.3.0, 3.3.1, 3.3.2, 4.0.0, 4.1.0, 4.2.0, 4.3.0, 4.3.1, 4.4.0a0, 4.4.0a1, 4.4.0a2, 4.4.0a3, 4.4.0a4, 4.4.0a5, 4.4.0a6, 4.4.0a7, 4.4.0a8, 4.4.0a9, 4.4.0a10, 4.4.0a11, 4.4.0a12, 4.4.0a13, 4.4.0a14, 4.4.0a15, 4.4.0a16, 4.4.0a17, 4.4.0a18, 4.4.0a19, 4.4.0a20, 4.4.0a21, 4.4.0a22, 4.4.0a23, 4.4.0a24, 4.4.0a25, 4.4.0a26, 4.4.0a27, 4.4.0a28, 4.4.0a29, 4.4.0a30, 4.4.0a31, 4.4.0a32, 4.4.0a33, 4.4.0a34, 4.4.0a35, 4.4.0a36, 4.4.0a37, 4.4.0a38, 4.4.0a39, 4.4.0a40, 4.4.0a42, 4.4.0, 4.4.1, 4.4.2, 4.5.0, 4.5.1, 4.5.2, 4.6.0a2, 4.6.0a3, 4.6.0, 4.6.1, 4.7.0, 4.7.1)
No matching distribution found for multidict==
Answer: It might be because for the version 4.7.0, there is no source distribution available on PyPI. See the list of distributions for multidict 4.7.0. Then compare this to the list of distributions for multidict 4.7.1, this one has a multidict-4.7.1.tar.gz.
Most likely none of the Python wheel built distribution available are suitable for Alpine Linux (something about the different libc maybe, I am not sure), so it falls back to the source distribution instead. But when there is no source distribution then this specific version just can't be built and installed at all.
See the "Platform Detection for Installers" section of PEP 513 -- A Platform Tag for Portable Linux Built Distributions:

We know of four main sources of potential incompatibility that are likely to arise in practice:

[...]
A linux distribution that does not use glibc (e.g. Alpine Linux, which is based on musl libc, or Android)


Solve the recurrence relation given by: $A_{n+2} + 4A_n = 0; A_0 = A_1 = 1$

Question: I am having trouble coming up with the general solution. It seems to be given by: x2 + 4, but if this is the case I don't see how the problem can be solved with real numbers. Thanks for any advice or guidance in advance.
Comment: Is this $A_{n+2} + 4 A_n = 0$? If so then $A_{n+4} = -4A_{n+2} = 16A_{n}$, and you get smth like $A_{4n} = A_{4n+1} = 16^n = 4^{2n}$, $A_{4n+2} = A_{4n+3} = -4^{2n+1}$ by induction on $n$ with step $4$. Am I missing something?
Comment: Or do you want to have a way to solve linear recurrence relations of any depth? It appears to me that [wiki](https://en.wikipedia.org/wiki/Recurrence_relation#Solving) has a good enough explanation of the general method, give it a try
Answer: Following your approach I think you got it backwards. Notice that the polynomial is $4x^2+x+1,$ you have to take care of the initial conditions so you get that if $A=\sum _{n=0}^{\infty}A_nx^n,$ then
$$A=1+x-4x^2A,$$
so $$A=\frac{1+x}{1+4x^2}=(1+x)\cdot\sum _{n=0}^{\infty}(-4)^nx^{2n}=\cdot\sum _{n=0}^{\infty}(-4)^nx^{2n}+\cdot\sum _{n=0}^{\infty}(-4^n)x^{2n+1}$$
so gives you that $A_{2n}=A_{2n+1}=(-4)^n.$
Comment: Thank you for this answer. I am confused where the extra x term comes from in your first equation. Is this simply to fill in the polynomial?
Comment: @RichardMcCormick You are welcome, It comes from the initial condition $A_1=1$ so the therm $A_1x=x.$
Answer: $$A_{n+2}=-4A_n$$
Let $A_n=t^n$, then $t=\pm 2 i \implies A_n =C(2i)^n+D (-2i)^n=2^n [ C  e^{in\pi/2}+D e^{-i n\pi/2}]$
$$A_0=0 \implies A_0=C+D=1 ~ \text{and}~A_1=C-D=-i/2 \implies C=(1/2-i/4), D=(1/2+i/4)$$
So $$A_n=2^n[(1/2-i/4)e^{in\pi/2}+(1/2+i/4)e^{i\pi n/2}]=2^{n} [\cos(n\pi/2)+\frac{1}{2}\sin(n\pi/2)]$$
Comment: OP has $A_{n+2}=-4A_n$, not $A_{n+2}=4A_n$.
Comment: Thanks, I have corrected it, you may see.
Answer: We can prove by induction $A_{2n}=A_{2n+1}=(-4)^n$, i.e. $A_n=(-4)^{\left\lfloor\tfrac{n}{2}\right\rfloor}$.


Como manter um registro no banco de dados, porem, oculto para o sistema?

Question: Tenho um aplicação em Delphi e preciso que nessa aplicação quando o usuário deletar um registro, esse registro continue no database, mas fique oculto no sistema.
Answer: Você poderá aplicar o que é conhecido como exclusão lógica:
No procedimento de exclusão da aplicação executar o comando UPDATE ao invés do DELETE, alterando o valor da coluna "excluido" para true.
Na listagem de registros, considerar somente os que possuem o valor da coluna 'excluído' com os valores NULL e false.
Comment: Conhecido também como Soft-delete.


What is the correct syntax for manually setting up one way binding in Ember.js?

Question: I read the documentation as well as the source but am still confused by both.
Any ideas?
Answer: Ember.Binding(to, from).oneWay().connect(obj) is how you'd directly create one however there is an alias Ember.oneWay(obj, to, from) which does the same thing .. an example usage:
App.aObject = Ember.Object.create({
    val: "blah blah"
});

App.bObject = Ember.Object.create({
    val: ""
});

Ember.oneWay(App, 'bObject.val', 'aObject.val');

Ember.get('App.bObject.val'); // => "blah blah"

You can capture that Ember.oneway() into a variable to use for manual disconnecting the binding later but usually I just use Ember's behind the scenes sorcery to create the binding binding creation by ending the value in 'Binding', so we end up with:
App.aObject = Ember.Object.create({
    val: "blah blah"
});

App.bObject = Ember.Object.create({
    valBinding: Ember.Binding.oneWay('App.aObject.val');
});

Ember.get('App.bObject.val'); // => "blah blah"

Comment: Awesome, answers my question exactly. For anyone else reading I think @chrixian meant to write Ember.oneWay( ... )
Comment: No I meant `Ember.Binding.oneWay` ... that way ember can set up the creation of the property using the given property name minus 'Binding'
Comment: word.. this is so weird. So in the case of declaring bindings after both objects have been instantiated, Ember.Binding.oneWay did not work while the alias you mentioned Ember.oneWay worked. Ember.oneway the lowercase version threw an error


How to get these organ sounds

Question: I'm a guitarist and keyboardist and try to do everything on my own when it comes to recording my music.
I'm a big fan of organs, however, there are some sounds I've never been able to achieve.
Two of them are in this song, one is right in the beginning, the other one can be heard at 3:43:

Do you have any suggestions on how to achieve that sound, preferably with a free vsti? I also own the Zebra 2 synthesizer which has some great organs, I just can't get these particular sounds.
Thanks alot!
Michael
Answer: The opening part of the song sounds to me like multiple tracks of monophonic guitar lines, each using some sustaining mechanism like an ebow or sustainiac.
The bit at 3:43 sounds like a (possibly Hammond) organ going through a rotary (possibly Leslie) speaker. A search for Hammond organ VSTs might yield something useful. Alternatively you might be able to find a rotary speaker VST effect that would work with one of your existing organ sounds.
Answer: You could always try this pedal if you want to get your guitar to sound like an organ.

It does sound like there is some volume swells also so maybe a good volume pedal could also help.

How to get these organ sounds


A little help in this binomial problem.

Question: In the binomial expansion of $(a-b)^n$, $n \geq 5$, the sum of $5^{th}$ and $6^{th}$ term is $0$, then $\frac{a}{b}$ is ?
I've solved this problem but its coming $n-4$ only, and the answer says it should be $\displaystyle{\frac{n-4}{5}}$. I'm not getting from where does this $5$ in denominator came from..??
Answer: Let $u=a/b$, then
$$(a-b)^n=b^n(1-u)^n=b^n\sum_{k=0}^{n}(-u)^k \binom{n}{k}$$
The sum of 5th term and 6th term is:
$$b^n \left((-u)^4 \binom{n}{4}+(-u)^5 \binom{n}{5}\right)=0 \implies b^n u^4\left(\binom{n}{4}-u \binom{n}{5}\right)=0$$
Assume that $u \not = 0$ and $b\not = 0$ then we have
$$\frac{a}{b}=u=\frac{\binom{n}{4}}{\binom{n}{5}}=\frac{n!}{4!(n-4)!}\frac{5!(n-5)!}{n!}=\frac{5}{n-4}$$
Comment: Ohh got that. My silly mistake. Thank you. :)

A little help in this binomial problem.


Entity FrameWork relacionamento muitos x muitos campo extra

Question: Bom dia,
Estou estudando o Entity FrameWork Code First e estou na dúvida de como devo criar um modelo de NxN com uma informação extra na tabela de relacionamento. Por exemplo:
Vamos supor o seguinte relacionamento (imagem tirada do site da MSDN)

Até ai tudo bem, crio o modelo Person e Course e estabeleço a relação entre eles com o ICollection e "dizendo" que um Course tem vários Person e vice-versa e o EF cria este relacionamento (CourseInstructo).
Agora vamos supor que precise de uma informação extra qualquer na tabela CourseInstructo, por exemplo Ativo ou DataInicio.
Da forma proposta o EF cria a tabela automaticamente não possibilitando que eu adicione campo extra no relacionamento, certo?
Como eu deveria proceder para este caso?
Deveria criar 3 modelos:

Person
Course
CourseInstructo

e estabelecer o relacionamento da Person e Course com CourseInstructo? Como seria o esboço desse código e depois a manipulação desses registros (INSERT, UPDATE, DELETE)?
Obrigado.
Answer: Neste caso, você precisa de um tipo para setar este valor extra, impossibilitando você de ter acesso direto da sua classe Person ou Course.
Você pode tratar este relacionamento como uma nova Entidade de Agregação, dado que esta informação irá ser pertinente a relação.
Entretanto, você deve realizar o tratamento manual desta entidade, bem como adiciona-la um novo DbSet<CourseInstructor> em seu contexto.
Em suas classes Course e Person você deve conter uma lista de CourseInstructor.
Por exemplo:
public class CourseInstructor
{
    public int Id { get; set; }

    public int CourseId { get; set; }

    public virtual Course Course { get; set; }

    public int PersonId { get; set; }

    public virtual Person Person { get; set; }

    public string Extra { get; set; }

    public int InstructorId { get; set; }

    public virtual Instructor Instructor { get; set; }
}

Um link que também pode te ajudar: Relacionamento Muitos Para Muitos Entity Framework 6
Comment: fiz todo esse processo. Criei as classes e as relações conforme indicado. Cada uma com o seu DBSet no Context e o seu repositório. Funciona ao adicionar Person e Course mas ao adicionar a relação deles da erro.   CourseInstructor.Person = Person(previamente cadastrado) e o mesmo para Course e depois mando salvar.
Comment: Olá @Renato, se isto te ajudou a encontrar a solução para o problema. Lembre-se de marcar o post como solução, para ajudar outros usuários com um problema semelhante no futuro :)
Comment: Consegui identificar o problema. Obrigado. Gostaria de referenciar um lonk que também contribuiu. http://pt.stackoverflow.com/questions/14829/relacionamento-muitos-para-muitos-entity-framework-6
Answer: Assim como o Felipe Oriani mencionou a crianção de uma nova classe "CourseInstructor", mas o Entity FrameWork Code First faz isso de forma automática vou dar um exemplo
        public class Person
        {
            public Person ()
            {
                this.Courses = new HashSet<Course>();
            }

            [Key]
     [DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
public int PersonId{ get; set; }
public strng lastName{ get; set; }
public strig firstName{ get; set; }

            public virtual ICollection<Course> Courses { get; set; }

        }

///
      public class Course
        {
            public Course ()
            {
                this.Persons = new HashSet<Person>();
            }

            [Key]
     [DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
public int CouserId{ get; set; }
public string Title{ get; set; }
//...

            public virtual ICollection<Person> Persons { get; set; }

        }

Desta forma cria uma nova tabela no banco, sem você precisar criar uma nova class.
facilita que todas vez que tiver qualquer alteração em abas das classe, não necessita também fazer a alteração em uma outra classe com as mesmas informações.
Answer: Tenta assim
    public class Course
{

     [key]
     public int CourseId {get;set;}

     etc ....

     [ForeignKey("CourseID")]
     public virtual ICollection<Person> Persons { get;  set; }

}

public class Person
{
    [key]
    public int PersonId {get;set;}

    etc...

    [ForeignKey("PersonID")]
    public virtual ICollection<Course> Courses { get;  set; }
}

public class CourseInstructo
{
   [key] // de preferencia com autoincremento
   public int CourseInstructoId {get;set;}

   [ForeignKey("PersonId")]
   public virtual Person Person { get; set; }

   [ForeignKey("CourseId")]
   public virtual Course Course { get; set; }

   [Key, Column(Order = 0)]
   public virtual int PersonId { get; set; }

   [Key, Column(Order = 1)]
   public virtual int CourseId { get; set; }

   //Campo extra

}


How to create a row name, row index, col index, col name from correlation matrix converted to df in R?

Question: I have a data set of around 4000 rows and 220 columns.
For research and analysis reasons I have created a correlation matrix and filtered out all the values that are greater then 0.4 for further research of the features.
Here is what I did:
df_high_corr <- which((res > 0.4 & res < 1), arr.ind = T)
res1 <- as.data.frame(df_high_corr))

I have converted it to data frame but I have only row labels to the left, I want to add/bind another column that will display me the column names corresponding to the col value.
For example:
__________|_row__|_col____|_col_name______
DM.RESY   | 18   |  6     | dummy_col_name
DM.MARIT  | 19   |  6     | dummy_col_name
PHX.dage  |198   |  6     | dummy_col_name
CRS.VSCLR |206   |  6     | dummy_col_name
QH.HENGY  | 61   | 12     | dummy_col_name2
QC.CVWSF  | 41   | 13     | dummy_col_name3

Please suggest me a way to do it - fast creative and easy, I want to learn the best practices to do it.
Comment: Yes and no, I have tried your solution but it didn't show me what I really needed. I have used another solution as.data.frame(as.table(data)) and it solved my issue.
Answer: Try this:
foo <- data.frame(col_name = colnames(res), col = 1:ncol(res))
merge(which((res > 0.4 & res < 1), arr.ind = T), foo)

There's no need to use tidyr, base merge does this perfectly.
Using mtcars I get this:
res <- cor(mtcars)
foo <- data.frame(col_name = colnames(res), col = 1:ncol(res))
bar <- merge(which((res > 0.4 & res < 1), arr.ind = T), foo)
head(bar)

  col row col_name
1   1   5      mpg
2   1   7      mpg
3   1   8      mpg
4   1   9      mpg
5   1  10      mpg
6   2   3      cyl


Calculate $\int_0^1\arctan x\left(\frac{3\ln(1+x^2)}{1+x}-\frac{2\ln(1+x)}{x}\right)\ dx$

Question: Prove that

$$\int_0^1\arctan x\left(\frac{3\ln(1+x^2)}{1+x}-\frac{2\ln(1+x)}{x}\right)\ dx=\frac{3\pi}{8}\ln^22-\frac{\pi^3}{32}$$

I managed to prove the above equality using integral manipulation (solution be posted soon) , but is it possible to do it in different ways and specifically by harmonic series?
The interesting thing about this problem is that we don't see any imaginary part which is usually involved in such integrals.
Note: the second integral $$\int_0^1 \frac{\arctan x\ln(1+x)}{x}\ dx=\frac{3\pi^3}{32}+\frac{3\pi}{16}\ln^22+\frac32G\ln2+3\text{Im}\operatorname{Li}_3(1-i)$$ was already evaluated here but I calculated the original problem without separating the two integrals.
Comment: @Zacky got you now. yes thats a nice equality i remember it very well. we can related these two equalities in different post.
Comment: @Zacky yes Zacky thats what i did. I even copied the first two lines from you. too lazy to write :)
Comment: I'm looking forward to your solution.
Comment: I will provide soon. as i mentioned i got lucky with this problem. some nice cancellation and symmetry was there.
Comment: I guess there are a bunch of similar integrals like this, that when substracted produces a nice result (the ugly terms are canceled). See here another one: https://math.stackexchange.com/q/3054741/515527
Comment: Anyway, your integral would look much better in the following form:
$$\int_0^1 \frac{\arctan x\ln(1+x^2)}{x(1+x)}dx=\frac{\pi^3}{96}-\frac{\pi}{8}\ln^2 2$$
Comment: @Zacky thank you but my solution leads to the form of the problem. but based for the form you suggested, what happened to the other integral that has $\ln(1+x)/x$?
Comment: @AliShather Well, just use this: https://math.stackexchange.com/questions/3006106/an-amm-like-integral-int-01-frac-arctan-xx-ln-frac1x231x2dx/3007623#3007623
$${\int_0^1 \frac{\arctan x \ln(1+x)}{x}dx}=\frac{3}{2}\int_0^1 \frac{\arctan x\ln(1+x^2)}{x}dx$$ The $2$ cancels out nicely, and $3$ is a common factor.
Comment: Such integral are not that hard to get heuristically with the help of lindep function of PARI GP.
Comment: @FDP I never used such software. all I use is Wolfram and just to verify my solutions and basic indefinite integrals.
Comment: I have found out the following example: \begin{align}\int_0^1\frac{\ln(1+x)}{1+x^2}\left(\frac{3\arctan x}{x}+2\ln x\right)dx=\frac{5}{128}\pi^3-\frac{7}{4}\text{G}\ln 2+\frac{3}{16}\pi \ln^2 2\end{align}I don't know how to prove this right now.
Comment: @FDP beautiful... I will work on it today. can you post it as a problem?
Comment: Not sure my question will be accepted.
Answer: @Kemono Chen elegantly proved here
$$\int_0^y\frac{\ln(1+yx)}{1+x^2}dx=\frac12 \tan^{-1}(y)\ln(1+y^2)$$
By integration by parts we have
$$\int_0^y\frac{y\tan^{-1}(x)}{1+yx}dx=\frac12 \tan^{-1}(y)\ln(1+y^2)$$
divide both sides by $1+y$ and integrate from $y=0$ to $y=1$, we get,
\begin{align}
\frac12I&=\frac12\int_0^1\frac{\arctan y\ln(1+y^2)}{1+y}\ dy=\int_0^1\int_0^y\frac{y\arctan x}{(1-yx)(1+y)}\ dy\ dx\\
&=\int_0^1\arctan x\left(\int_x^1\frac{y}{(1-yx)(1+y)}\ dy\right)\ dx\\
&=\int_0^1\arctan x\left(\frac{\ln(1+x)}{x}-\frac{\ln(1+x^2)}{x}+\frac{2\ln(1+x)-\ln(1+x^2)-\ln2}{1-x}\right)\ dx\\
&=\underbrace{\int_0^1\frac{\arctan x\ln(1+x)}{x}\ dx}_{J}-\underbrace{\int_0^1\frac{\arctan x\ln(1+x^2)}{x}\ dx}_{K}\\
&\quad+\underbrace{\int_0^1\frac{\arctan x}{1-x}\left(2\ln(1+x)-\ln(1+x^2)-\ln2\right)\ dx}_{\large{x=(1-y)/(1+y)}}\\
&=J-K-\int_0^1\frac{\left(\frac{\pi}{4}-\arctan x\right)}{x(1+x)}\ln(1+x^2)\ dx\\
&=J-K-\frac{\pi}{4}\int_0^1\frac{\ln(1+x^2)}{x(1+x)}\ dx+K-I\\
\frac32I&=J-\frac{\pi}{4}\left(\frac{3\pi^2}{48}-\frac34\ln^22\right)\\
3I-2J&=\frac{3\pi}{8}\ln^22-\frac{\pi^3}{32}
\end{align}


dget complains that public key not found

Question: I'm trying to backport a package, but dget (dscverify) says that it can't check the signature because of public key not being found:
[root ~/build/openssl] dget -x http://ftp.de.debian.org/debian/pool/main/o/openssl/openssl_0[72/753]
queeze14.dsc
dget: retrieving http://ftp.de.debian.org/debian/pool/main/o/openssl/openssl_0.9.8o-4squeeze14.dsc
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  2003  100  2003    0     0  27106      0 --:--:-- --:--:-- --:--:-- 47690
dget: retrieving http://ftp.de.debian.org/debian/pool/main/o/openssl/openssl_0.9.8o.orig.tar.gz
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 3684k  100 3684k    0     0  3507k      0  0:00:01  0:00:01 --:--:-- 3615k
dget: retrieving http://ftp.de.debian.org/debian/pool/main/o/openssl/openssl_0.9.8o-4squeeze14.debia
n.tar.gz
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 94425  100 94425    0     0   371k      0 --:--:-- --:--:-- --:--:--  422k
openssl_0.9.8o-4squeeze14.dsc:
dscverify: openssl_0.9.8o-4squeeze14.dsc failed signature check:
gpg: keyblock resource `/root/.gnupg/secring.gpg': file open error
gpg: Signature made Mon 11 Feb 2013 11:04:16 PM EET using RSA key ID 1A5522DD
gpg: Can't check signature: public key not found
Validation FAILED!!

I've tried updating debian-keyring package, specifying dsc files from different versions of debian. To no avail. How come it can't verify the signature? Can I ignore this messege? Or what an I to do?
Comment: Stop using lenny? That went out of support years ago.
Comment: It's not `lenny`, it's `squeeze`.
Comment: Do you have the `debian-keyring` package installed?
Comment: Yes, I stated the in the question. But I've confirmed that just now, `dpkg` says `2010.12.29` for version.
Comment: The same goes for `wheeze`.
Answer: Running the following command solves the problem.
$ gpg -k

As far as I can tell, the problem lies in gpg complaining about not being configured. In the end the following command is run:
cat openssl_0.9.8o-4squeeze14.dsc | gpg --batch --no-options --no-default-keyring \
    --always-trust --keyring /usr/share/keyrings/debian-keyring.gpg \
    --keyring /usr/share/keyrings/debian-maintainers.gpg

UPD And here's a bug report.
UPD Link to mailing list discussion.


.Net Library for converting Motion Jpeg files to Jpeg stills?

Question: I have a couple of Panasonic cameras that I use for shooting video, and they produce Motion JPEG (wrapped as .mov). I want to write a simple tool (in C#)  to convert the .mov files to a set of JPG stills.
Can't find much help becasue most folks want to read streams or to go the other way (from stills to video).
What should I use? I have picked up that there are at least couple of different libraries that might be useful. (DirectShow, OpenCV) but I'd appreciate any and all advice on how to approach this task...
Comment: anyone? Even anyone in the same boat with no answers?
Answer: In the end, I just analysed the files, worked out the headers and wrote the code. If anyone else is up to the same task, it's pretty easy, just watch for the keyframes, which seem to repeat what I'd deduced is the "start JPEG" code 3 times (at least for my camera).
Maybe useful....
<code>    byte[] _startToken = new byte[2] { 0xFF, 0xD8 }; //JPEG Start
    byte[] _endToken = new byte[2] { 0xFF, 0xD9 }; //JPEG End
</code>
Comment: I wonder why you said "keyframes" and not "frames"? Is there non-keyframe images in a Mjpeg? And yeah, good idea to spot these famous "ÿù" :).


Upgrade do laravel 5.7 para o 5.8

Question: Bom dia prezados,
Estou realizando a migração do meu projeto pessoal do laravel 5.7 pra o 5.8, porém há uma parte na documentação que eu não entendi muito bem, pode ser uma pergunta boba, mas não consigo encontrar nada a respeito.

All array_* and str_* global helpers have been deprecated. You should use the Illuminate\Support\Arr and Illuminate\Support\Str methods directly.

O que isso impacta no meu projeto?
Pelo que eu entendi os helpers do tipo array_* devem ser substituídos pelo Arr, então onde tenho por exemplo array_push devo substituir por Illuminate\Support\Arr::prepend neste caso?
Se alguém puder me tirar esta dúvida agradeço!
Comment: Não entendo algumas votações negativas em perguntas, esta me parece legítima e dentro do escopo.
Answer: Não tem sentido algum substituir as funções nativas do PHP pelas funções do Laravel, a mensagem se refere as funções globais do Laravel, não tem nada haver com array_push ou str_replace, que são nativas.
As funções do Laravel (não nativas do PHP) eram as que estavam documentadas até a versão 5.6: https://laravel.com/docs/5.6/helpers, simplesmente veja o que esta documentado no Laravel 5.8 para helpers e verá quais funções estão disponíveis: https://laravel.com/docs/5.8/helpers
Algumas das funções descontinuas:

array_add
array_collapse
array_divide
array_dot
array_except
array_first
array_flatten
array_forget
array_get
array_has
array_last
array_only
array_pluck
array_prepend
array_pull
array_random
array_set
array_sort
array_sort_recursive
array_where
array_wrap
str_after
str_before
str_contains
str_finish
str_is
str_limit
str_plural
str_random
str_replace_array
str_replace_first
str_replace_last
str_singular
str_slug
str_start

Veja que nenhuma tem haver com as nativas do PHP
Comment: Valeu, ultimamente não tenho programado muito em php, no meu trabalho utilizo VB e C#, e no emprego anterior utilizava typescript, então andava meio enferrujado, Obrigado pelo esclarecimento!!

Upgrade do laravel 5.7 para o 5.8


How to edit existing pdf file itext7, C#?

Question: Before, I edit a field into an existing PDF file as follows:
using var memoryStream = new MemoryStream();
var pdfReader = new PdfReader(new MemoryStream(templateFileByteArray));
var pdfStamper = new PdfStamper(pdfReader, memoryStream, '\0', false);
var pdfFormFields = pdfStamper.AcroFields;
pdfFormFields.GenerateAppearances = true;
pdfFormFields.SetField("TextFullName", customer.Name, customer.Name);
pdfStamper.FormFlattening = true;
pdfReader.Close();
pdfStamper.Close();

How can I do it with iText7.
in iText7 I couldn't find PdfStamper equivalent.
Comment: It's too bad that the iText devs haven't published a document helping specifically with migration from iTextSharp. I started with it about 8 years ago. I bought the book, and was able to do a bunch of stuff that I am thankful for, but now in migrating some of that work to iText7, I find there are no official migration notes. It seems like it would be a no-brainer to provide something like that in a day where so many organizations are refactoring to .Net core from older .net apps. I suppose I am late in asking at this point. Just started hitting migration needs this year.
Comment: Between iText 5.x and iText 7.x there was a complete re-design of the API. Before switching to iText 7, therefore, consider reading some introductions, e.g. the [iText 7: Jump-Start Tutorial for .NET](https://itextpdf.com/en/resources/books/itext-7-jump-start-tutorial-net) and [iText 7: Building Blocks](https://itextpdf.com/en/resources/books/itext-7-building-blocks).
Answer: The rough alternative is the following code:
PdfReader reader = new PdfReader(sourceFile);
PdfWriter writer = new PdfWriter(outFile);
PdfDocument pdfDocument = new PdfDocument(reader, writer);
PdfAcroForm form = PdfAcroForm.getAcroForm(pdfDocument, false);
form.getField("TextFullName").setValue("Name Value");
form.flattenFields();
pdfDocument.close();


How to redirect from servlet to jsp after getting alert?

Question: in my code i want to display alert message, that is coded in the servlet page.
    and then i want to redirect to jsp. i got alert message. but it doesn't redirect. Please check my code?
catch (Exception e) {
            e.printStackTrace();
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            String someMessage = "Vehicle already Assigned";
            out.println("");
            out.println("");
            out.println("");
    }

Where i put this line
getServletContext().getRequestDispatcher("VehicleSchedule.jsp").forward(request, response);

Comment: Can't do two things (forwarding a request and returning a response) at once.
Comment: Ohhhh i see... is there any other option to redirect with alert message?
 if u know pls share with me dear **Kohei TAMURA**
Comment: If you want to forward a request to JSP with the error message, you should write `request.setAttribute("errorMessage", someMessage);` in your servlet and `<%=request.getAttribute("errorMessage")%>` in VehicleSchedule.jsp
Comment: yes sure. Thanks
Answer: You can use something like this but i am not really recomend!
out.println("");

This is a tricky and easy way to do this! But you can do this with session also if you want.
Comment: ohhhhh Thanks dear **Fotis Grigorakis**
Comment: If my answer helped you, you can accept it and up vote it! ;)
Answer: You can simply use javascript code along with your alert message, However it will redirect your request and will not dispatch it with any data.
 out.println("");
 **out.println("window.location.href = 'myPage.jsp';");**

So if you want to pass any data along with request object, you will need to append it in URL or add it in Session object.
out.println("window.location.href = 'myPage.jsp?var1=value1';");

 or

session.setAttribute("var1","val1");


How to calculate a posterior for the given model?

Question: Suppose we have a joint distribution on vector $[\mathbf{x}, y]$:
$$
p([y, \mathbf{x}] ) = \mathcal{N}\left(\begin{pmatrix} y \\ \mathbf{x}\end{pmatrix}| 0, \begin{pmatrix} k& \mathbf{v} \\ \mathbf{v}^T & K\end{pmatrix}\right),
$$
where $\mathbf{x} \in \mathbb{R}^N$, $y \in \mathbb{R}$.
And also we know distribution of $\mathbf{x}$ conditioned on some data $D$:
$$
q(\mathbf{x}| D) = \mathcal{N} (\mu, \sigma^2 I).
$$
How does analytical expression for $p(y| D)$ look like (i.e. how to handle such an integral in the simplest way)?:
$$
p(y| D) = \int p(y| \mathbf{x}) q(\mathbf{x}| D) d \mathbf{x} = ?
$$
So, I try to solve this, but all I obtain looks like a monster, which isn't appropriate for me, so I have to use this expression further through my research.
Comment: The difficulty with Bayesian methods when the prior is not nice (like a conjugate prior) is that the normalization constant is an integral that can be difficult to evaluate.  This is one of the reason MCMC methods are so popular.
Comment: The posterior $p(y| D)$ is seems to be normal, so all I need is mean and variance.
Comment: Would solving up to proportionality be permitted, or is this one of the cases where you need to explicitly calculate the normalization constant?
Answer: It is much easier to do these evidence combination operations in the natural parametrization, which for the multivariate normal distribution with mean $\mu$ and covariance matrix $\Sigma$ is
$$\begin{bmatrix}\Sigma^{-1}\mu \\ \Sigma^{-1}\end{bmatrix}.$$
Convert $p$ and $q$ so that they're in this parametrization, then pad $q$ with zeroes for the extra component (since the precision there is zero) and just add the natural parameters.
Therefore, the resulting distribution is:
\begin{align}
y \mid D \sim \mathcal N\left([\Psi\Phi\mu]_1, \Psi_{11}\right)
\end{align}
where
\begin{align}
\Theta &= \begin{bmatrix} k& \mathbf{v} \\ \mathbf{v}^T & K\end{bmatrix}^{-1} \\
\Phi &= \begin{bmatrix} 0& \mathbf{0} \\ \mathbf{0}^T & \sigma^{-2}I\end{bmatrix} \\
\Psi &=(\Theta + \Phi)^{-1}.
\end{align}


Not Enough Arguments For an IF Statement...But There Are

Question: When I run this equation in Excel it tells me that there is only 1 argument for the IF statement. I am not sure why it is saying that when I have 3 arguments. Within the OR statement I have 2 different AND statements. It works just fine if I get rid of the second AND statement. Did I mess up a parentheses somewhere? I am not sure what is wrong. Any help would be greatly appreciated. Thanks!
<code>=IF(OR(ARRAYFORMULA(SUM(COUNTIF(B19:O19,{"I","Ip","Ia","It","Ih","A","Aa","Ap","At","Ah","X","R","Rt","Rx","Rp","Rh","K","Kt","E","Et","AL","HL","TV*","FFSL","ADM*"})))=10, AND(ARRAYFORMULA(SUM(COUNTIF(B19:O19,{"R-10","Rx-10*","Rp-10","Rt-10*","Rh-10","I-10","Ia-10","Ip-10","It-10","Ih-10","X-10*","A-10*","At-10"})))=4, ARRAYFORMULA(SUM(COUNTIF(B19:O19,{"I","Ip","Ia","It","Ih","A","Aa","Ap","At","Ah","X","R","Rt","Rx","Rp","Rh","K","Kt","E","Et","AL","HL","TV*","FFSL","ADM*"})))=5),AND(ARRAYFORMULA(SUM(COUNTIF(B19:O19,{"HL-9","X-9","N-9","E-9","J-9","Jh-9","Nh-9","Eh-9"})))=8,ARRAYFORMULA(SUM(COUNTIF(B19:O19,{"I","Ip","Ia","It","Ih","A","Aa","Ap","At","Ah","X","R","Rt","Rx","Rp","Rh","K","Kt","E","Et","AL","HL","TV*","FFSL","ADM*"})))=1) ,"80 Hours","Error"))
</code>
Comment: yes, you messed up a parenthesis somewhere (there are two closing parentheses at the end, so `"80 Hours"` and `"Error"` are *inside* the `OR` statement - I'm guessing you wanted them outside).
Comment: Ah, yes, I am pretty sure I want them in the IF statement. I'll see if I can find it... Thanks.
Comment: Yep. That was it. Thanks! Just moved that last ")" before the "80 Hours".
Answer: This question makes me think "If only there was an online Excel Formula Beautifier".
Oh look, there is.
If you copy-and-paste it into the beautifier you get the code below.
You can now see that your parameters "80 Hours", "Error" are parameters of the first ARRAYFORMULA function, not the IF function.
<code>=IF(
    OR(
        ARRAYFORMULA(
            SUM(
                COUNTIF(
                    B19:O19,
{ "I",
                            "Ip",
                            "Ia",
                            "It",
                            "Ih",
                            "A",
                            "Aa",
                            "Ap",
                            "At",
                            "Ah",
                            "X",
                            "R",
                            "Rt",
                            "Rx",
                            "Rp",
                            "Rh",
                            "K",
                            "Kt",
                            "E",
                            "Et",
                            "AL",
                            "HL",
                            "TV*",
                            "FFSL",
                            "ADM*"
                        ARRAYROWSTOP)
                    ARRAYSTOP)
                )
            )
        ) = 10,
        AND(
            ARRAYFORMULA(
                SUM(
                    COUNTIF(
                        B19:O19,
{ "R-10",
                                "Rx-10*",
                                "Rp-10",
                                "Rt-10*",
                                "Rh-10",
                                "I-10",
                                "Ia-10",
                                "Ip-10",
                                "It-10",
                                "Ih-10",
                                "X-10*",
                                "A-10*",
                                "At-10"
                            ARRAYROWSTOP)
                        ARRAYSTOP)
                    )
                )
            ) = 4,
            ARRAYFORMULA(
                SUM(
                    COUNTIF(
                        B19:O19,
{ "I",
                                "Ip",
                                "Ia",
                                "It",
                                "Ih",
                                "A",
                                "Aa",
                                "Ap",
                                "At",
                                "Ah",
                                "X",
                                "R",
                                "Rt",
                                "Rx",
                                "Rp",
                                "Rh",
                                "K",
                                "Kt",
                                "E",
                                "Et",
                                "AL",
                                "HL",
                                "TV*",
                                "FFSL",
                                "ADM*"
                            ARRAYROWSTOP)
                        ARRAYSTOP)
                    )
                )
            ) = 5
        ),
        AND(
            ARRAYFORMULA(
                SUM(
                    COUNTIF(
                        B19:O19,
{ "HL-9",
                                "X-9",
                                "N-9",
                                "E-9",
                                "J-9",
                                "Jh-9",
                                "Nh-9",
                                "Eh-9"
                            ARRAYROWSTOP)
                        ARRAYSTOP)
                    )
                )
            ) = 8,
            ARRAYFORMULA(
                SUM(
                    COUNTIF(
                        B19:O19,
{ "I",
                                "Ip",
                                "Ia",
                                "It",
                                "Ih",
                                "A",
                                "Aa",
                                "Ap",
                                "At",
                                "Ah",
                                "X",
                                "R",
                                "Rt",
                                "Rx",
                                "Rp",
                                "Rh",
                                "K",
                                "Kt",
                                "E",
                                "Et",
                                "AL",
                                "HL",
                                "TV*",
                                "FFSL",
                                "ADM*"
                            ARRAYROWSTOP)
                        ARRAYSTOP)
                    )
                )
            ) = 1
        ),
        "80 Hours",
        "Error"
    )
)
</code>
Comment: Or to make it even more beautiful, replace it with not-Excel.
Comment: That's good to know. Sorry for the bad original posting. Thanks for your help!


procedural php/mysql to object oriented issue

Question: This is the original code I am trying to write in object oriented form..
$posResult = mysql_query("SELECT MAX(position)+1 FROM todo");

        if(mysql_num_rows($posResult))
            list($position) = mysql_fetch_array($posResult);

This is where I am at.... I think I need to bind_result? also, I have an issue with the mysql_fetch_array...
if($stmt = $this->HH->Database->prepare("SELECT MAX(position)+1 FROM todo")) {
        $stmt->execute();
        $stmt->store_result();

        if($stmt->num_rows != FALSE) {
            list($position) = mysql_fetch_array($posResult);
        }
    }

Can someone advise on how to correct this?
Comment: Is `$this->HH->Database` Mysqli or PDO?
Comment: new mysqli($server, $user, $pass, $db);
Answer: It looks like you are moving over to PDO, which is great, it is a much better way to connect, but you are still trying to use some of the older mysql_* commands which won't work. While there are a number of ways to get the data, but this is the approach that I most commonly use:
if($stmt = $this->HH->Database->prepare("SELECT MAX(position)+1 FROM todo")) {
    $stmt->execute();

    $stmt->setFetchMode(PDO::FETCH_INTO, new yourClassName);
    foreach($stmt as $yourClassObject)
    {
        $someVar=$yourClassObject->QueryColumnName;
        // or
        $this->someProperty=$yourClassObject->QueryColumnName;
    }
    }

I do generally have a class that matches the results of the query, so I use FETCH_INTO but you can use a different method such as return an indexed array, associated array or others.
Comment: I actually was not intending to move over to PDO... nor do I really know much about it at all. I realize the older mysql_ command does not work. Any other alternatives to the PDO approach?
Comment: @Greg Actually I think that using PDO is easier than using the old functions. It might be different, but the flexibility is amazing - and if you just want to run simple queries directly it lets you do that as well.


How to simplify addition of quotients with variables

Question: Recently I was given a problem where I had a quotient with variables and a regular quotient and had to simplify it, but had no clue how to do it. For example,
$$  \left|\frac{x-1}{x+3}-\frac{1}{5}\right|=\frac{4}{5}\left|\frac{x-2}{x+3}\right|$$
Can you please explain how this works?
I am having trouble understanding this, any help will be appreciated.
Original Image
Comment: Get a common denominator, which is $5(x+3)$. Multiply the top and bottom of $\frac{x-1}{x+3}$ by $5$, and multiply the top and bottom of $\frac{1}{5}$ by $x+3$.
Answer: As Nick indicates in the comment, you do this with variables the exact same way you do it without variables. Remember that variables are just place-holders for numbers (or whatever else they are varying over). They behave just like those numbers.
There is one rule for mixing multiplication/division with addition/subtraction. That is the distributive law:
$$A(B + C) = AB + AC$$
To apply this to adding fractions, you need to rewrite them into a form where it applies. If you have $$\frac ab + \frac cd$$
you don't have a common multiplier. But, you can rewrite the fractions in a form where they do. Note that $\frac AA = 1$ and multiplying by $1$ does not change values. So you can multiply the first term by $\frac dd$ and the second term by $\frac bb$:
$$\begin{align}\frac ab + \frac cd &= \frac dd\frac ab + \frac bb\frac cd \\&= \frac{ad}{bd} + \frac{bc}{bd} \\&= \frac 1{bd}ad +\frac 1{bd}bc \\&= \frac{1}{bd}(ad + bc) \\&= \frac{ad+bc}{bd}\end{align}$$
In your example, $a = x-1, b = x+3, c = -1, d = 5$
$$\begin{align}\frac{x-1}{x+3}-\frac{1}{5} &= \frac 55 \frac{x-1}{x+3} + \frac{x+3}{x+3}\frac{-1}5\\
&=\frac{5x-5}{5x+15} + \frac{-x-3}{5x+15}\\
&=\frac 1{5x+15}\left((5x-5) + (-x - 3)\right)\\
&=\frac {4x-8}{5x+15}\end{align}$$
That combines the fractions, but then your calculation goes a step further, factoring the combined fraction:
$$\frac {4x-8}{5x+15} = \frac{4(x-2)}{5(x+3)} = \frac 45\frac{x-2}{x+3}$$
And finally also handles the absolute values:
$$\left|\frac{x-1}{x+3}-\frac15\right|=\left|\frac45\frac{x-2}{x+3}\right| = \frac45\left|\frac{x-2}{x+3}\right|$$
Of course, one normally does not write out the steps as I've done here - particularly in pulling out the denominators as a multiplication by the inverse. I choose to show it this way to tie it directly to the distributive law, so that you can see how this is justified.


Visual Studio 2022 docker debugging - "no symbols have been loaded"

Question: I'm trying to debug two C# .NET 6.0 Docker containers from Visual Studio 2022, but the breakpoints I set always show "no symbols have been loaded".
The two Docker containers are in a docker-compose.yml file, at version 3.9 and Docker Desktop shows them running okay.
In VS2022, I've tried Debug > Attach to Process with:

Connection Type of "Docker (Linux Container)"
Debug these Code types set to "Managed (.NET Core for Unix)".

I can list the contents of the containers and see the .pdb files.
I've tried deleting the containers and images in Docker Desktop, cleaning the VS solution and re-building and re-starting the containers, but get the same error.
Comment: Are you sure you're building the containers with the debug version of the code? Also, try clearing out **all** of your breakpoints from the solution, and running a Clean Solution and then retry. This sometimes helps.
Comment: Good points @akseli, but yes we're building debug version of code.   Just tried clearing out breakpoints, cleaning solution, rebuilding and resetting the breakpoints and still get error.    Are you able to debug containers in VS2022?
Comment: I haven't had to in past few months, but before that I remember everything working as expected...
Answer: You are probably experiencing an issue with the Just My Code feature.
The two easiest ways to get your symbols to load in this case are:
Uncheck "Enable Just My Code" in the debugger options:

Or, open the Modules window, select your dll, right click and select "Load Symbols":
Comment: This solution did work for us Nathan, but debugging using the docker-compose startup profile was more straightforward, and we don't need to Attach to Process any more, so we're using that approach now.
Answer: If you're trying to debug a referenced project make sure that DebugType option is set to portable to create cross-platform PDB file in the referenced project file. Learn more about DebugType in C# Compiler Options that control code generation.
<PropertyGroup>
  <DebugType>Portable</DebugType>
</PropertyGroup>

Answer: We fixed this ourselves by ensure the debug config was shown as in the steps and screenshot below.
Simple scenario

ensure Debug solution configuration is selected
ensure the Startup Project is the docker-compose file
ensure Docker Compose is shown and then click it to start debugging

With this config, all our breakpoints worked as expected and we don't need to Attach to Process any more.
We can still see our various containers and their logs in both Docker Desktop and in the VS Containers window.
Launch Profiles scenario
Additionally, we have it working on another solution that has Docker Compose Launch Profiles.

Ensure the docker-compose file has profiles specified for the various services
in the toolbar > Docker Compose > Manage Docker Compose Launch Settings, select the Docker Compose profile

Under each service, ensure the one you want to debug is Start debugging
Save
Start debugging as in the simple scenario above


find a and b such that piecewise this piecewise function is twice differentiable

Question: I am stuck with this homework problem..
Given the following piecewise function:
\begin{cases}
        y = \int_0^{2x} \sqrt{1+t^4} dt, & x\gt 0 \\
        y = ax+bx^2 &   x \le 0 \
\end{cases}
Find $a$ and $b$ such that it is twice differentiable.
All help is greatly appreciated...
My idea of an approach here is to make a set of equations by checking for continuity at zero, which gives an equation, then calculating the derivative at zero, which gives another equation, then solve this set of equations. However, I don't know what to do with that integral..
I'd love to show some work, and I have been idling on how to start before posting this..If you feel like not doing the work (as expected), please give me a direction:))
Answer: First, we check that the function is continuous.
Yes, $\displaystyle \lim_{x \to 0^+}\int_0^{2x}\sqrt{1+t^4}\,dt=\lim_{x\to0^-}ax+bx^2=0$.
Now, we take the derivative of each side, and reevaluate the limit.
We need that $\displaystyle \lim_{x \to 0^+}2\sqrt{1+(2x)^4}=\lim_{x \to 0^-}a+2bx=2$.
That's our first equation: $a=2$.
Then, we take the second derivative, and reevaluate.
We have that $\displaystyle \lim_{x \to 0^+}\frac{48x^3}{\sqrt{1+16x^4}}=\lim_{x \to 0^-}2b=0$.
So for $a=2$ and $b=0$, the function is twice differentiable.
Comment: Thank you! Why is it okay to just plug in x for t?
Comment: wait no, i did it wrong HAHA...
Comment: the answer doesn't change, but you are correct in pointing out my mistake. i have corrected it


Error in a binomial coefficient sum identity proof

Question: I have been given an identity $\begin{align}
\sum_{i=0}^n i\binom{n}{i}^2 = n\binom{2n-1}{n-1}
\end{align}$.
However when I tried to prove it, I got a different result.
$\begin{align}
\sum_{i=0}^n i\binom{n}{i}^2 = n\sum_{i=0}^n \binom{n-1}{i-1} \binom{n}{i} =
n\sum_{i=0}^n \binom{n-1}{n-i} \binom{n}{i} = n\binom{2n-1}{n}
\end{align}$
First equation follows from absorption identity, second one from symmetry, and the third one from Vandermonde's identity. Where is my mistake?
Comment: I think you'd find that $\binom{n}{k}=\binom{n}{n-k}$ that should help to some extent.
Answer: Let us devise a purely combinatorial approach: assume to have a parliament with $n$ people in the right wing, $n$ people in the left wing. In how many ways can we form a committee with $n$ people and elect a chief of the committee from the left wing? The first approach is to select $i$ people from the left wing, $n-i$ people from the right wing, then the chief among the selected $i$ people from the left wing. This leads to $\sum_{i=0}^{n}i\binom{n}{i}\binom{n}{n-i}=\sum_{i=0}^{n}i\binom{n}{i}^2$. The other approach is to select the chief from the left wing first ($n$ ways for doing that), then select $n-1$ people from the remaining $2n-1$ in the parliament. Conclusion:
$$ \sum_{i=0}^{n}i\binom{n}{i}^2 = n\binom{2n-1}{n-1} = n\binom{2n-1}{n}. $$
Comment: +1 for making me realize (along with @Roddy MacPhee) that $2n-1-(n-1)=n$ :P
Answer: $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
\begin{align}
\sum_{i = 0}^{n}i{n \choose i}^{2} & =
\sum_{i = 0}^{n}i{n \choose i}{n \choose n - i} =
\sum_{i = 0}^{n}i{n \choose i}\bracks{z^{n - i}}\pars{1 + z}^{n} =
\bracks{z^{n}}\pars{1 + z}^{n}\sum_{i = 0}^{n}{n \choose i}i\,z^{i}
\\[5mm] & =
\bracks{z^{n}}\pars{1 + z}^{n}
\bracks{z\,\partiald{}{z}\sum_{i = 0}^{n}{n \choose i}z^{i}} =
\bracks{z^{n}}\pars{1 + z}^{n}\bracks{z\,\partiald{\pars{1 + z}^{n}}{z}}
\\[5mm] & =
\bracks{z^{n - 1}}\pars{1 + z}^{n}\bracks{n\pars{1 + z}^{n - 1}} =
n\bracks{z^{n - 1}}\pars{1 + z}^{2n - 1} =
\bbx{n{2n - 1 \choose n - 1}}
\end{align}
Answer: If one takes $n=2$ then
$$\sum_{i=0}^n i\binom{n}i^2=0+\binom21^2+2\binom22^2=4+2=6$$
and
$$\binom{2n-1}{n-1}=\binom{3}1=3.$$
It seems in this case that
$\sum_{i=0}^n i\binom{n}i^2$ equals $n\binom{2n-1}n$ rather than
$\binom{2n-1}{n-1}$.
Answer: The question as stated is incorrect; here's a combinatorial proof for your version (the $n\binom{2n-1}{n}$ version):
Suppose we have $n$ turtles and $n$ rabbits at a sports meet. How many ways can we choose two teams of $n$ animals each, one of which has a captain (who must be a turtle)?
The LHS counts this directly by counting the number of ways to choose $i$ turtles to include and $i$ rabbits to exclude from the team with a captain, and picking a captain from among these turtles. The other team is composed of the remaining animals.
The RHS first picks the captain, then chooses $n$ of the other animals to form the other team. The remaining animals join the captain's team.
Comment: the two results are the same


How to find an equation for the surface that the distance from its point to x-axis is three times the distance from its point to yz-plane

Question: As title says, how does one find an equation for the surface consisting of all points $P$ for which the distance from $P$ to the x-axis is three times the distance from $P$ to the $yz$-plane?
Comment: What have you tried? For instance, suppose the $y$ and $z$ coordinates are given; what are the possible values for the $x$ coordinate.
Answer: Hint: Note that the distance from $(x,y,z)$ to the $yz$-plane is $|x|$, and the distance from $(x,y,z)$ to the $x$-axis is $\sqrt{y^2+z^2}$.
Answer: HINT
what is its locus if ratio $ x/y $ is constant and you rotate it on x-axis?


Gauss Theorem used in the proof of Liouville's Theorem

Question: I am using the 2nd Edition of PDEs by L.C.Evans.
on Page 29 the following theorem is stated:

Theorem 7 (Estimates on derivatives).
Assume $u$ is harmonic in $U$. Then
$$|\nabla u(x_0)|\leq \frac{C}{r^{n}}\|u\|_{L^1(B(x_0,r))}$$
for each ball in $B(x_0,r) \subset U$

note: this is a special case of the original version, which is a more general kth order of gradient.
And the Proof:

Proof

$u_{x_i}(x_0)$ is harmonic if $u$ is harmonic
apply the mean value formula for $u_{x_i}(x_0)$
$$\begin{split}
|u_{x_i}(x_0)| & = |\frac{2^n}{\alpha(n)r^n}\int_{B(x_0,r/2)}u_{x_i}dx| \\
 & = |\frac{2^n}{\alpha(n)r^n}\int_{\partial B(x_0,r/2)}u\nu_idS|
\end{split}$$
...

I stop because my question is here.
I know here Gauss Theorem is applied but I think Gauss Theorem is for divergence and not partial derivative on a single dimension.
Comment: Apply the divergence theorem to a vector field with only one non-zero component.
Comment: Thank you so much. I have sketched it into an answer :).
Answer: Inspired by RRL, I mananaged to understand the steps
let $v$ be a n-dimensional constant vector field with the $i$-th element being $1$ and others $0$. Then
$$u_{x_i} = \nabla u\cdot v$$
And for the vector field $uv$ we have the following (note that $u$ is $\mathbb{R}^n \to \mathbb{R})$)
$$\nabla \cdot (uv) = \nabla u \cdot v + u\textbf{div}(v) = \nabla u\cdot v$$
so
$$u_{x_i} = \nabla \cdot (uv)$$
$\nabla \cdot (uv)$ fits the divergence theorem and and we can use it to achieve the 2nd "$=$"


Converts the temperature expressed in Celsius to Fahrenheit by VHDL

Question: I am wondering how to use the data types in VHDL to calculate the formula of Celsius to Fahrenheit(by b=a*1.8+32. VHDL doesn't support numbers with decimal points in the synthesis. It needs to output a real type (Fahrenheit) by the integer input(Celsius).
I tried to use the real type, but it couldn't be used in the synthesis except for the simulation part.
This is the part of the codes I wrote:
In synthesis:
entity temperature is
    Port ( a : in INTEGER RANGE 82 TO 92;
           b : out INTEGER RANGE 100 TO 300);
end tem;

Architecture Behavioral of temperature is

begin
b<=a*18+320;
end Behavioral;

In simulation:
signal a: INTEGER;
  signal b: INTEGER;
  signal c: REAL;
  signal d: REAL;
begin

  temperature port map ( a => a,
                      b => b );

  stimulus: process
            variable k: integer:= 0;
  begin

a<=82;
c<=82.0;
d<=179.6;
wait for 5 ns;
for k in 0 to 4 loop

          wait for 5 ns;
          a<= a + 1;
          c<=c+1.0;
          d<=(c+1.0)*1.8+32.0;
        end loop;

        wait;

    wait;
  end process;

Comment: Does the answer to [this question](https://stackoverflow.com/questions/58583309/how-can-i-use-floating-point-numbers-in-vhdl) provide any help?
Comment: Apologies if I broke the code too badly trying to fix the question formatting; between the inconsistent indentation and my unfamiliarity with the language I hope I got it right.
Comment: Thank you very much for your answers. You really enlightened me on this issue. Thanks for your time on it.
Answer: That's not how you deal with numbers in hardware.

The implementation of the " * " is dependent on the end product, you might end up using a DSP or implement the multiplication in logic.
You need to think how wide are your numbers and select a bit length accordingly.
As a general rule, multiplication of a m-bit number with a n-bit number will give a (m+n)bit number. The summation will give max(m,n)+1 bits.
If you want to use floating point you need to create the logic for handling such operations, as there are many and the synthesizer won't generate one for you.
In this case Fixed Points numbers are fine, as long as you are able to interpret the result. I point here to an introduction if you are not familiar with them. It also seems that you actually need only integers, I will stick with them for this example, you can add the fractional bits if you understand the reasoning.

The first number has a maximum value of 93, so rounding to the next power of two (128), we need 7 bits.
The first constant is 18, so we need 5 bits.
The result of the multplication will be then 12 bits wide.
The second constant is 320, and we need 9 bits.
Based on these calculations the output needs 13 bits to not overflow.

entity temperature is
    Port ( a     : unsigned(6 downto 0);
           b     : unsigned(12 downto 0) );
end temperature;

Architecture Behavioral of temperature is

constant C1     : unsigned(4 downto 0) := to_unsigned(12,5);
constant C2     : unsigned(8 downto 0) := to_unsigned(320,9);

begin
   b<=a*C1+C2;
end Behavioral;


Product of matrices coming from bases of free abelian groups

Question: I am reading a line in Stewart and Tall's Algebraic Number Theory text that I am unsure about. Suppose $G$ is a free abelian group of rank $n$ and $\{x_1,\dots,x_n\}$ and $\{y_1,\dots,y_n\}$ are both bases. Then there exist integers $a_{ij},b_{ij}$ such that $y_i=\sum_j a_{ij}x_j$ and $x_i=\sum_j a_{ij}y_j$. Consider the matrices $A=(a_{ij})$ and $B=(b_{ij})$. The book claims that $AB=I_n$, the identity matrix. Why is this true?
Comment: Which textbook are you referring to?
Comment: Stewart Algebraic Number Theory
Answer: This is just the composition of inverse change of basis matrices, and so is the identity.


Views Display Mode Toggle

Question: I'm looking for a way to add the ability for users to toggle one of two view modes. Essentially, looking for a 'list/grid' switch. I've tried using https://www.drupal.org/project/views_modes but it's failing to switch the URL at all.
If anyone has knowledge of a patch/fork of this project, or a way to achieve this, I'd be grateful!
Comment: Have you looked at the issues list for that module? Perhaps the patch you are looking for is there?
Comment: I'm actually just going to use a jQuery cookie. I did find a patch, but with its current support, I don't really want to risk it.
Comment: Ok, well be sure to post your code as an answer when you're done :)
Answer: Display Suite Extras module (part of Display Suite) has an option to do that.
Answer: What about creating two separate views, each set the way you want and a link as Global Text in the header of each that directs to the other.
Comment: ajax? :)  If that's the feel you want, I would create the two views, and use a custom tpl to show them, with some simple jquery to act as a switch, hiding one and showing the other. Both would load at page time but then there's no delay during the switch.
Comment: Interesting. And how would you ajaxify that switch?
Comment: Thanks Geoff. I didn't mention Ajax in the question because I didn't ask it :)) it was just a comment cause I was thinking about a similar feature. .. you might complete your answer

Views Display Mode Toggle


RewriteCond doesn't match, while literally it should

Question: The goal is to make redirect from
/Swiss+Military/something..

to
/Swiss+Military+Hanowa/something..

I've tried:
RewriteCond %{REQUEST_URI} /Swiss+Military/(.*)
RewriteRule .* /Swiss+Military+Hanowa/%1 [R=301,L]

Rewrite log at level 9 reveals the following:
RewriteCond: input='/Swiss+Military/' pattern='/Swiss+Military/(.*)' => not-matched

I can't figure out why it is not matched..
Any ideas?
SOLVED - need to escape + signs at the pattern (how didn't I remind that myself)
edit
There is even better solution for this case (which I didn't put at the beginning because it didn't worked - of the same reason as the posted one) - just a single RewriteRule:
RewriteRule /Swiss\+Military/ /Swiss+Military+Hanowa/ [R=301,L]

Answer: RewriteCond uses Perl syntax for the pattern. That means the the '+' in your pattern means "match 1 or more" (of the previous character). Try escaping the '+' in your pattern by putting a slash in front of it like this: '\+'.
Comment: Damn... As easy as apple pie.
I'm into PCRE for ages and didn't recognized that I have special character as a literal.

Thank you, **msdin**!


sequential criteria continuous function

Question:
Let $f$ be a real valued function on $(-1,1)$. $f$ is continuous at $0$.
  $f(x)=f(x^2)$ on $(-1,1)$.Then how can be $f(x)=f(0)$ on $(-1,1)$ ?

MY ATTEMPT:
Given $f$ is continous at $0$. Let's choose a sequence $\{c^{2^n}\}$ converging to $0$.
$\lim f(c^{2^n})=f(0)$.how can then proceed
Answer: Let $x \in (-1,1)$. By induction we see that
$f(x)=f(x^{2^n})$ for all $n$ . Since $x^{2^n} \to 0$ as $ n \to \infty$ and $f$ is continuous, we have $f(x^{2^n}) \to f(0)$ as $ n \to \infty$ .
Answer: We get $f(c)= f(c^{2^{n}})$ for all $n$ by induction. For $|c|<1$ we have $\lim_{n \to \infty} c^{n}=0$. This also implies $\lim_{n \to \infty} c^{2^{n}}=0$. Hence $f(c)= f(c^{2^{n}})\to f(0)$ by continuity.

sequential criteria continuous function


Does the order of explanatory variables in logistic regression change the results?

Question: I am curious about the consequences of changing the order of the explanatory variables in a binary logistic regression. In a recent series of logistic regressions I ran in SPSS, I found that changing the order of the explanatory variables ($z, y, x$ instead of $x, y, z$) resulted in different coefficient values and significance levels. Investigating further, I got the same results in R using the same orders. Clearly, shifting the predictors around matters in terms of the results—my question is how? (And yes, I checked to make sure I wasn't entering the variables stepwise.)
Answer: The order of the explanatory does not matter in logistic regression. The symptoms you describe, i.e. the unstable results, may hint at multicollinearity problems or problems of quasi-complete separation in your data. Do you also have large standard errors? As your independent variables are factors, you can tabulate them one against each other and inspect the relation between them. You should also tabulate the covariate patterns against your dependent variable. You can also start by fitting the model stepwise. Then you will see at which point the problem arises.
Comment: OK, but in the presence of multicollinearity, the maximisation routine can have problems to converge, or may even fail to converge. These problems can translate into dicely parameter estimates.
Comment: Even if there was multicollinearity, the coefficients wouldn't change based on what order you entered them into the formula.
Answer: The order in which you enter the variables (into a single model) does not matter. The logistic regression model of a binary response, $Y$, with three predictors $X_{1},X_{2},X_{3}$ -
$$ \log \left( \frac{ P(Y=1) }{ P(Y=0) } \right)
= \beta_{0} + \beta_{1} X_{1} + \beta_{2} X_{2}  + \beta_{3} X_{3} $$
will give identical results to the "re-arranged" logistic regression model
$$ \log \left( \frac{ P(Y=1) }{ P(Y=0) } \right)
= \alpha_{0} + \alpha_{1} X_{2} + \alpha_{2} X_{3}  + \alpha_{3} X_{1} $$
with the coefficients re-arranged appropriately. Here some R code that verifies this:
x1=rnorm(100)
x2=rnorm(100)
x3=rnorm(100)
y=-.3 + .5*x1 + 1.2*x2 - .75*x3 + rlogis(100)
y=(y>0)
g1=glm(y~x1+x2+x3,family="binomial")
g2=glm(y~x2+x3+x1,family="binomial")
summary(g1)
summary(g2)

The code generates from the model
$$ \log \left( \frac{ P(Y=1) }{ P(Y=0) } \right)
= -.3 + .5 X_{1} + 1.2 X_{2}  - .75 X_{3} $$
The estimates for the coefficients of $X_{1}, X_{2}, X_{3}$ (and their significance) is the same regardless of what order you put the variables in. I'm not sure why you'd be finding results that disagree with this. A coding error may be the culprit.
Edit: Based on the comment discussion, it appears that perhaps you are using a categorical predictor and the variables you're including are dummy variables, indicating levels of the predictor. In that case, the order does matter because, in R, the first one entered will be chosen as the "reference" level of the variable and all comparisons are made with respect to it. So, if you change the reference level, you also change the thing the coefficients are being compared to, therefore the estimates and $p$-values can certainly change.
Comment: Are you sure that they are the same coefficients? When you include factors, one level from each is dropped. Maybe a different level is dropped in each of orderings?
Comment: thanks for the response. Can you think of any reason why the following two equations might produce different results? `g1 <- glm(y1~ as.factor(x1) + as.factor(x2) + as.factor(x3), family=binomial(link = "logit"))` vs. `g2 <- glm(y1~ as.factor(x2) + as.factor(x1) + as.factor(x3), family=binomial(link = "logit"))`   ? Because they did for me. All I did was swap the first two terms. (Sorry for the crappy formatting; can't figure out how to make it look better.)
Comment: Another clue—one of the models kicks out one of the categorical variables with the message "Coefficients: (1 not defined because of singularities)," but the other model doesn't do this. I don't understand why the order of the terms would cause R to boot that variable in one model but not the other.
Comment: Normally that error message indicates that some parameters are non-identified. For example, if level '1' of x1 always perfectly coincided with level '1' of x2, the two effects can not be separated from each other. It is mysterious why this would depend on the order in which you enter the variables. Are you sure there is no other code entered between the two calls to glm()?
Comment: Yeah, the order issue is perplexing. But the same thing happened in both R and SPSS, which makes me think it's more than just a simple bug. Same code both times; I promise.
Comment: @Charlie, yes, this is what's happening. Actually, in one ordering one level is dropped, but in the other ordering _zero_ levels are dropped, which accounts for the differences in results. (The algorithm also fails to converge in the latter.) What I can't figure out is, why would the order affect _whether_ a level was dropped as opposed to _which_ level? And given the difference, which results should I choose? I'm guessing the one with the level dropped, as that fixes the multicollinearity issue.
Comment: You can't have 0 levels dropped or else you do have multicolinearity. If the algorithm isn't dropping a level to ensure that the design matrix (the matrix with all your predictor/x variables) is invertible, then that's a bit screwy. I'd be surprised if a canned product is failing to drop a level to remove problems of multicolinearity. That said, I would create dummy variables for each level of each factor, then I would exclude on my own one from each group and running the regression on the remaining dummies. This should be reliable in any order.
Answer: You could try the following in SPSS and see whether it sheds any light:
graph/scatter (matrix) outcome factor1 factor2 factor3.


How to obtain all possible colorings of a knot diagram by a given quandle

Question: Let $K$ be a knot diagram in the plane. Let $C$ be a coloring for $K$ by a quandle $X$. Recall that the relation $x*y =z$ holds at each crossing where $x,z$ are colors of the under arcs , $y$ is the color of the over arc with orientation normal directed tawards the under arc colored by $z$. My question is : Suppose a knot $K$ can be colored by a quandle $X$.  Suppose I start from any crossing and color the over arc by an arbitrary color in $X$ and the under arc by also an arbitrary color, and then  apply the relation to get the color of the other under arc at the chosen crossing, then we trace the knot diagram and at each crossing we apply the quandle relation, if I do this can I guarantee that i'll obtain a valid coloring by $X$. If so then we can obtain all possible colorings of the knot by a given quandle by this way, right?
Answer: No. A simple counterexample is a crossing from a Reidemeister I twist.  If you color the overstrand by anything other than the current color of the understrand, you will immediately get a contradictory coloring.  This contradiction can be deferred arbitrarily far out in time by using Reidemeister moves to put arbitrarily many crossings on the twist.
You can reduce the number of choices by putting a knot into bridge position, coloring the bottom set of bridges arbitrarily, then checking that the top bridges are colored consistently.  For a dihedral coloring, this is a system of $b$ unknowns and $b$ equations (with $b$ the bridge number).  There is no reason to believe that this system of equations will always have either rank $0$ or rank $b$, which is what your conjecture would imply.
Comment: Oh, I see the counterexample which I missed. Thank you so much
Answer: @KyleMiller's answer points out that choosing the color of two strands at a crossing might over-determine the coloring. Conversely, it can happen that such a choice under-determines the coloring. That is to say, there are knots such as $9_{35}$ (not sure that this is the example with fewest crossings) with the property that choosing colors for any two strands will not uniquely determine the colors of all the other strands. This is just to say that there are knots whose fundamental quandle cannot be generated by just two elements.