Vector Algebra Coordinate Transformation

Question: Let us look at two coordinate systems $K$ and $K'$ with axes, respectively, $(x_1,x_2,x_3)$ and $(x_1',x_2',x_3')$ and unit vectors ($\vec{e_1},\vec{e_2},\vec{e_3}$) and ($\vec{e_1'},\vec{e_2'},\vec{e_3'}$) respectively, so $x_i$ and $x_j$ ($i=1,2,3$ and $j=1,2,3$) are the Cartesian coordinates of an arbitrary point $P$. $A_i$ are the coordinates of the origin $O'$ of system $K'$ with respect to $K$.
Now, $b_{ij}$ are the direction cosines of the axes $O'x_j'$ of system $K'$ with respect to $K$. Then this should be true:
$\begin{array} \\
x_1 = a_1 + b_{11}x_1' + b_{12}x_2' + b_{13}x_3' \\
x_2 = a_2 + b_{21}x_1' + b_{22}x_2' + b_{23}x_3' \\
x_3 = a_3 + b_{31}x_1' + b_{32}x_2' + b_{33}x_3' \end{array}$
However for the life of me I cannot figure out why. As far as I know direction cosines are the cosines of the angles between the vector and the three coordinate axes. So $b_{11}$ would be $= \frac {\vec{Ox_1}}{\|\vec{O'x_1'}\|} = \frac{\vec{Ox_1}}{\sqrt{(Ox)_1^2 + (Ox)_2^2 + (Ox)_3^2}}$ OR they would be simply $\frac {x_1}{x_1'}$ - I dont know how what or why.
But I ALSO read that if we take a vector $H$ that exists both in the $K$ and $K'$ systems (with coordinates $H_1,H_2,H_3$ and $H_1',H_2',H_3'$ resp.), then that vector could be written as
$$H = H_1i_1 + H_2i_2 + H_3i_3 \text{ and } H = H_1'j_1 + H_2'j_2 + H_3'j_3$$
and since $H=H$ we can find the components of the vector $H$ in the $K'$ system in term of the components of $H$ in the $K$ system by simply taking the dot product of this equation with the desired unit vector $e$ in the $K'$ system so that
$$\begin{array} \\H_j' = H_1i_j' \cdot i_1 + H_2i_j' \cdot i_2 + H_3i_j' \cdot i_3 &\text{where j = 1,2,3}\end{array}$$
and this I don't get at all, as far as I know the dot product gives you a scalar.
This is terrible notation: I know, I am trying to bridge my two primary sources of information on the matter.  One is a textbook, the other is this this pdf from ocw.mit.edu (page 9).
Comment: For some basic information about writing math at this site see e.g.
[here](//meta.math.stackexchange.com/q/5020),
[here](//meta.stackexchange.com/a/70559),
[here](//meta.math.stackexchange.com/q/1773) and
[here](/help/notation).
Comment: i appreciate the help but what gives making edits to my question without permission?

also, thanks for the info, it wasnt in the general formatting help
Comment: ok, i'm stumped. first off thanks for all the help, second off there were some comments here by you (Bye_World) that are now gone, third off the part that you removed because it was not related to math was sort of an introduction, like "hello, how are you doing" and etc. that is customerly exchanged between people at thte start of a conversation which i find weird to not include, but whatever /rant
Comment: furthermore the problem with my first question is that i don't get the equations themselves, i suppose through some dark magic
$\begin{array} \\
x_i = a_i + b_{i1}x_1' + b_{i2}x_2' + b_{i3}x_3' \end{array}$

should equal $x_i'$ but i don't get how
Comment: and MAN do i hate the guy who thought that pressing "Enter" when writing a comment was the greatest idea ever

also forgot to add i don't get how about the second part a dot product (which should be scalar, as far as i know) can aid in giving us a vector
Comment: What you need to understand from these expressions is that they relate your coordinate systems through an **affine transformation**. This means you can write it as ${\mathbf X'} = {\mathbf A} + {\mathbf B} {\mathbf X}$. The ${\mathbf A}$ term means a **translation**, which is just a displacement, whereas the term ${\mathbf B}$ means a **rotation**.
Answer: Coordinate Transformations:
A short treatise
by Bye_World
First off, let's go over the Einstein summation convention because it's pretty useful for this type of thing.
Let $\vec v \in \Bbb R^3$ be given by $\vec v=v^1\hat e_1 + v^2\hat e_2 + v^3\hat e_3 = \sum_{i=1}^3 v^i\hat e_i$ with respect to the orthonormal basis $\{\hat e_1, \hat e_2, \hat e_3\}$.  Here the superscripts on the scalars $v^1, v^2, v^3$ are NOT EXPONENTS.  They are just indices, the same as on $\hat e_1,$ etc.  The reason to use this superscript index notation is to distinguish between objects which transform contravariantly vs covariantly.  You can look at the link if you'd like more information, but it's not important for you to know what the difference is right now -- you should just take it as notation.
NOTE: You should notice here that $\vec v$ is a vector, $v^1$ is a scalar, and $\hat e_1$ is a vector.
The Einstein summation convention is just a suppression of the summation symbol $\sum$ in this type of expression. So the equation $\vec v = \sum_{i=1}^3 v^i\hat e_i$ would instead just be written $\vec v = v^i\hat e_i$ where summation over the $i$'s is implied.
The exact details are that:

summation is always implied when the same index occurs once as a superscript and once as a subscript.  Such indices are called summing indices or dummy indices.  Example: $\vec v=\sum_{i=1}^3v^i\hat e_i = v^i\hat e_i$.  Here $i$ is the only summing index.
if there is an index which is unpaired, then it is not summed over and must appear on BOTH sides of the equation.  Such indices are called free indices.  Example: $\vec x_a = R^b_a \hat e_b = \sum_{b=1}^3 R^b_a \hat e_b$.  Here $a$ is the free index and $b$ is the summing index.  Notice here that $\vec x_a$ is a vector indexed by $a$ -- it is the $a$th vector in the set $\{\vec x_1, \vec x_2, \dots\}$, where I've left these vectors unspecified --, $R^b_a$ is a scalar indexed by $2$ indices -- where, in general, $R^1_2 \ne R^2_1$ --, and $\hat e_b$ is the $b$th standard basis vector.
if your sum includes more than $1$ of the same index appearing as either a subscript or superscript, then you CANNOT use the Einstein summation convention.  Example: $A^a_bB^c_bx^b\hat e_c$ is not a valid expression using the Einstein summation convention because there are two $b$ subscripts in this single term and thus the summation is ambiguous.  If this summand occurs, you'd have to explicitly use the $\sum$ symbol.

You may have noticed the object $R_a^b$ in the above and wondered what it meant.  Different types of objects are indexed differently.
Vectors are objects whose components can be distinguished by $1$ index.  A vector can always be written as a column matrix where each entry is one of its components (another word for "components" is "coordinates").  For example $\vec v = \begin{bmatrix} v^1 \\ v^2 \\ v^3 \end{bmatrix}$.  This is a $1$ dimensional array of the scalars $v^1, v^2, v^3$ and thus requires only $1$ index to specify any of its components.
A more general matrix, on the other hand, requires $2$ indices.  For example, if $R=\begin{bmatrix} \cos(\theta) & -\sin(\theta) \\ \sin(\theta) & \cos(\theta) \end{bmatrix}$, then to specify a single component we need to specify both the column & the row.  By convention, the $a$th row and $b$th column of the matrix $R$ is denoted $R^a_b$.  Keep in mind that this component $R^a_b$ is a scalar, not a matrix.  In this example, $R^1_2 = -\sin(\theta)$.  We can see then that matrix multiplication is denoted, using the Einstein summation convention, as $X^a_c=Y^a_bZ^b_c$, where $X, Y, Z$ are matrices (multiply two matrices out and make sure that this DOES in fact produce the correct result).
There are higher dimensional objects called tensors which require more than $2$ indices, but again, it's not super important for you to know about them, yet, and I won't be going over them here.

Now, using this new convention, let's start talking about coordinate transformations.  The first thing you should know about coordinate transformations is the difference between passive and active transformations.

An active transformation is when you transform an object -- here the only objects I'll consider are vectors -- directly.  An active transformation does not change the space that the object is in, nor does in change the coordinate system (that is, the set of basis vectors).  The only thing that changes are the coordinates of a single vector (or more general object).  So we'd like a mapping $T: \Bbb R^n \to \Bbb R^n$ given by $T(\vec v) = \vec w$.
Let's look at an example in the plane with respect to the standard basis.  Let's say you wanted to rotate your vector $\vec v=v^{\alpha}\hat e_{\alpha}$ clockwise by $\pi/4$ and then stretch the $x$ component by a factor of $2$.
Our goal here is to find a matrix $T$ such that $w^{\beta} = T^{\beta}_{\alpha} v^{\alpha}$ where $\vec w$ is the result of rotating and scaling $\vec v$ as specified above.  However, trying to find that matrix directly could be a hassle.  Because we know that the composition of linear maps is equivalent to matrix multiplication, why don't we try to split $T$ into the product of $2$ matrices.  Let's let $T=SR$, where $R$ rotates the vector $\vec v$ and then $S$ scales the result.
Let's look at the rotation first:

Assume that the $A$ in the above image was originally pointing along the $x$ direction and then was rotated by angle $\theta$ to its current location.  The coordinates of its new location are then $(\|A\|\cos(\theta),\|A\|\sin(\theta))$.  So apparently our rotation matrix should transform $\begin{bmatrix} \|A\| \\ 0 \end{bmatrix} \mapsto \begin{bmatrix} \|A\|\cos(\theta) \\ \|A\|\sin(\theta)\end{bmatrix}$.  Similarly (you should do it yourself) we could draw a picture to convince ourselves that our rotation matrix should transform $\begin{bmatrix} 0 \\ \|A\|\end{bmatrix} \mapsto \begin{bmatrix} -\|A\|\sin(\theta) \\ \|A\|\cos(\theta)\end{bmatrix}$.
By linearity, we know that this implies $R(1,0) = (\cos(\theta), \sin(\theta))$ and $R(0,1) = (-\sin(\theta), cos(\theta))$.  We now have enough information to construct our transformation matrix: $\begin{bmatrix} \cos(\theta) & -\sin(\theta) \\ \sin(\theta) & \cos(\theta)\end{bmatrix}$.
In our particular case, this means that $R=\begin{bmatrix} \cos(-\frac {\pi}4) & -\sin(-\frac {\pi}4) \\ \sin(-\frac {\pi}4) & \cos(-\frac {\pi}4)\end{bmatrix} = \begin{bmatrix} \frac 1{\sqrt{2}} & \frac 1{\sqrt{2}} \\ -\frac 1{\sqrt{2}} & \frac 1{\sqrt{2}}\end{bmatrix}$ where the negative sign comes from the fact that we're rotating our system clockwise whereas the direction of positive increase of angles is conventionally counterclockwise.
Now for the scaling matrix.  By definition it takes any vector $(x,y) \mapsto (2x,y)$.  I hope it should be fairly obvious that the matrix representation of it is $\begin{bmatrix} 2 & 0 \\ 0 & 1\end{bmatrix}$, but if not you can figure it out the same way as above.
Now that we have $S$ and $R$ we can find our matrix $T$ by just multiplying the two together:  $$T = SR = \begin{bmatrix} 2 & 0 \\ 0 & 1\end{bmatrix}\begin{bmatrix} \frac 1{\sqrt{2}} & \frac 1{\sqrt{2}} \\ -\frac 1{\sqrt{2}} & \frac 1{\sqrt{2}}\end{bmatrix} = \begin{bmatrix} \sqrt{2} & \sqrt{2} \\ -\frac 1{\sqrt{2}} & \frac 1{\sqrt{2}}\end{bmatrix}$$
Using the Einstein summation convention, our transformation is then $w^{\alpha} = S^{\alpha}_{\beta}R^{\beta}_{\gamma}v^{\gamma} = T^{\alpha}_{\delta}v^{\delta}$.  In general ALL active linear transformations of vectors will have the form $w^{\alpha} = T^{\alpha}_{\beta}v^{\beta}$, where $w^{\alpha}$ is the $\alpha$th component of the vector $\vec w$ (with respect to some basis -- in my example it's the standard basis), $T^{\alpha}_{\beta}$ is the component of the matrix $T$ in the $\alpha$th row and $\beta$th column, and $v^{\beta}$ is the $\beta$th component of the vector $\vec v$ with respect to the same basis as $\vec w$.
Let's go ahead and calculate the coordinates of our vector $\vec w$:  $$\vec w = T\vec v = \begin{bmatrix} \sqrt{2} & \sqrt{2} \\ -\frac 1{\sqrt{2}} & \frac 1{\sqrt{2}}\end{bmatrix} \begin{bmatrix} v^1 \\ v^2 \end{bmatrix} = \begin{bmatrix} \sqrt{2}v^1 + \sqrt{2}v^2 \\ -\frac 1{\sqrt{2}}v^1 + \frac 1{\sqrt{2}}v^2\end{bmatrix} = (\sqrt{2}v^1 + \sqrt{2}v^2)\hat e_1 + (-\frac 1{\sqrt{2}}v^1 + \frac 1{\sqrt{2}}v^2)\hat e_2$$

Things to notice:

Active transformations do not change the SYSTEM OF COORDINATES -- they only change the coordinates of A SINGLE VECTOR.  This can be seen by the fact that the general formula for an active transformation of a vector is $w^{\alpha} = T^{\alpha}_{\beta}v^{\beta}$ -- nowhere in this formula do the basis vectors show up.
In fact, an active transformation can be defined even when there is no coordinate system specified.  I have used the standard basis as my coordinate system so that I can get actual numbers, but in general, we can define an active transformation without doing so.
An active transformation must be a transformation of a space into itself.  It would not be defined for more general transformations $T: V \to W$.

Now let's look at passive transformations. Passive transformations are when you have some object in your space (such as a vector), but instead of transforming that object, you transform the coordinate system around it.  The coordinates of that object will then change with (or actually against) the change in the basis vectors so that it stays the same.  So to contrast a passive transformation with an active transformation, in a passive transformation, we want to transform the basis vectors themselves and a change in the coordinates of a vector are the result of keeping that vector the same, and in an active transformation we want to transform the coordinates of a specific vector with respect to a given set of basis vectors.
So let's look at an example.  We've covered rotation and scaling transformations.  How about this time we do a shear transformation?  Let's look at the transformation $\hat e_1 \mapsto \vec f_1 = \hat e_1 + \hat e_2$ and $\hat e_2 \mapsto \vec f_2 = \hat e_2$.  I'll leave it to you to verify that the set $\{\vec f_1, \vec f_2\}$ is a basis for the plane.
We see that the matrix which corresponds to this transformation is $T=\begin{bmatrix} 1 & 1 \\ 0 & 1\end{bmatrix}$ because $$\begin{bmatrix} \vec f_1 \\ \vec f_2 \end{bmatrix} = \begin{bmatrix} \hat e_1 + \hat e_2 \\ \hat e_2 \end{bmatrix} = \begin{bmatrix} 1 & 1 \\ 0 & 1\end{bmatrix} \begin{bmatrix} \hat e_1 \\ \hat e_2 \end{bmatrix}$$
So let's see how the components of the vector $\vec v = v^{\alpha}\hat e_{\alpha}$ change when we represent it in the $\{\vec f_1, \vec f_2\}$ basis.
Well, first note that because it is a basis of the plane, we can represent the vector $\vec v$ as a linear combination of $\vec f_1, \vec f_2$.  Therefore $\vec v = v^{\alpha}\hat e_{\alpha} = v^{\alpha'}\vec f_{\alpha'}$.  Notice here that I use the notation $\alpha'$ to show that the components are with respect to a different basis.  Also note that $\alpha$ and $\alpha'$ are different symbols and thus when they both appear in one term (as they will in a second), summation will NOT be implied (i.e. $a^x\vec b_{x'} \ne a^1\vec b_{1'} + a^2\vec b_{2'} + \cdots$).
We have $\vec v = v^{\alpha}\hat e_{\alpha} = v^{\alpha'}\vec f_{\alpha'} = v^{\alpha'}(T_{\alpha'}^{\alpha}\hat e_{\alpha}) = (T_{\alpha'}^{\alpha}v^{\alpha'})\hat e_{\alpha}$.  Therefore we've found that $v^{\alpha} = T_{\alpha'}^{\alpha}v^{\alpha'}$.
And knowing that $\vec f_{\alpha'} = T\hat e_{\alpha}$ gives us $\hat e_{\alpha} = T^{-1}\vec f_{\alpha'}$ (note that a change of coordinates MUST be invertible).  Therefore by the same steps as in the above paragraph, we have that $v^{\alpha'} = [T^{-1}]^{\alpha'}_{\alpha}v^{\alpha}$.
Having found equations relating $v^{\alpha'}$ to $v^{\alpha}$ and $\hat e_{\alpha}$ to $\vec f_{\alpha'}$, we've completely characterized our transformation.
I'll leave it to you to actually calculate what the components of $\vec v$ are with respect to this new basis.

Things to note:

A passive transformation is a transformation of the basis vectors.  However, for a vector to stay the same, its coordinates will need to change as well to reflect the change of basis.  Given the change of basis $\vec e_i \to \vec f_i$, for $i=1,2,\dots, n$, a given vector can be represented by either set of coordinates: $\vec v = v^{\alpha}\vec e_{\alpha} = v^{\alpha'}\vec f_{\alpha'}$.
The general equations for this are: $\vec f_{\alpha'} = T_{\alpha'}^{\alpha}\hat e_{\alpha}$, $\ \ \hat e_{\alpha} = [T^{-1}]^{\alpha'}_{\alpha}\vec f_{\alpha'}$, $\ \ v^{\alpha} = T_{\alpha'}^{\alpha}v^{\alpha'}$, and $v^{\alpha'} = [T^{-1}]^{\alpha'}_{\alpha}v^{\alpha}$.
Each of those four above equations is enough to derive the others, so you wouldn't need to memorize them (though it's not particularly hard given their symmetric nature).
Our space must be equipped with a coordinate system (set of basis vectors) for a passive transformation to make sense.

So far, we've only talked about linear transformations.  An affine transformation can be described by a linear transformation plus a translation.
For fun, let's see why it doesn't matter whether we perform the translation or linear transformation first: if we have some vector $\vec v$ and we'd like to apply the affine translation $G$ to it, then we could represent it as $G(\vec v) = L(\vec v) + \vec t$, where $L$ is a linear transformation (one that can be represented by a matrix) and $\vec t$ is a translation vector.  It could also be represented by $G(\vec v) = L(\vec v + \vec s)=L(\vec v) + L(\vec s)$, where we can see that $L(\vec s) = \vec t$.  Thus they are equivalent.
Your system of equations is a representation of an affine transformation.  We could represent it in matrix form as $$\begin{bmatrix} x^1 \\ x^2 \\ x^3 \end{bmatrix} = \begin{bmatrix} b^1_{1'} & b^1_{2'} &b^1_{3'} \\  b^2_{1'} & b^2_{2'} &b^2_{3'} \\ b^3_{1'} & b^3_{2'} &b^3_{3'} \end{bmatrix}\begin{bmatrix} x^{1'} \\ x^{2'} \\ x^{3'} \end{bmatrix} + \begin{bmatrix} a^1 \\ a^2 \\ a^3 \end{bmatrix}$$
Or in index notation as:
$$x^{\alpha} = b^{\alpha}_{\alpha'} x^{\alpha'} + a^{\alpha}$$
(Do you see how this notation is much cleaner?)
The linear part works exactly as normal.  And the translation part should be pretty clear as well -- after the vector is transformed linearly, it is translated by $\begin{bmatrix} a^1 \\ a^2 \\ a^3 \end{bmatrix}$.
This is technically enough to specify your transformation, but notice that as a passive transformation, it'd be nice if we had a formula relating the basis vectors of the $K$ and $K'$ systems of coordinates.  I'll leave this as an exercise for you.  Notice that this will also be an affine transformation, so if you can't figure it out, let me know.  HINT: if the coordinates of the vector is translated in this direction $\vec a$, which direction should the basis vectors be translated so that the vector stays the same?

Things to notice:

Technically every linear transformation is an affine transformation.  We can see this by setting the translation vector $\vec t=0$.
However, we generally consider affine spaces to not contain the origin.  Remember that vector spaces always contain the origin and a linear mapping always maps to origin to the origin.  Thus, we wouldn't generally want to treat a space we know is a vector space as an affine space, or we'd lose some tools for dealing with it.

NOTE: I have not focused on affine transformations here because it seems your problems are more with the linear parts of these transformations.  If you'd like more help in understanding affine transformations, let me know and I can go further into it.

Now, let me try to take a crack at your questions:
First question: Why are the elements $b^i_j$ the cosines of the angles between the $i$th basis vector of $K$ and the $j$th basis vector of $K'$?
Let's focus on the linear transformation $$\begin{bmatrix} x^1 \\ x^2 \\ x^3 \end{bmatrix} = \begin{bmatrix} b^1_{1'} & b^1_{2'} & b^1_{3'} \\ b^2_{1'} & b^2_{2'} & b^2_{3'} \\ b^3_{1'} & b^3_{2'} & b^3_{3'} \end{bmatrix}\begin{bmatrix} x^{1'} \\ x^{2'} \\ x^{3'} \end{bmatrix}$$
This seems to be your problem, and the translation part of your original problem isn't super difficult.
Notice that $K =\{\hat e_1, \hat e_2, \hat e_3\}$ and $K' = \{\hat f_{1'}, \hat f_{2'}, \hat f_{3'}\}$ (I've changed your notation for the basis vectors of $K'$ slightly) are both orthonormal bases.  So let's consider an arbitrary vector $\vec x \in \Bbb R^3$.  Because $K$ and $K'$ are both bases of $\Bbb R^3$, we can represent $\vec x$ as a linear combination of either basis:  $\vec x = x^{\alpha}\hat e_{\alpha} = x^1\hat e_1 + x^2\hat e_2 + x^3\hat e_3 = x^{\alpha'}\hat f_{\alpha'} = x^{1'}\hat f_{1'} +x^{2'}\hat f_{2'} + x^{3'}\hat f_{3'}$.  What we'd like to get here is the relationship between each $x^{\alpha}$ and $x^{\alpha'}$.
We can see from the above matrix equation (and from our earlier discussion on passive transformations) that the relationship should be $x^{\alpha} = b^{\alpha}_{\alpha'}x^{\alpha'}= b^{\alpha}_{1'}x^{1'} + b^{\alpha}_{2'}x^{2'} + b^{\alpha}_{3'}x^{3'}$.  So what we need to do is figure out what these $b^{\alpha}_{\alpha'}$'s are.
To do that, let's take the dot product of $\vec x$ with $\hat e_{1}$.  Then we have $\hat e_1 \cdot \vec x = \hat e_1 \cdot (x^1\hat e_1 + x^2\hat e_2 + x^3\hat e_3) = \hat e_1 \cdot (x^{1'}\hat f_{1'} +x^{2'}\hat f_{2'} + x^{3'}\hat f_{3'})$.  Let's take this one step at a time.  The left equality gives us $\hat e_1 \cdot \vec x = x^1(\hat e_1 \cdot \hat e_1) + x^2(\hat e_1 \cdot \hat e_2) + x^3(\hat e_1 \cdot \hat e_3) = x^1(1) + x^2(0) + x^3(0) = x^1$.  The ones and zeroes come from the fact that $K$ is an orthonormal basis set.
The right equality gives us $\hat e_1 \cdot \vec x = x^{1'}(\hat e_1 \cdot \hat f_{1'}) + x^{2'}(\hat e_1 \cdot \hat f_{2'}) + x^{3'}(\hat e_1 \cdot \hat f_{3'})$.  Here the dot products don't just give us ones and zeroes because $\hat e_1$ is not necessarily orthogonal or parallel to any of the $\hat f_{\alpha'}$'s.  So we'll have to evaluate them with the identity $\vec a \cdot \vec b = \|\vec a\|\|\vec b\|\cos(\theta_{a,b})$, where $\theta_{a,b}$ is the angle between the vectors $\vec a$ and $\vec b$.
In this case $\hat e_1 \cdot \hat f_{\alpha'} = (1)(1)\cos(\theta_{1,\alpha'})$, where $\theta_{1,\alpha'}$ is the angle between $\hat e_1$ and $\hat f_{\alpha'}$.  Thus we have $\hat e_1 \cdot \vec x = x^{1'}\cos(\theta_{1,1'}) + x^{2'}\cos(\theta_{1,2'}) + x^{3'}\cos(\theta_{1,3'})$.
Putting these two equalities back together, we have $x^1 = x^{1'}\cos(\theta_{1,1'}) + x^{2'}\cos(\theta_{1,2'}) + x^{3'}\cos(\theta_{1,3'})$.  Notice that this is of the form $x^1 = b^1_{1'}x^{1'} + b^1_{2'}x^{2'} + b^1_{3'}x^{3'}$.  Because the values of $b^{\alpha}_{\alpha'}$ for each $\alpha$ and $\alpha'$ are unique, we know that $b^1_{1'} = \cos(\theta_{1,1'})$, $b^1_{2'} = \cos(\theta_{1,2'})$, and $b^1_{3'} = \cos(\theta_{1,3'})$.  We'd get similar results by taking the dot product of $\vec x$ with $\hat e_2$ and $\hat e_3$, so we can say that in general $b^{\alpha}_{\alpha'} = \cos(\theta_{\alpha,\alpha'})$.  Where remember $\cos(\theta_{\alpha,\alpha'})$ is just the cosine of the angle between $\hat e_{\alpha}$ and $\hat f_{\alpha'}$.
Second Question: How does the equation $\begin{array} \\H_j' = H_1i_j' \cdot i_1 + H_2i_j' \cdot i_2 + H_3i_j' \cdot i_3 &\text{where j = 1,2,3}\end{array}$ make sense when the dot product produces a scalar?
Hopefully by now you see that both the left and right hand sides are in fact scalars.  The LHS is the $j$th component of the vector $H$ in the primed basis and the right hand side is an expression for calculating this component w.r.t. to the components of the unprimed basis.  The scalar $H^a\hat f_{b'} \cdot\hat e_a$ is just the component $H^a$ multiplied by the cosine of the angle between the vector $\hat f_{b'}$ and $\hat e_a$ (I've changed the notation to mine so that you can see how my notation relates to yours) -- where summation is implied by the Einstein convention.
Comment: The Einstein summation convention is interesting, we have learned about that method, only i don't recall we calling it exactly that, but it was possibly mentioned once or something. :)
More interestingly we learn that summation is supposed if an index occurs TWICE, since we mostly note indices as subscripts, noting an index as a sueprscrips is rare with us, so just mentioning something peculiar. :)
I will add some more later, since i guess comments can only be edited a certain time after they are posted and i mistakenly pressed "Enter" to enter a new line already. :)
Comment: ok, i finally got to read it all, first of all - thanks a bunch, your answer is well formed, thorough, detailed and very informational, second you answered my second question perfectly, i just d-oh'ed realizing $H'$ was a scalar, but my first question remains unanswered, i think you misinterpreted it because it is so basic. Firstly i am not sure i get what directional cosines are - are they just the relationship between one vector and the other like vector1/vector2? and in any case - why would coordinate $x_1$ be equal to a sum of ALL coordinates*directional cos?
Comment: @mathgenius I've edited my answer.  See if it answers your question now.
Comment: thank you, i get it now, could you do me one last favor and tell me what directional cosines really are?
Comment: @mathgenius Just a term that means the cosine of the angle between two vectors.  The concept didn't really need a name, IMO, but someone noticed that any transformations which just rotate/ reflect the basis vectors (without changing their length or relative angles) will be representable by a matrix whose every entry is the cosine of the angles between the old basis vectors and the new basis vectors -- thus the name "directional cosine".  More interestingly, the inverse of this type of matrix is always its transpose.  This does deserve a name, IMO -- its called an orthogonal matrix.
Comment: Oh, Jeesus Chirst, the wikipedia entry on directional cosines confused me so much, it prevented me from understanding this simple set of equations. :) Thank you again for all your help!


how to transfer files from desktop to server when using ssh

Question: I am using ssh to connect to a server.  I want to upload local files to the server. Usually I do this by opening the 'New File Transfer Window'  However, i'd like to just do this from the command prompt.
what is the command to do this?
Comment: Please include the operating system you are connecting from.
Answer: You can do this with rsync.
Something like this should suffice:
rsync -av /path/to/Desktop/ server.name:/path/to/destination

The -av tells rsync to 'archive' (maintains permissions, acts recursively, etc) and to be verbose (print transferred filenames).
Note: if you leave a trailing / at the end of 'Desktop', the contents of the Desktop will be transferred. Without the slash, all documents will be transferred into a folder called 'Desktop' on the destination.
Comment: This would address the question (technically) if you included the -e ssh flag to rsync.
Comment: Right, but that isn't necessary with modern versions of rsync. It transfers files over ssh by default.
Comment: Right you are.  I guess I'm showing my age.
Answer: Since you mention the "New File Transfer" window, my guess is that you're using the ssh.com SSH2 client.
SCP2.EXE is the program to copy files over ssh from the command line.
Comment: yes I use ssh2. but why do i need to download scp2.exe. cant I just use the terminal window to transfer files?
Comment: That terminal window is open on the *server*.  So any transfers you initiated there would be from that server.  It would require a similar SSH server on your side to accept the transfer request.  To do something on a terminal, you would need something local, like a command prompt.  Then call SCP2.exe, or Putty's pscp.exe.
Answer: Sometimes for small text files I copy the contents to the clipboard then paste it to cat in the terminal window. E.g.

Copy text
cat > path/to/file
Paste the file (Shift-Inset) works in putty
Type enter if the file doesn't end in one (makes next key stroke work)
Type Ctrl-D to terminate the input stream
Comment: +1 I do too. I doubt this is the answer he wanted but it is sometimes the quickest way for small files and quick edits.


Is $X=\{(0,0),(1,0)\}\cup \bigcup_{n \neq 1}\{(x, 1/n) \mid x\in \mathbb{R}\}$ connected? Find its conmected components.

Question:
Is $$X=\{(0,0),(1,0)\}\cup \bigcup_{n \neq 1}\{(x, 1/n) \mid x\in \mathbb{R}\}$$ connected with the usual topology on $\mathbb{R}^2$? Find its conmected components.

I have a vague idea if what this space $X$ looks like, and I don't know the answer so I thought I could try to provethat the set is not locally connected.
I think that the points $(0,0), (1,0)$ might be problematic but I'm not sure how to take it from there. I think that if $U$ is an open set not containing, then it is disconnected since we could write it terms of unions of points $\{x,1/n_i\}$, but I'd need to prove that this sets are open, but I don't know how.
The plan is proving that the connected components of $X$ are the points $\{x,1/n\}$ and $(0,0),(1,0)$, then show that $(0,0),(1,0)$ are not open and hence $X$ is not locally connected. But I'd really need some help to point me at the right direction. Thanks in advance!
Comment: You seem to be mis-interpreting the set $\{(x,1/n) \, \bigm| \, x \in \mathbb{R}\}$. Think of it as the horizontal line given by the equation $y=1/n$.
Answer: Suppose we have two nonempty connected sets $A,B$ in a topological space X, and we're wondering if $A \cup B$ is connected. For the union to be connected, it suffices to consider any two open sets $U$ containing $A$, $V$ containing $B$, and show $U \cap V$ necessarily have non-empty intersection (why is this? try drawing a picture/proving this statement directly). If the union is disconnected, you need to find $U,V$ (U contains A, V contains B) such that $U \cap V = \emptyset$
Now your set $\{(x, \frac{1}{n})| x \in \mathbb{R}\}$ are each connected because they are path connected, (because they are horizontal lines) (You should really prove it's path connected if it's unclear). Hence it's connected. Clearly, the points $(0,0)$ and $(0,1)$ are connected as sets in their own right, so by the lemma it suffices to take an open set U around $(0,0)$, and an open set $V$ around $A=\{(x, \frac{1}{n})| x \in \mathbb{R}\}$ and prove $U \cap V \neq \emptyset$ to show the union of the two is connected, or find open balls $U, V$ s.t $U \cap V = \emptyset$ and this will show the union of the two isn't connected. Since the topology on $\mathbb{R}$ is generated by a basis of open balls, it's sufficient to take $U,V$ to be open balls.
Comment: The set $A$ in your second paragraph is certainly not connected: it's the union of the lines $y=\frac1n$ for $n\ne 1$.
Comment: You're right-- sloppy mistake I assumed it was another familiar exercise without reading carefully!
Comment: Let me guess: you were thinking of one of the comb spaces.
Answer: Each line $I_n={\Bbb R} \times \{1/n\}$, $n\geq 2$ is clearly a connected component. It is connected and it is closed and open (for the topology induced on  $X$). A connected component is a maximal connected set, i.e. an increasing union of connected sets which is not contained in any strictly larger connected set. Being in a maximal connected set is an equivalence relation between points so the special points $\{(0,0)\}$ and $\{(1,0)\}$ must be in components different from every $I_n$. So each of them is a connected component by itself (consisting of one point).
Note that $\{(0,0)\}$ being in the closure of the $I_n$'s  does not imply that it belongs to a strictly larger components. For example the connected components (in ${\Bbb R}$)  of $\{0\} \cup \{1/n: n\geq 1\}$ consists of one point sets (essentially the same exercise as the present).


VUE: Com recuperar uma variável do array filtrando pelo valor

Question: Boa tarde, estou precisando recuperar a variável name desse array de objetos, quando eu filtrar pelo id, quando eu digitar por exemplo o id 1, retornar "Sólido"
full_category_list: [
    {
        id: 1,
        name: 'Sólido',
        parent : 0,
    },
    {
        id: 2,
        name: 'Líquido',
        parent : 0
    }
]

Answer: Você pode criar uma computed property que calculará qual a categoria selecionada.

new Vue({
    el: '#app',
    data: {
        selected: null,
        full_category_list: [
            {
                id: 1,
                name: 'Sólido',
                parent : 0
            },
            {
                id: 2,
                name: 'Líquido',
                parent : 0
            }
        ]
    },
    computed: {
        selected_category: function() {
            var category = this.full_category_list.find(cat => cat.id == this.selected);
            return category ? category.name : "Nenhum selecionado";
        }
    }
});

  <input v-model="selected">

{{ selected_category }}


angular2 work with Observable(Http) without reloading

Question: I have a PartnersService that in constructor load list of partners array from server.
this.partners = this._http.get('/app/partners/partners.data.json')
            .map(this.extractData)
            .catch(this.handleError);

When I get a list of partners, everything OK.
But I need to get partner by ID.
In this case, I use function with callback
getPartner(id:number, callback:(partner:Partner)=>void):void {
    this.partners.subscribe(partners=> {
        for (let partner of partners) {
            if (partner.id == id) {
                callback(partner);
            }
        }
    });
}

In browser console, I see that any time when I call subscribe, angular2 send request to server. Can I do something, to not send request any time? And maybe exist better way to create getPartner() function(without callback)?
Answer: You could try something like that:
getPartners() {
  if (this.partners) {
    return Observable.of(this.partners);
  } else {
    return this._http.get('/app/partners/partners.data.json')
        .map(this.extractData)
        .catch(this.handleError)
        .do(partners => {
          this.partners = partners;
        });
  }
}

getPartner(id:number):Observable<partner> {
  this.getPartners().map(partners => {
    return partners.find(partner => (partner.id == id));
  });
}

And execute the method this way:
this.service.getPartner('some id').subscribe(partner => {
  console.log(partner);
});

Comment: I like this a lot! But where will `this.partners` be assigned?
Comment: Thanks! Its work, but.... Here is my code [plnkr.co](http://plnkr.co/edit/vLVW6VmYzvVIksEZIPyd?p=preview). Its work if it loaded from default route(PartnersPage). But if I reload page on url 'somesite.com/#/partner/1', then I receive error: "TypeError: Cannot read property 'name' of undefined in [{{partner.name}} in PartnerInfoDirective"
Comment: You're welcome! I think that it's because the data i's loaded asynchronously at the beginning. You should use the Elvis operator: "{{partner?.name}}".
Comment: Elvis operator not help.
Comment: Could you update your question with the content of the component where the error occurs? Thanks!
Comment: I update code [plnkr.co](http://plnkr.co/edit/vLVW6VmYzvVIksEZIPyd?p=preview). When I add elvis operator, the error no longer occurs, but the data are not displayed on the page(app/partner.info.directive.html) if I reload page on url 'somesite.com/#/partner/1'
Comment: Your problem is because the template path isn't correct for the partner details component. See this working plunkr: http://plnkr.co/edit/019KUADxCPWQl37dSWVi?p=preview.
Comment: You about `templateUrl: './app/partners.details.html'`? This not help.
Comment: What do you mean by "this not help"? The details screen is displayed in my case...
Comment: Its work fine if in app/partners.details.ts I initialize Partner `private partner:Partner = new Partner();` [plnkr.co](http://plnkr.co/edit/vLVW6VmYzvVIksEZIPyd?p=preview). But I'm not sure that's right way.
Comment: Thierry, details page open's fine when you start app from default route `PartnersPage`. But if you go to '.../#/partner/1' and then reload page: "TypeError: Cannot read property 'name' of undefined in [{{partner.name}} in PartnerInfoDirective"
Answer: You could use publishLast() as well to capture the event.
constructor() {
  this.partners = this._http.get('/app/partners/partners.data.json')
        .map(this.extractData)
        .catch(this.handleError)
        //shares the subscription with all observers so you don't get repeated
        //calls and caches the result.
        .publishLast();
  //Initiates the http call
  this.connection = this.partners.connect();
}

getPartner(id:number):Observable<partner> {

  return this.partners
             //Convert Observable<partner[]> to Observable<partner>
             .flatMap(x => x)
             .filter(p => p.id === id);
}

Comment: Its work to, but I get the same error(see description in my previous comment)
Comment: I would assume because you are trying to load Partner before the service has returned it. I am not familiar enough with Angular2 to tell you how to do an @Input asynchronously, but for Rx you should avoid "breaking" out of the Observable, in anything but trivial applications it will become a nightmare to track your system state. See my modification to your [plunkr](http://plnkr.co/edit/r4r4IOv8qHC7GQnQBRWT?p=preview)


Pacemaker monitoring mysql

Question: I have Pacemaker+Corosync set up to manage a shared IP address between two Mysql boxes in Master-Master/Active-Passive setup (using interleaved primary keys).
I have Pacemaker set up to manage the shared IP between the two machines, however, it currently only migrates the IP when a node is down rather than when there is a problem with mysql. I would like the IP to fail over automatically if there is a problem connecting to the local mysql instance.
The configuration section of my cib.xml looks like this...
<configuration>
    <crm_config>
      <cluster_property_set id="cib-bootstrap-options">
        <nvpair id="cib-bootstrap-options-dc-version" name="dc-version" value="1.0.9-89bd754939df5150de7cd76835f98fe90851b677"/>
        <nvpair id="cib-bootstrap-options-cluster-infrastructure" name="cluster-infrastructure" value="openais"/>
        <nvpair id="cib-bootstrap-options-stonith-enabled" name="stonith-enabled" value="false"/>
        <nvpair id="cib-bootstrap-options-expected-quorum-votes" name="expected-quorum-votes" value="2"/>
      </cluster_property_set>
    </crm_config>
    <nodes>
      <node id="db0.xxx.xxx" uname="db0.xxx.xxx" type="normal"/>
      <node id="db1.xxx.xxx" uname="db1.xxx.xxx" type="normal"/>
    </nodes>
    <resources>
      <group id="group1">
        <primitive class="ocf" id="ip0" provider="heartbeat" type="IPaddr2">
          <instance_attributes id="ip0-instance_attributes">
            <nvpair id="ip0-instance_attributes-ip" name="ip" value="192.168.101.139"/>
            <nvpair id="ip0-instance_attributes-nic" name="nic" value="eth0"/>
            <nvpair id="ip0-instance_attributes-cidr_netmask" name="cidr_netmask" value="22"/>
            <nvpair id="ip0-instance_attributes-broadcast" name="broadcast" value="192.168.103.255"/>
          </instance_attributes>
        </primitive>
      </group>
    </resources>
    <constraints>
      <rsc_order id="ip_before_lvs" score="INFINITY">
        <resource_set action="start" id="ip_before_lvs-0">
          <resource_ref id="ip0"/>
        </resource_set>
      </rsc_order>
    </constraints>
    <rsc_defaults/>
    <op_defaults/>
  </configuration>

I think that I need to add something like the following to my ip0 primitive...
<operations>
  <op id="....
</operations>

But I am not sure exactly what I would need in order to check that mysql was running, and also probably log in to mysql and perform a query with a known output. If those two checks fail then the resource should be migrated.
Any pointers appreciated.
Answer: I have the exact same setup with heartbeat...
The problem we face is knowing when to migrate the write ip..
Basically checking via login and select doesnt work, i have seen certain tables being corrupted and the one being checked to be fine.
Right now im listening to the mysql log, which is the only reliable place for catching problems...
(after long consideration, i decided not to do automatic migrating)
Hope this helps :)
Comment: I wanted to move the IP if mysql dies really, not after any kind of table corruption etc. I do trust it to do that automatically. Any idea how I even go about configuring it to move a shared IP in response to mysql not running, at the moment pacemaker is trying to start and stop mysql for me which I definitely don't want to happen!
Comment: I never use pacemaker/heartbeat to manage resources other than IP addresses.. i dont like the idea of a cluster managing init scripts..

A cluster in my opinion should all be running not pieces starting and stopping ( basically the ip is the glue that holds it together )...

Use an ip address which moves between nodes (preferably 2 mysql only).. Using replication on the servers in master/master with interleaved keys ( or dont use auto-increment )....

Basically configure a "mysql write" IP which moves to your write masters..
And handle Mysql failure on a different level

Pacemaker monitoring mysql


Proportion multiple components failing when knowing one component failing

Question: Let's consider a system having 3 similar components. The probability of having only one component failing is 10%.
If we don't take into account the sampling error, can I say that, the probability to have 2 components failing is $(10\%)^2 = 1\%$, and the probability to have 3 components failiing is $(10\%)^3 = 0.1\%$?
If I have probability to have 2 components failing = 10% and probability to have 3 components failing is 16%, can I conclude that there is another event which makes also the 3 components failing together?
And, last but not least, I didn't found any formula for that because I don't know the naming of this kind of problem in the statistics world. What should I have searched for?
Thanks a lot
P.S.: For context, I have a real case showing those probability of failure, for which we want to establish the root cause. Having seen that chain, and knowing that those 3 components are at some point managed together, and at another point independently,  those proba tends to tell me that there are two issues: one at common part, and one at independant part.
Comment: I have a question on this. What if each of the 3 components has different individual failure probability, let say p1, p2, and p3? what would be the formula?
Answer: If the failure probabilities are independent, and each of the $N$ components has an individual failure probability of $p$, then the number of failures $n$ will have a Binomial distribution
$$\Pr[n=k]=\begin{pmatrix}N\\ k\end{pmatrix}p^k(1-p)^{N-k} \text{ , } k=0,1,\ldots,N$$
Here the factor in parentheses is a binomial coefficient, and is read as "$N$ choose $k$", representing the number of distinct combinations of $k$ elements that can be chosen from a set of $N$.
In your case $N=3$ and $p=0.1$. In particular, the probability that $n=2$ is not given by $p^2=0.01$, because you must account for 1) the different combinations of two components that could fail, and 2) the probability that the third component doesn't fail, i.e.
\begin{align}
\Pr[n=2] &= \begin{pmatrix}3\\ 2\end{pmatrix}\times{0.1^2}\times{0.9} \\
&= 3\times{0.01}\times{0.9} \\
&= 2.7 \%
\end{align}
The binomial distribution only applies if the component failure probabilities are i.i.d.. From your description, this may not be the case.
Comment: Thanks a lot. I should have thinked about binomial, indeed.


Show that the set of Hermitian matrices forms a real vector space

Question: How can I "show that the Hermitian Matrices form a real Vector Space"? I'm assuming this means the set of all Hermitian matrices.
I understand how a hermitian matrix containing complex numbers can be closed under scalar multiplication by multiplying it by $i$, but how can it be closed under addition? Wouldn't adding two complex matrices just produce another complex matrix in most instances?
Also, how can I find a basis for this space?
Comment: Hermitian matrices are not closed under multiplication by $i$, that's why they don't form a *complex* vector space, only a real one.
Comment: related: https://math.stackexchange.com/q/91598/173147
Answer: Hint:
i give you the intuition for $2\times 2$ matrices that you can extend to the general case.
An Hermitian $2\times 2$ matrix has the form:
$$
\begin{bmatrix}
a&b\\
\bar b&c
\end{bmatrix}
$$
with: $a,c \in \mathbb{R}$ and $b\in \mathbb{C}$ ($\bar b $ is the complex conjugate of $b$).
Now you can see that, for two matrices of this form, we have:
$$
\begin{bmatrix}
a&b\\
\bar b&c
\end{bmatrix}
+
\begin{bmatrix}
x&y\\
\bar y&z
\end{bmatrix}=
\begin{bmatrix}
a+x&b+y\\
\bar{b}+\bar{y}&c+z
\end{bmatrix}
$$
and, since $\bar{b}+\bar{y}=\overline{b+y}$ the result is a matrix of the same form, i.e. an Hermitian matrix.
For the product  we have:
$$k
\begin{bmatrix}
a&b\\
\bar b&c
\end{bmatrix}=
\begin{bmatrix}
ka&kb\\
k\bar b&kc
\end{bmatrix}
$$
so the result matrix is Hermitian only if $k$ is a real number.  Finally we see that the null matrix is hermitian and the opposite of an Hermitian matrix is Hermitian, so the set of hermitian matrix is  real vector space.
For the basis:
Note that an hermitian matrix can be expressed as a linear combination with real coefficients in the form:
$$
\begin{bmatrix}
a&b\\
\bar b&c
\end{bmatrix}=
a\begin{bmatrix}
1&0\\
0&0
\end{bmatrix}+
\mbox{Re}(b)
\begin{bmatrix}
0&1\\
1&0
\end{bmatrix}
+\mbox{Im}(b)
\begin{bmatrix}
0&i\\
-i&0
\end{bmatrix}
+c
\begin{bmatrix}
0&0\\
0&1
\end{bmatrix}
$$
and ,since the four matrices at the right are linearly independent, these form a basis.
Comment: I can't believe you answered this a year ago without an upvote. With regards,
Comment: please see my question here  https://math.stackexchange.com/q/3766237/676071    @Emilio Novati


Deleting from database, unsuccessful

Question: I am trying to delete an entry from a database have been unsuccessful.  Here is my code to show what I am doing. I create a ContextMenu, which opens a new menu titled "Delete" but when I click on this delete it doesn't delete the selected item. It just doesn't do anything.
main.java:
import java.util.List;
import java.util.Random;

import android.app.ListActivity;
import android.os.Bundle;
import android.text.Editable;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuInflater;
import android.view.View;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import android.view.MenuItem;

public class Announce extends ListActivity{
    private CommentsDataSource datasource;
    EditText edit;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.announce);

        datasource = new CommentsDataSource(this);
        datasource.open();

        List<Comment> values = datasource.getAllComments();

        ArrayAdapter<Comment> adapter = new ArrayAdapter<Comment>(this,
                android.R.layout.simple_list_item_1, values);
        setListAdapter(adapter);
        registerForContextMenu(getListView());
    }

    public void onClick(View view) {
        @SuppressWarnings("unchecked")
        ArrayAdapter<Comment> adapter = (ArrayAdapter<Comment>) getListAdapter();
        Comment comment = null;
        switch (view.getId()) {
        case R.id.add:
            edit = (EditText)findViewById(R.id.editTxt);
            Editable txt=(Editable)edit.getText();
            String insert = txt.toString();
            comment = datasource.createComment(insert);
            adapter.add(comment);
            edit.setText("");
            break;
        }
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo){
        super.onCreateContextMenu(menu, v, menuInfo);
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.context_menu, menu);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item){
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
        if(item.getTitle() == "Delete") {
            datasource.deleteCommentById(info.id);
            return true;
        }
        return super.onContextItemSelected(item);
    }

    @Override
    protected void onResume() {
        datasource.open();
        super.onResume();
    }

    @Override
    protected void onPause() {
        datasource.close();
        super.onPause();
    }

}

And here is my SQLHelper, which I am calling for delete.
import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class CommentsDataSource {

    // Database fields
    private SQLiteDatabase database;
    private MySQLiteHelper dbHelper;
    private String[] allColumns = { MySQLiteHelper.COLUMN_ID,
            MySQLiteHelper.COLUMN_COMMENT };

    public CommentsDataSource(Context context) {
        dbHelper = new MySQLiteHelper(context);
    }

    public void open() throws SQLException {
        database = dbHelper.getWritableDatabase();
    }

    public void close() {
        dbHelper.close();
    }

    public Comment createComment(String comment) {
        ContentValues values = new ContentValues();
        values.put(MySQLiteHelper.COLUMN_COMMENT, comment);
        long insertId = database.insert(MySQLiteHelper.TABLE_COMMENTS, null,
                values);
        Cursor cursor = database.query(MySQLiteHelper.TABLE_COMMENTS,
                allColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null,
                null, null, null);
        cursor.moveToFirst();
        Comment newComment = cursorToComment(cursor);
        cursor.close();
        return newComment;
    }

    public void deleteComment(Comment comment) {
        long id = comment.getId();
        System.out.println("Comment deleted with id: " + id);
        database.delete(MySQLiteHelper.TABLE_COMMENTS, MySQLiteHelper.COLUMN_ID
                + " = " + id, null);
    }

    public void deleteCommentById(long id) {
        System.out.println("Comment deleted with id: " + id);
        database.delete(MySQLiteHelper.TABLE_COMMENTS, MySQLiteHelper.COLUMN_ID
                + " = " + id, null);
    }

    public List<Comment> getAllComments() {
        List<Comment> comments = new ArrayList<Comment>();

        Cursor cursor = database.query(MySQLiteHelper.TABLE_COMMENTS,
                allColumns, null, null, null, null, null);

        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            Comment comment = cursorToComment(cursor);
            comments.add(comment);
            cursor.moveToNext();
        }
        // Make sure to close the cursor
        cursor.close();
        return comments;
    }

    private Comment cursorToComment(Cursor cursor) {
        Comment comment = new Comment();
        comment.setId(cursor.getLong(0));
        comment.setComment(cursor.getString(1));
        return comment;
    }
}

What am I doing wrong? It just simply does not delete the item I choose.
Comment: In case my answer doesn't help, have you tried setting breakpoints and debugging this code? If so, how far does it get? Does it hit onContextItemSelected in the Annouce activity? Does it reach the deleteCommentById method?
Answer: Try changing
if(item.getTitle() == "Delete") {

to
if(item.getTitle().equals("Delete")) {

Comment: Tryed nothing happens. It seem thath it doesnt even recognize thath item was clicked..
Comment: Are you saying that the onContextItemSelected method is never called?
Comment: Dont know if its called or not as i am not realy familiar with this debugger in eclipse, But i tryed chaning methoid little bit but nothing happens.
Answer: I think you should call this
 adapter.notifyDataSetChanged();

after this part of code..
  datasource.deleteCommentById(info.id);

Comment: Probably yes, but when i type it shows up as error i try: info.notifyDataSetChanged(); and it shows as fixed add cast to info but this is not helping.

Deleting from database, unsuccessful


Elevation of 3D function

Question: $f(x,y) = \begin{cases} x^2/y & y \neq 0 \\ 0 & y = 0\end{cases}$
I need to draw the elevation (or you may call it Equivalent curve) of this function and I don't know how to draw them. Can some-one help me please?
Thanks a lot.
Comment: http://www.wolframalpha.com/input/?i=plot+(x%5E2%2Fy%2Cy)
Comment: Thanks, but I need to know how to draw only the elevation curves, on a paper and without help from wolframalpha :)
I think "elevation" is not correct word in calculus, do you have another word for that?
Comment: Do you mean the contour map?
Comment: @ozo -yes, I think that this is the word I was looking for. Thanks again. English isn't my native lang'. So, would you like to help me please?
Answer: Set $f(x,y)=k$ for some constant $k$ then $y=\frac{1}{k}x^2$. In other words the contour lines (the lines with constant $f$ values) will consist of a series of quadratic curves emanating from the origin in both the positive-$y$ and negative-$y$ directions.
Begin with $k=\pm1$ and so draw $y=\pm x^2$. And then consider $k=\pm 2$ and you know this is equal to the curves you've already drawn but divided by 2, and so on for increasing $k$. Like this:
Comment: First - thanks. But I didn't understood the last sentence you wrote, and how to draw them.
Comment: @momd I have updated my answer. Is that clearer?
Comment: so everytime I just need to put y=k (const) in the function and then changing (increasing) its value? 'till which number?
Comment: @momd That's right (although I assume you mean $f=k$ (const)). And you keep going until you feel you've done enough to make the structure clear - I wouldn't go beyond $k=\pm 5$.
Comment: OK, i got it. but now, what the lines are actually presenting?
Comment: @momd The value of $f$ is constant along each curve. So along the blue curves $f(x,y)=\pm 1$, along the green curves $f(x,y)=\pm 2$, etc. Therefore, as $k$ increases (i.e. as the consecutive curves approach the $x$ axis) the $z=f(x,y)$ component moves further out of the plane.
Comment: I'm not sure I understood. In simple words - I'm asking - what is the point of this? How it "help" me or what it "gives" me?
Comment: @momd Well why do we use contour maps at all? Answer: It reveals three-dimensional structure in a two-dimensional drawing. http://en.wikipedia.org/wiki/Contour_line

Elevation of 3D function


Why is the semicolon 'unexpected'?

Question:
In the above fiddle, it says the semicolon at the end of the line is unexpected. How so?

alert('foo');

alert('bar');
Comment: Your "semi-colon"  on the first line is actually a greek question mark.  Delete and retype it as a ; and the error will go away.
Comment: Does this answer your question? [Unexpected token ILLEGAL using node javascript](https://stackoverflow.com/questions/36730548/unexpected-token-illegal-using-node-javascript)
Comment: https://i.redd.it/qy7vniac12q01.jpg
Answer: The character you have there is not a semicolon (character code 59), but a "Greek Question Mark", character code 894.

console.log(';'.charCodeAt()); // Greek
console.log(';'.charCodeAt()); // Normal

Use the regular ; semicolon instead.
Answer: The character on the first line is not a semicolon, it's a Greek question mark.
;
Answer: The first character is not actually a semicolon, it's a Greek question mark, U+037E / ; / ; / %CD%BE
Greek question mark: ;
Semicolon: ;
The difference is barely noticeable though.
This works:

alert('foo');

alert('bar');
Comment: No reason to automatically assume this is a troll question.
Comment: Thanks, this code snippet worked

Why is the semicolon 'unexpected'?


Redirecionar paginas usando atributos if, else if e else o que está errado?

Question: meu codigo php
<?php

include "conectar.php";

//comando para iserir dados direto do formul?rio para o banco de dados

$nome=$_POST["nome"];
$cpf=$_POST["cpf"];
$identidade=$_POST["identidade"];
$telefone=$_POST["telefone"];
$celular=$_POST["celular"];
$email=$_POST["email"];
$cep=$_POST["cep"];
$endereco=$_POST["endereco"];
$complemento=$_POST["complemento"];
$bairro=$_POST["bairro"];
$cidade=$_POST["cidade"];
$uf=$_POST["uf"];
$sexo=$_POST["sexo"];
$idade=$_POST["identidade"];
$peso=$_POST["peso"];
$individual=$_POST["individual"];
$tresvidas=$_POST["tresvidas"];
$cincovidas=$_POST["cincovidas"];

$sql="INSERT INTO cadsolidario VALUES ('$nome', '$cpf', '$identidade', '$telefone', '$celular', '$email', '$cep', '$endereco', '$complemento', '$bairro', '$cidade', '$uf', '$sexo', '$idade', '$peso', '$individual', '$tresvidas', '$cincovidas')";
$RES=mysqli_query($con,$sql);
$num=mysqli_affected_rows($con);

if($num = "tresvidas"){
include('busca.php');

}else if($num = "cincovidas"){
    include('index.php');

}else{
     include('consulta-consultas.php');
}

?>

observaçao: esta inserindo os dados corretamente.
Mas não está redirecionando o que devo fazer? Obrigado!
Comment: Para compara valores usa-se dois sinais de iguais `==` e não um (que é atribuição)
Comment: Olá Flavio, faltou o código.
Comment: ok vou auterar e digo se houve mudanças, obrigado! -rray
Comment: Tenho a impressão que sempre vai cair no `else`, `$num` recebe um número mas você compara com uma string...
Comment: Éexatamente o que está acontecendo, devo colocar $res? confesso que fiquei totalmente perdido! Rs.
Comment: @FlavioCordas De onde vem as palavras "tresvidas" e "cincovidas"? Da base de dados?
Comment: Eu não sei o que você está comparando nem o pq, precisa explicar esses detalhes editando a pergunta.
Comment: opa desculpe a demora! eu quero que a partir dos dados digitados no formulario, onde $tresvidas=$_POST['tresvidas']; for escolhido me leve para pagina busca php! Entende?
Comment: `tresvidas` é um radio button ou select?
Answer: O mysqli_affected_rows() devolve o NÚMERO de rows afetadas, no entanto, você está a comparar com uma string.
Notei também que você está a usar = nos seus if. O que tem de errado é que = é usado em comparações em PHP enquanto == é usado para ver se um valor é exatamente igual ao outro.
Comment: Verdade, também tem isto, aproveita e adiciona a resposta o problema que o rray falou https://pt.stackoverflow.com/questions/255954/redirecionar-paginas-usando-atributos-if-else-if-e-else-o-que-est%c3%a1-errado#comment525182_255954
Comment: Boa noite, eu quero selecionar no formulário ou tresvidas ou cincovidas e a partir daí de acordo com a seleção me enviar para as respectivas paginas. Estou realmente precisando dessa ajuda, desculpem a demora!
Comment: Amigos já resolvi!
Comment: if($tresvidas == "tresvidas"){
include('tresvidas.php');

}else if($cincovidas == "cincovidas"){
    include('dependentes.php');

}else{
  include('index.php');
}

mysqli_close($con);


Uninstalling the module from drupal-7

Question: I had installed module Commerce and it was giving me error whenever I try to display product.Then I went through forums to find out solution. And reason mentioned in forum was commerce module might not installed properly due to maximum execution time.So I decide to uninstall commerce module and  I have done. Also removed it from the sites\all\modules. I have cleared all the caches.
But question is that after removing the module, product(which is part of the commerce module) is still showing up in admin navigation bar at top.
I know it is not coding related question but still any help would be appreciated.
Comment: clear the browser caching...
Comment: I have done that.But still same result.**Product** is not working but still is shows up in the admin menu.When I click on that it fires this error : `Notice: Undefined index: sku in views_handler_filter->accept_exposed_input() (line 1273 of C:\wamp\www\drupal-7.31\sites\all\modules\views\handlers\views_handler_filter.inc).`
What might be the issue ?
Answer: Follow these steps. From these steps I think your query may solved.

Clear caching from the drupal.
Clear caching from the database.
Clear browser caching.

& check. If the menu again shows then
Goto
Admin -> Structure -> Menu -> Management -> list links

& check
Clear Caching from the database (local server)
TRUNCATE TABLE cache;
TRUNCATE TABLE cache_advagg_aggregates;
TRUNCATE TABLE cache_advagg_info;
TRUNCATE TABLE cache_block;
TRUNCATE TABLE cache_bootstrap;
TRUNCATE TABLE cache_field;
TRUNCATE TABLE cache_filter;
TRUNCATE TABLE cache_form;
TRUNCATE TABLE cache_image;
TRUNCATE TABLE cache_menu;
TRUNCATE TABLE cache_page;
TRUNCATE TABLE cache_path;
TRUNCATE TABLE cache_update;
TRUNCATE TABLE cache_views;
TRUNCATE TABLE cache_views_data;

Comment: How to clear cache from the database ?
Comment: In your db there are lots of cache table. You can delete the caching data from those tables. Do you know how to delete ? I think you are using local server am I right ?
Comment: Yes there are lots of cache table.So I need to empty all those table ? Or Do I need to do in different way ?
Comment: Check updated answer. Add more truncate query if more tables are there except those in your database.
Comment: Working .. I am little bit slow ..
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/17885/discussion-between-samzha-and-twix).
Comment: Ok .. Truncated all the tables.Do I need to clear my browser cache again ?
Comment: you may try once.
Comment: Ok .Doing..Why am I not able to reply from chat room ?
Comment: got any result ?
Comment: Tried all the things but still no result.With your suggestion I am able to hide but not able to delete it.
Comment: did you check "Admin -> Structure -> Menu -> Management -> list links"
Comment: Yah ..Through that I have hide that. But I want to delete it permanently.
Comment: It is not completely solved.So if no one able to solve than I'll accept it so that other can resolve from this question.Can you tell me how to delete my drupal site completely from the localhost ?
Answer: Visit admin/modules/uninstall, check if its uninstalled.
Check once again DRUPAL_ROOT/sites/all/modules for commerce module, if exist delete the folder.
and still not solved
Clear the cache twice thrice
still not solved
If you have ssh access to your project clear cache via drush
still not solved
Restart mysql and apache2
still not solved
put site in maintenance mode and reboot the live server.
For further help visit How to fix error found in Drupal Commerce after installation
Comment: I am using `local host`. Done all your steps except drush and maintenance mode.But still it is showing :(

Uninstalling the module from drupal-7


Confused about the necessity of multplying the covariance function by a scaling factor in Gaussian Process modeling

Question: I was reviewing examples of implementing GP-based model with PyMC3. I noticed some examples will multiply the covairance function by a factor, which is in turn modeled as a random variable, while others do not.
For examples, in https://docs.pymc.io/notebooks/GP-Latent.html, it adds such scaling factor. The relevant lines are as below
<code>η = pm.HalfCauchy("η", beta=1)
cov = η ** 2 * pm.gp.cov.Matern52(1, ℓ)
gp = pm.gp.Latent(cov_func=cov)
</code>
But in https://docs.pymc.io/notebooks/GP-Marginal.html, it does not add such scaling factor. The relevant lines are as below
<code># Specify the covariance function.
cov_func = pm.gp.cov.ExpQuad(1, ls=0.1)

# Specify the GP.  The default mean function is `Zero`.
gp = pm.gp.Marginal(cov_func=cov_func)
</code>
My questions are

what is the actual difference made by adding such scaling factor. My understanding is it will only change the variance of value of f(x) at each x, but does not change the correlation of f(x) values at different x vallues. Am I right?

when should we try to model this factor and when not?
Answer: This scale factor allows you to translate the default covariance functions (under which $\text{Var}[f(x)]=1$) into the actual covariance function you want to associate to $f(x)$ in your prior. It does not affect the correlation between any $f(x)$ and $f(x')$, although it does affect their covariance (multiplying it by $\eta^2$).
Now, when do you need such a scaling factor? Whenever you don't want a distribution with $\text{Var}[f(x)]=1$. Then, you can use a deterministic scaling factor (just multiplying that covariance function by some float) or you can learn the scale from the data itself (like the first example in your question).
For example, if one were modeling average height of children as a function of time. Would it make sense to have $\text{Var}[f(x)]=1$? It would certainly depend on the units that are being used, and it would make sense to multiply the covariance function by some scale factor in centimeters or inches.
And even if $f(x)$ has no units, you may want it to have a variance greater than 1, or smaller than 1. Scale factors allow you to choose this variance at your own discretion, or even consider put a prior on it, instead of just taking the default value of $1$ for granted.
Hope it was helpful
Comment: Thanks @PedroSebe.  If the y value of the samples has been standarized (i.e. mean=0, stdev=1), is that fair to say this scaling factor is not needed?
Comment: yes, I think it's fair to say so


Octobercms timezone issue

Question: I am trying to set the timezone in OctoberCMS to South African Standard Time (SAST), I have tried editing app.php with time zones CAT, SAST, UTC+2 and UTC+2:00 but none are accepted so I am unsure how to get the system to display the correct time.
<code>/*
  |--------------------------------------------------------------------------
  | Application Timezone
  |--------------------------------------------------------------------------
  |
  | Here you may specify the default timezone for your application, which
  | will be used by the PHP date and date-time functions. We have gone
  | ahead and set this to a sensible default for you out of the box.
  |
 */
'timezone' => 'UCT',
</code>
Answer: I found the answer, simple as it is:
<code>'timezone' => 'Africa/Johannesburg',
</code>
Answer: Just struggled with something similar.  Here was my final setup.
Shared server is running on "MST" as was MySQL by default
Config Files:
app.php
<code>...
'timezone'=>'UTC',
...
</code>
database.php
<code>...
'mysql'=>[
    'timezone'=>'-00:00',
    'driver'=> ...
]
</code>
Backend: user can pick their timezone in their individual preferences.  I chose 'UTC' for checking that everything was time stamping correctly.
Frontend: Need to convert to users TZ for presentation and forms.  Your save process must convert from User TZ to 'UTC'.  You can use JS to get the user TZ from browser and AJAX it to your server for saving a session variable or other method of telling server what TZ the user is using.
<code><script>
tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
window.addEventListener("load", function(){
$.request('onSetTZ', { data: {tz: tz}});
});
</script>
</code>
You can convert TZ in twig but I suggest that you handle all TZ conversions in PHP using Carbon for retrieval, presentation and saving because it will be easier if this is done all at the same layer.

Octobercms timezone issue


How to print a reversed colorbar in matlab?

Question: I want to reverse a colorbar on a figure saved as a pdf from Matlab. I can reverse the colorbar on my screen, but when I print my figure as a pdf the colorbar is flipped back to the normal direction again.
Minimum example:
figure(1)
colormap(parula(100))
c = colorbar('direction','reverse');
print(1,'-dpdf','graphs\test_colorbar.pdf',sprintf('-r%d',150))

Using export_fig does not help - when export_fig prints a reversed colorbar it flips the colormap and reverses the label order, which does not work if the ticks are not symmetric around the middle value of the colorbar.
Minimum example showing why flipping the colorbar and labels does not help:
tick_array = 0:0.3:1;

figure(1)
colormap(parula(100))
colorbar('direction','reverse','Ticks',tick_array)
export_fig('graphs\test_colorbar.pdf','-pdf')

tick_labels = strtrim(cellstr(num2str(flip(tick_array)')));

figure(2)
colormap(flipud(parula(100)))
colorbar('Ticks',tick_array,'Ticklabels',tick_labels)

The figure saved by export_fig looks like figure 2 (which is incorrect).
Answer: Try reversing the map itself, instead of the parameter that control its direction:
figure(1)
c = parula(100);
colormap(flipud(c));
colorbar;
print(1,'-dpdf','graphs\test_colorbar.pdf',sprintf('-r%d',150))

I also really suggest export_fig for saving images in MATLAB, especially for publication quality figures
Comment: @tannoreth the answer is "because `print` sucks", unfortunately. That is the reason `export_fig` is the N1 all time downloaded file for MATLAB. `print` works for basic things, but it is very limited and has tons of errors
Comment: I could reverse the colormap (and also the labels) as a workaround. However, that doesn't explain why printing the figure has the colorbar in the opposite direction as on the screen. Also, that fix only works if the colorbar is the last thing I plot (I think).
Comment: Unfortunately, this fix doesn't work for some of my graphs where the labels aren't symmetric (e.g. if the colormap goes from 0 to 1.2, but the labels only go from 0 to 1). I will check out export-fig.
Comment: Export_fig prints the figure by reversing the colormap and the order of the labels (which does not work with some of my figures).
Comment: @tannoreth if you genuinely found a bug in `export_fig` you should report it in Github. Yari Altmani does generally fix them quite quick.


How exactly the exact symbols (C C# D D# E F F# G G# A A# B) of 12 tone equal temperament with octave (2x) and perfect fifth (3/2) found?

Question: How are the exact symbols (C C# D D# E F F# G G# A A# B) of 12 tone equal temperament with octave (2x) and (3/2) found?
What is the math or formula used to find those specific symbols?
Imagine a tuning that is equal temperament but instead of 12 tones has 3 tones, it still has octave but has 1.618 instead of the usual (3/2), what would be the symbols of this tuning?
Comment: It's not entirely clear what question you're asking here. In fact, there seem to be several questions. Also, dividing an octave into three equal divisions is already catered for by 12-tone-equal-temperament, as 12 is divisible by 3. In fact, this gives the **Augmented Arpeggio**, consisting of three Major 3rds, for instance **C E G#**.
Comment: http://music.stackexchange.com/questions/24086/what-is-the-theory-behind-scales/24093#24093
Comment: Clarify, please. Symbols or pitches? Do you want to know the differences between just and equal temperaments? Where did you get 1.618? That's a sharp minor 6th, in either just or equal temperaments. You can find the differences here: http://www.phy.mtu.edu/~suits/scales.html and the formula here: http://www.phy.mtu.edu/~suits/NoteFreqCalcs.html.
Answer: You already know some of the ratios. An octave is 2:1. A just/pure fifth is 3:2. (A perfect fifth may not have this exact ratio, by the way. More on that later.)
If you divide an octave into twelve equal parts, you need a number that, when multiplied by itself 12 times, equals two. That is . (Read it as "the twelfth root of two.") It's approximately equal to 1.059463094359295.
To determine the frequencies of equal temperament, you need a starting frequency. That is usually defined as A4 = 440 Hz, which is basically arbitrary.
To get A♯/B♭, multiply 440 by the twelfth root of two. To get B, multiply that number by the twelfth root of two.  By the time you've done this 12 times, you'll reach A5, which is 880.
All symbols, including the use of letters for notes (as well as the letters themselves), are ultimately arbitrary; so the symbols of your imagined tuning would be whatever you defined them to be. The symbols used in Western music are not universal. They aren't even consistent within Western music. (What English speakers call "B" is sometimes called "H" or "Si" in other Western countries, for example.) The reason why there are twelve notes is explained here: What is the theory behind scales?
A perfect fifth and a just/pure fifth are not necessarily the same, and, in equal temperament, they never are. The perfect fifth of A is E. Following the ratio of 3:2, you'd expect to find E at 660 Hz. That is a pure fifth. But, in equal temperament, E ≈ 659.25511382574. It's still a perfect fifth—because it's E—but it is no longer pure/just. Other temperaments have perfect fifths which are pure and others which are not, or fifths which are sometimes closer to pure/just than others. In equal temperament, the fifths are all the same distance apart; hence "equal".
Answer: You seem to have several confusions.
First of all, 12-tone equal temperament does not, and cannot have perfect fifths defined as exactly 3/2. It is impossible by definition. In 12TET, all half steps must be the same size, and there must be twelve of them in an octave. This means that whatever factor (x) you multiply a frequency by to raise it a half step must equal exactly 2 when you multiply it 12 times. Or in other words: x12 = 2, which means that x = 21/12.
In 12TET, a perfect fifth is defined as exactly seven of these half steps, so it can be found by multiplying the lower frequency by 27/12 (~1.49830707). You'll note that this is an irrational number, and specifically, is not equal to 3/2 (=1.50).

Secondly, unlike the frequencies, the letter symbols are not exactly found by any kind of formula, much less one based on 12TET (the letters predate the adoption of 12TET). Rather, they are simply the result of western music being based on a seven note scale, and naming those seven notes after the first 7 letters of the alphabet. See: Why are notes named the way they are?
That said, there is a pattern to the letters, if you go by the Line of Fifths (illustrated here), in that the letters always repeat in the same order when you go by fifths (F, C, G, D, A, E, B). Continuing the pater, these seven notes are followed by seven sharp notes with the same letter order (F♯, C♯,...), and those are followed by double-sharps in the same letter order. Working backwards, F is preceded by flats in the same order as well (reversed since we're going backwards, B♭, E♭,...), and these are preceded by double-flats, once again, with the same letter order.

Thirdly, if you come up with some kind of scale of your own (like three equally spaced notes), you really shouldn't redefine what the letters mean (like naively naming them A, B, C, or something). That will cause needless confusion. You should just call them by the nearest actual pitch. As Bob mentioned in a comment, in the case of three equally-spaced notes, they will just be major thirds apart. Exactly which major thirds will depend on which note you start on.
Answer: In Pythagorean tuning, the pitches are generated by compounding perfect (just intonated) fifths, one way to do this is to go symmetrically outward from a central pitch, octave reducing.

C
F-C-G
Bf-F-C-G-D
Ef-Bf-f-C-G-D-A
Af-Ef-Bf-F-C-G-D-A-E
Df-Af-Ef-Bf-F-C-G-D-A-E-B
Gf-Df-Af-Ef-Bf-F-C-G-D-A-E-B-Fs

Note that Gf, Fs generated this way are very close in pitch (enharmonic).  The reason why is happens is a numerical coincidence (3/2)**12 is approximately equal to 2**7, i.e. going out enough fifths (approximately) gets you some number of octaves above your starting pitch. This makes 12 notes a "natural" stopping point in considering the spine of fifths.  Also note that the 5-note pentatonic and 7 note diatonic (B-flat major in this case) scales, appear in the sequence of scales generated in this way.
In many cases one says Gf and Fs are "close enough" to be considered equivalent, one of them is dropped, and you have a 12 note chromatic scale.  Note that one can start at a different starting point (e.g. start on B) and get a 12 note scale where some of the notes are replaced with their enharmonic equivalents.
If you generate 12 tones by extending along (or outwards) the spine of fifths, you can generate 12 notes that might serve as a workable scale (I'm not sure to what extent pure Pythagorean tuning has been used in practice -- this theory is more applicable to 7 note diatonic scales), and the note names associated with those pitches will be in the sensible order.
Although rarely considered, one can continue extending the "line-of-fifths" to gneerate, e.g. G-sharp, or A-flat-flat and so on; it is formally it is infinite.
There is no reason why one couldn't start at a given pitch, and then grow outwards using an alternative "generator",  e.g. the golden ratio as alluded to in the question to generate

C
W-C-X
U-W-C-X-Y

and so on (I just made up symbols for these notes); aside from some numerical coincidences that one could look for, there is no reason to think that the pitches generated in this way will have any particular relationships to the pitches generated via Pythagorean tuning;
this even includes the idea of getting an approximate octave-equivalence that would allow one to close the "circle-of-phi" and thus have a workable number of scale degrees.
The following Python script demonstrates how to generate a table of relative pitches given a single generating interval.

import math

def octave_reduce(f):
    while f > 2:
        f=f/2
    while f < 0.5:
        f=f*2
    return f

p_steps=xrange(12) # generate a 12 note scale

p_basis=3.0/2.0 # pythagorean is generated by compounding just intonated fifthe
p_frequencies=[ octave_reduce( p_basis**p ) for p in p_steps]

p_note_names=['Df', 'Af','Ef','Bf','F','C','G','D','A','E','B','Fs']
# output the Pythagorean scale in of pitch, which is just their scale order
print [x[1] for x in sorted( zip(p_frequencies, p_names))]

# one could make a golden ratio based scale
# in essentially the same way:
g_basis=0.5*(1+math.sqrt(5))
g_frequencies=[ octave_reduce( g_basis**p) for p in p_steps]


Will nicotine gum (e.g., Nicorette) harm my singing voice?

Question: Since about the age of 30 (I'm 35 now) I have sometimes been addicted to smoking tobacco.  I know that smoking tobacco can damage my singing voice--I have experienced this personally.  Lately, I had quit again, but then I moved in with a roommate who smokes a lotta cigarettes, as do his friends--who have become my friends--and I have started smoking cigarettes and/or Black n Milds (cigarillos) again.  I just very recently started chewing nicotine gum (generic version of Nicorette) to lead me to smoking little to none again.
I have searched on Google, and I can't find anyone talking about whether nicotine gum does or does not harm the singing voice.  Anyone have any knowledge on this?
Note: I don't plan on cutting nicotine out of my life entirely, in the immediate future; rather, I want to use nicotine gum to satisfy my cravings, while still enjoying a cigarette or Black n Mild occasionally with my friends who smoke.  This means that I may be chewing nicotine gum for quite some time.
Comment: As a singer, you're an athlete. You will have to keep "in training" all the time. There are no off- seasons for singers (hopefully).
Answer: Yes. Nicotine supplements will damage your voice. As will smoking and being around people who are smoking.
According to The Singer's Voice, by Michael S. Benninger and Thomas Murry (Plural Publishing, 2008) (LINK: Book at Publisher's Website), nicotine supplements should be avoided (p. 94, Table 9.1) and they can cause vocal dryness (p. 95, Table 9.2).
The below images are screenshots from Google Books
Excerpt from The Singer's Voice, p. 94, Table 9.1

Excerpt from The Singer's Voice, p. 95, Table 9.2

In addition, the Mayo Clinic lists the following possible side effects (among others) for Nicorette:

Mouth sores, blisters, or irritation
sore throat
belching
hiccups
mouth, tooth, jaw, or neck pain

all of which could affect singing.
Answer: Yes, Nicorette gum has a damaging effect on the vocal cords. I am a singer, and it has coated my vocal cords, and has affected my singing.
Answer: I was using Nicorette gum for a few years and finally had to quit when I realized it was the cause of my voice going hoarse. It damaged vocal chords and it took me over a month to get my voice back with the help of ginger, lemon and honey tea. Stay away from Nicorette gum.


Condensing ArrayList NullPointer

Question: So I am making a program that takes in polynomial functions and does different things with it.
Right now, I am trying to make a method that checks the Polynomial that is input, which is stored as an ArrayList, and condensing it so everything with the same exponent gets added together.
I keep receiving a NullPointer Exception whenever I run the program, and I am not sure why I am receiving this. I know what the error means, but I have looked through my code and cannot see why the Polynomial is being seen as null.
This is my constructor
public ArrayList<PolyTerm> terms;

public Poly(ArrayList<PolyTerm> terms)
{
    sort(terms);
    condenseExponents();
    this.terms = terms;
}

And in my main class I have my Poly objects created like this:
PolyTerm poly1 = new PolyTerm(4, 3);
PolyTerm poly2 = new PolyTerm(-3, 1);
PolyTerm poly3 = new PolyTerm(15, 3);
PolyTerm poly4 = new PolyTerm(7, 2);

PolyTerm poly5 = new PolyTerm(14, 12);
PolyTerm poly6 = new PolyTerm(2, 0);
PolyTerm poly7 = new PolyTerm(19, 2);

ArrayList<PolyTerm> terms = new ArrayList<>();
    terms.add(poly1);
    terms.add(poly2);
    terms.add(poly3);
    terms.add(poly4);

ArrayList<PolyTerm> terms1 = new ArrayList<>();
    terms1.add(poly5);
    terms1.add(poly6);
    terms1.add(poly7);

Poly test = new Poly(terms);
Poly test2 = new Poly(terms1);

Where the first thing being taken in by the PolyTerm is the coefficient, and the second thing being taken in is the exponent.
So back to the Poly class.
In my constructor, I call condenseExponents() which is meant to condense to ArrayList and combine the coefficients of all similar exponents. Here is that method
private void condenseExponents()
{
    for(int i = 0; i < terms.size() - 1; i++)
    {
        for(int j = i + 1; j < terms.size(); j++)
        {
            if(terms.get(i).getExponent() == terms.get(j).getExponent())
                terms.set(i, new PolyTerm(terms.get(i).getCoef() + terms.get(j).getCoef(), terms.get(i).getExponent()));
                terms.remove(j);
        }
    }
}

The NullPointer Exception keeps being thrown on the first line of the for loop in that method.
Does anybody know why?
Comment: Shouldn't it be `j < terms.size() - 1` instead of `j < terms.size()`?
Comment: @lealceldeiro I don't think so. Since the `nested loop` is `j = i + 1`, when so when `i` gets to the last index, then `j` would try to go to an index that doesn't exist which would be a problem. I may be wrong though
Answer: Assign term before your function call;
public ArrayList<PolyTerm> terms;

public Poly(ArrayList<PolyTerm> terms)
 {
sort(terms);
this.terms = terms;
condenseExponents();
}

Comment: @brent_mb because `sort()` gets the local variable `terms` as an argument, while `condenseExponents()` tries to use the member variable.
Comment: Thank you. This fixed it. I am confused why my `sort` method works before the assignment, but the `condense` method does not.

Condensing ArrayList NullPointer


convergence in law in $\mathbb{R}^d$

Question: In my probability professor's notes there's this lemma given as obvious, but I am not able to prove its truth.

Let $(X_n)_{n \in \mathbb{N}}$ and $X$ be random variables with values in $\mathbb{R}^d$.
Prove that the following to statements are equivalent:

the sequence $(X_n)_{n \in \mathbb{N}}$ converges in law to $X$.
for any $u \in \mathbb{R}^d$ we have that $(\langle u,X_n \rangle)_{n \in \mathbb{N}}$ converges in law to $\langle u,X \rangle$.

I am able to prove the easy direction (i.e. 1. $\implies$ 2.).
Can somebody provide me a proof of 2. $\implies$ 1. ?
Comment: Pick $u = e_i = (0, \dots, 0, 1, 0, \dots, 0)$ (one is at the $i$th position) for $i = 1,\dots, d$
Comment: I thought about it, but I can't see how it helps though. I mean, how can the convergence in law of the components imply the convergence in law of the whole random variable? Just take for example $f(x,y) = max(1,xy)$, I don't see in this case how it can help.
Comment: I don't think this is obvious. This is the famous  Cramér-Wold device; it is usually proven via characteristic functions.
Comment: Oh I see! Thank you very much!
Answer: This is the Cramér-Wold theorem. A proof is given in Billingsley's Probability and Measure (p.383 Theorem 29.4). This is a very standard reference.
The way in Billingsley to prove "2 implies 1" is using the characteristic functions (and the continuity theorem). A key observation is that for any $t\in{\bf R}^d$,
$$
\varphi_X(t)= \varphi_{\langle t,X\rangle}(1)
$$
where $\varphi_X$ denotes the characteristic function of the random vector $X$ and $\varphi_{\langle t,X\rangle}$ is the characteristic function of the random variable $\langle t,X\rangle$.
Comment: @CalvinKhor: I believe convergence in law for each component is not sufficient. Consider for instance $X\sim N(0,1)$. Note that $X$ is symmetric. One can find an example that $X_n\Rightarrow X$ *and* $X_n\Rightarrow -X$ but $X_n+X_n\not\Rightarrow X+(-X)$. So by the theorem above, one cannot have $(X_n, X_n)\Rightarrow (X, -X)$.
Comment: Is the result is false if we just assume $\langle e_i, X_n\rangle$ converges in law, $e_i$ being the standard basis vectors?

convergence in law in $\mathbb{R}^d$


Acknowledge of RegExp

Question: I need to validate url, so I used site http://www.rubular.com/ and maybe I get wrong result.  So I wrote this: w{3}\.[a-z]+\.[a-z]{3} in http://www.rubular.com/ and it gived me almost wanted result. In my model Website I wrote:
 VALID_URL_REGEX = /w{3}\.[a-z]+\.[a-z]{3}/
 validates :url, :presence => true, format: { with: VALID_URL_REGEX }

Question : how I can make to check, that last part should contain only 3 letters ?
Comment: It's wrong to check that the last part has only three letters. For instance, both `.eu` and `.info` are valid TLDs.
Comment: When I'm doing VALID_URL_REGEX =(here code from  [link](http://stackoverflow.com/a/1141962/79835) but I get error
A regular expression or a proc or lambda must be supplied as :with.
So how I should change this : validates :url, :presence => true, format: { with: VALID_URL_REGEX } ?
Comment: Why should the last part only contain 3 letters? This answer should give you a 'correct' regex. http://stackoverflow.com/a/1141962/79835
Comment: Your regex has several problems. As others have said it only accepts 3 char tld. it doesn't take into account subdomains other than www, and fails to account for domains like wwww.history.uk.com, it also does not account for other chars which a domin name can have (e.g. - _). You would be better getting an existing regex that has been well tested.
Answer: You have to use \A and \z to match against start and end of string.
Like this: /\Aw{3}\.[a-z]+\.[a-z]{3}\z/.
But like Mahmoud Al-Qudsi said, tlds can have more or less than 3 letters.
And you should make it match multiple subdomains or naked domains (e.g. stackoverflow.com instead of www.stackoverflow.com).
I came up with this /\A(?:[\w-]+(?<!-)\.){1,}[\w]{2,}\z/.
Comment: Thank u for help!
When I'm doing VALID_URL_REGEX =(here code from  [link](http://stackoverflow.com/a/1141962/79835) but I get error
A regular expression or a proc or lambda must be supplied as :with.
So how I should change this : validates :url, :presence => true, format: { with: VALID_URL_REGEX } ?
Comment: It's to long for comment, I did it like this:
in my application made VALID_URL_REGEX = (the same text as in $search)

Acknowledge of RegExp


Offside on purpose

Question: I'm interested in the community's thoughts on recent events.  Since it is about officiating and offside, I know there's much room for interpretation.
I viewed a match at the U14 level where team A left 2 players in an extreme offside position for almost the entirety of the first half.  Basically, the two remained at the corners of the 18 throughout without engaging play from teammates.  I can't decide if this is unsportsmanlike to the extent it doesn't appear to be in the spirit of the game or if it represents a clever interpretation of the rules.
It may be noted that team A was the far superior side on the day. The two players did not engage the ball in any attacking play where their own team controlled events and never accepted a played a ball from a team-mate.  They remained statues. A couple of offside calls went against them from careening balls through.
Here's the kicker; it put the keeper off his game completely and he focused on these two intently. The coach was equally frustrated. A goal was indeed awarded when a defender forgot about the statues and offered an intentional pass back to his keeper and it was intercepted by the attacker.
So, how would you interpret Law 11 in this instance?
Comment: BTW, this question is clearly about the legality of this tactic, and how the official should have handled it. It's completely on-topic and answerable in its current form.
Comment: Perhaps you're correct on the off-topic and allow me to politely apologize if so; but the question I hoped was inherent is what if any ruling should the referee make in such events? Thanks for your reply.
Comment: No need to apologize because it was my opinion. I think it would be better if you could edit your question so that it could be more related with the rules even though I believe there is no rule other than the one related with off-side.
Comment: Seems like he's asking if it's legal, which would be an okay question.  Is it nice, not okay, but legal, okay.
Comment: It is only possible at U14 level and it was actually a very stupid play. Whoever coached the team was a fool and doesn't know a thing about football. BTW, what's the point of asking this question here? If you are seeking opinions of others, your question is off-topic.
Comment: Thanks for the feedback.  It was frustrating to watch a new coach and an inexperienced team fall victim to an experiment, but I did want to understand if it was indeed legit and even if so, would the ref have the authority to force a more natural match.  I have coached for years and have never witnessed anything quite like this.
Comment: "Since it is about officiating and offside, I know there's much room for interpretation." - in fact, there is little room for interpretation. The problem is that IFAB have changed the interpretation so often in the past 15 years that has led to this conclusion. Law 11 in its current form is crystal clear.
Answer: This is nothing more than a poor tactic. Neither of these players can really do anything of significance until the ball has been deliberately played (other than a deliberate save) by an opponent or goes out of play. Until this happens, they're effectively leaving their team short by two players.
IFAB Laws of the Game, 121.2 Offside Offence:

A player in an offside position at the moment the ball is played or touched by a team-mate is only penalised on becoming involved in active play by:

interfering with play by playing or touching a ball passed or touched by a team-mate or
interfering with an opponent by:

preventing an opponent from playing or being able to play the ball by clearly obstructing the opponent's line of vision or
challenging an opponent for the ball or
clearly attempting to play a ball which is close to him when this action impacts on an opponent or
making an obvious action which clearly impacts on the ability of an opponent to play the ball

or

gaining an advantage by playing the ball or interfering with an opponent when it has:

rebounded or been deflected off the goalpost, crossbar or an opponent
  been deliberately saved by any opponent

A player in an offside position receiving the ball from an opponent who deliberately plays the ball (except from a deliberate save by any opponent) is not considered to have gained an advantage.

Law 11 makes no distinction between intentionally and unintentionally placing oneself in an offside position:
IFAB Laws of the Game, 11.1 Offside Position:

It is not an offence to be in an offside position.
A player is in an offside position if:

any part of the head, body or feet is in the opponents' half (excluding the halfway line) and
any part of the head, body or feet is nearer to the opponents' goal line than both the ball and the second-last opponent

The hands and arms of all players, including the goalkeepers, are not considered.
A player is not in an offside position if level with the:

second-last opponent or
last two opponents

It is worth mentioning that Law 12 mentions that a player may be cautioned for persistent infringement.
IFAB Laws of the Game, 12.3 Disciplinary Action:

A player is cautioned if guilty of:
...

persistent infringement of the Laws of the Game (no specific number or pattern of infringements constitutes "persistent")

However, it is a general understanding amongst referees (think of it as common law) that players should not be cautioned for persistent infringement when the infringement only harms their team eg. taking a free kick to oneself, incorrectly taking a throw-in, offside. This forum thread on RefChat highlights this:

Are there any circumstances when you might caution a player for being persistently penalised for being in an offside position?
...
No it's a technical offence, a bit like persistently taking a throw-in incorrectly, which you wouldn't caution for either
Another way of thinking of it, is that he is only penalising his own team
...
Actually I don't see how the striker is doing anything wrong beside being offside
If you consider that he's interfering while being offside, than give the offside
If he does it again, do it again
If he does it again, do it again
Who is he harming beside his own team in this scenario ?

This is contrast to offences which actively harm the opponents' ability to play should and hence should come under the guise of persistent infringement. Examples of this include repeatedly fouling opponents, encroaching at a penalty kick forcing a retake multiple times, consistently holding opponents at a corner kick before the ball is in play.

Offside on purpose


Combinatorial proof of $\binom{n}{k} = \binom{n}{n-k}$

Question: How do I prove this combinatorially?

$$\displaystyle \binom{n}{k} = \binom{n}{n-k}$$
Answer: Picking the $k$ elements you want out of $n$ possibilities amounts to the same thing as picking the $n-k$ elements you don't want out of $n$ possibilities.
Answer: If $X$ is a set, we denote its cardinality with $\# X$ . If $A$ is a set with $\# A = n$ and $0 \leq k \leq n$, then there exists a bijective mapping between the two following sets:
$$
U = \{ X \subseteq A \mid \ \#X = k \},
$$
$$
V = \{ Y \subseteq A \mid \ \#Y = n-k \};
$$
the map is $X \mapsto A \setminus X$.
Answer: $$
\binom 62 =15 = \binom 64.
$$
The number of ways to choose 2 out of 6 equals the number of ways to choose 4 out of 6, since every way of choosing 2 out of 6 corresponds to a way of choosing 4 out of 6, namely the 4 that are not among the chosen 2:
$$
\begin{array}{rcl}
AB & \leftrightarrow & CDEF \\
AC & \leftrightarrow & BDEF \\
AD & \leftrightarrow & BCEF \\
AE & \leftrightarrow & BCDF \\
AF & \leftrightarrow & BCDE \\
BC & \leftrightarrow & ADEF \\
BD & \leftrightarrow & ACEF \\
BE & \leftrightarrow & ACDF \\
BF & \leftrightarrow & ACDE \\
CD & \leftrightarrow & ABEF \\
CE & \leftrightarrow & ABDF \\
CF & \leftrightarrow & ABDE \\
DE & \leftrightarrow & ABCD \\
DF & \leftrightarrow & ABCE \\
EF & \leftrightarrow & ABCD
\end{array}
$$
(And simlilarly with other numbers.)


Show complex number in polar coordinates and in polar form

Question: I'm a but stuck with this problem

Represent in polar form and graph in the complex plane as in Fig. 325. Do these problems very carefully

$$\frac{\sqrt{2} + \frac{i}{3}}{-\sqrt{8} - \frac{2i}{3}}$$
$$= \frac{\sqrt{2} + \frac{i}{3}}{(2*-\sqrt{2}) - \frac{2i}{3}}$$
$$= \frac{\sqrt{2} + \frac{i}{3}}{-2(\sqrt{2} + \frac{i}{3})}$$
$$= \frac{-1}{2}$$
Where do I go from here?
Comment: But I don't understand the question!, could you make it more clear
Answer: We have $$-\frac{1}{2}=-\frac{1}{2}+i\cdot0=\frac{1}{2}e^{i(\pi+2n\pi)}$$ for $n\in\mathbb Z$, so take $n=0$ and we get $-\frac{1}{2}=\frac{1}{2}e^{i\pi}$