Why are nonsquare matrices not invertible?

Question: I have a theoretical question. Why are non-square matrices not invertible?
I am running into a lot of doubts like this in my introductory study of linear algebra.
Comment: A good question, but do you have any thoughts on this?
Comment: I'm thinking that it's because of improper linear transformation? The elements don't get mapped properly from an mxn matrix to an nxm matrix
Comment: See my answer. But following with your line of thinking...keep in mind multiplying a function by its inverse must result in the identity matrix. An identity matrix must be square.
Answer: I think the simplest way to look at it is considering the dimensions of the Matrices $A$ and $A^{-1 }$ and apply simple multiplication.
So assume, wlog $A$ is $m \times n $, with $n\neq m$ then $A^{-1 }$ has to be $n\times m$ because thats the only way $AA^{-1 }=I_m$
But it must also be true that $A^{-1 } A=I_m$ but now instead of $I_m$ you get $I_n$ wich is not in accordance with the definition of an Inverse ( see ZettaSuro)
Hence $m$ must be equal to $n$
Comment: Wow. Just wow..
Comment: @sigmatau $I_m$ and $I_n$ are both shortened in my book to $I$, the identity matrix. "but now you get $I_n$ which is not in accordance with the definition of an Inverse" what is this definition ? But i guess when the book shortens $I$ for identity matrix, they must have in mind a specific size, either $I_m$ or $I_n$, otherwise $I$ is not well defined.
Answer: Simple answer: because by definition a matrix is commutative with its inverse on multiplication. That is: $A^{-1}$ is a matrix such that $AA^{-1}=I_n$ and $A^{-1}A=I_n$.
For two matrices to commute on multiplication, both must be square.
More complicated answer: There exists a left inverse and a right inverse that is defined for all matrices including non-square matrices. For a matrix of dimension $m\times{n}$, the left and right inverse are defined as follows:
$$A^L:=\{B|BA=I_n\}$$
$$A^R:=\{B|AB=I_m\}$$
If $A^L=A^R$ , by definition $A^L=A^R=A^{-1}$.
Comment: Your $A^L$ and $A^R$ are affine sets. And they are possibly empty. Are they really called the "left inverse" and the "right inverse" And not rather the set of left and right inverses? And does it really answer this question? Also, in your first paragraph, your notation is not correct. You have a matrix on the left. A set on the right.
Comment: @julien Yes, it is worth noting that for any given matrix there is a set of left and right inverses. But I made sure to say **a** left and right inverse rather than **the** left and right inverse.
Comment: @julien What would be the notation for "B such that ...." without building a set?
Comment: Sometimes, a good old sentence in English is much better than symbols, you know. And that's group theory anyway. We say that $A$ is invertible if there exists $B$ such that bla. If it exists, such a $B$ is unique and is denoted by $A^{-1}$.
Comment: @julien True. It's always so tempting to try and write every single thing out with predicate logic and set notation, sometimes I forget we have plain English.
Comment: Making this community wiki because, while the ideas are all there, it could be improved with some better formulating and further elaboration.
Comment: "By definition a matrix is commutative with its inverse on multiplication" could be interpreted to mean that a non-square n-dimensional vector is therefore not a matrix at all, but some other kind of object.
Comment: Actually the definition of an inverse matrix does not stipulate the dimension of $I$.
My book says the inverse of a matrix $A$ is defined to be the matrix $B$ such that $AB=BA=I$. But it follows logically, since two non square matrices cannot commute, and an inverse matrix commutes with the original matrix.
Answer: Since this question has just been bumped anyway and I feel like I have something else to add, here are my thoughts:
As pointed out by sigmatau we would have $AA^{-1} = I_m$ and $A^{-1}A = I_n$ and he reasons, that we would have $m=n$ then. I think this is an "unnatural" conclusion: Consider the definition of an inverse of a function $f : A\to B$: It is a function $f^{-1} : B\to A$ with $f^{-1}\circ f = id_A$ and $f\circ f^{-1} = id_B$ and we don't require $id_A = id_B$.
So we can and should ask the question, whether there may be an $A^{-1}$ with $AA^{-1} = I_m$ and $A^{-1}A = I_n$, if $n\neq m$. The answer is no:
The matrix $A$ corresponds to a linear map $f : \mathbb{R}^n \to \mathbb{R}^m, x\mapsto Ax$. By the dimension formula we have:
$n = \dim(\ker f) + \dim(\operatorname{im} f)$.
If $A$ has an inverse, then so does $f$ ($y \mapsto A^{-1}y$). Hence $f$ is injective, so $\dim(\ker f) = 0$ and $f$ is surjective, so $\dim(\operatorname{im} f) = m$. But then $n = 0 + m = m$.
Comment: In fact, just use the that $f$ is an isomorphism. Then $m = n$.
Comment: Your comments on the inverse of a function notwithstanding (since the domain and codomain of a function are not necessarily identical), sigmatau's argument does work. Note that the inverse of a matrix $A$ is defined to be a matrix $B$ such that $AB = BA = I$. If $A$ is a non square $m\times n$ matrix , then you reach the conclusion after left and right multiplication with $B$ that $I= I_m $ and $I = I_n$ (also note that $B$ is forced to be an $n \times m $ matrix , otherwise $AB \neq BA $). Thus $I_m = I_n$, which is absurd since $m \neq n $.
Comment: Even more to the point since the inverse $B$ of a matrix $A$ is defined to be commutative, viz., $AB = BA$, this can only occur if $A$ and $B$ are square. So per the definition of inverse, since two non square matrices can't be commutative, a nonsquare matrix cannot be invertible.
Answer: If $A$ and $B$ are $m\times n$ and $n\times k$ matrices respectively, then the rank of $AB$ is less than or equal to both ranks of $A$ and $B$. So, suppose that $A$ is an $m\times n$ invertible matrix, with $m\neq n$. If its inverse is $B$, then $B$ has to be an $n\times m$ matrix, and $AB=I_m$, $BA=I_n$. So, if $n<m$, then the rank of $AB=I_m$ should be $m$, but also less than or equal to the rank of $A$, which is less than or equal to $n$, which is a contradiction. You work similarly in the case $m<n$.
Comment: This argument can be used to prove a more general statement: If a matrix $A$ has right inverse $B$ and left inverse $C$, then $A$ is a square matrix. After that, it can be proved that in such case $B=C$.
Answer: Maybe I am bumping this but I want to add an example for clarity. Other answers state basically that for a matrix to be invertible, their multiplication should be commutative by definition: $\mathbf{A A^{-1} = A^{-1} A}$ and should be equal to identity matrix. This can only be possible with square matrices. But, this proof could be augmented with geometric intuition I guess.
Here is an example that shows how non-square matrices harm the invertibility of a linear transformation.
$$\begin{pmatrix}
     a & b & -a &  & -b \\
     a & b & -a &  & -b \\
     a & b & -a &  & -b
\end{pmatrix}$$
You can see that this matrix maps from $R^4$ to $R^3$. But as all linear transformations, it maps the zero vector to zero vector. Also see that it maps $(1, 1, 1, 1)$ to zero vector as well. Then, how the inverse transformation should map $(0, 0 ,0)$? Notice that inverse transformation is from $R^3$ to $R^4$. How can we decide whether to map $(0,0,0)$ to $(0,0,0,0)$ or to $(1, 1, 1, 1)$ or to $(2, 2, 2, 2)$ etc. As you can see, this is just a counterexample but I think, someone should prove that non-square matrices can not have inverses because they can not uniquely map. I think proof has got to do with linear dependence and independence.
Here is my more detailed sketch:
Assume an $nxn$ linear transformation $\mathcal{\bar L}$ like
\begin{pmatrix}
     a_{11} & a_{12} & \cdots & a_{1n} \\
     a_{21} & a_{22} & \cdots & a_{2n} \\
     a_{31} & a_{32} & \cdots & a_{3n} \\ \\
     a_{n1} & a_{n2} & \cdots & a_{nn} \\
\end{pmatrix}
Now take two arbitrary vectors from $R^n$, say; $x=(x_1, x_2 \cdots , x_n)$ and $u=(u_1, u_2 \cdots , u_n)$. We are going to take a look at the transformation $\mathcal{\bar L} x = u$. After this step, we will manipulate this transformation to get to linearly independent vectors. This part is long and hard to type so I will just give an example for $3x3$ case. I hope you will be able to see how this generalizes.
Here we have a $3x3$ linear transformation $\mathcal{\bar L_3}$ that maps an arbitrary vector $(x, y, z)$ to another vector $(u, v, w)$. Assuming that $\mathcal{\bar L_3}$ is given by:
$$\begin{pmatrix}
     a & b & c \\
     e & f & g \\
     k & l & m
\end{pmatrix}$$
Then we have the following system of equations:
$$ax + by + cz = u$$
$$ex + fy + gz = v$$
$$kx + ly + mz = w$$
which can be written as
$$ax + by + cz - u = 0$$
$$ex + fy + gz - v = 0$$
$$kx + ly + mz - w = 0$$
which can be written as
$$(a - \frac{u}{3x})x + (b - \frac{u}{3y})y + (c - \frac{u}{3z})z = 0$$
$$(e - \frac{v}{3x})x + (f - \frac{v}{3y})y + (g - \frac{v}{3z})z = 0$$
$$(k - \frac{w}{3x})x + (l - \frac{w}{3y})y + (m - \frac{w}{3z})z = 0$$
We started with our transformation that maps $(x, y, z)$ to $(u, v, w)$ and got ourselves three vectors that are orthogonal to $(x, y, z)$. There can not be four different vectors that are orthogonal to each other in $R^3$. So two of those four vectors must be equal. If you try to set two of them to be equal, you'll see that $(x, y, z)$ is not arbitrary anymore but is determined by your initial transformation and $(u, v, w)$. Since it is uniquely determined, square matrices, as we saw, can have inverses. If you do this, you'll see that there are cases ending up with division by 0. I believe these correspond to case of determinant being 0 but I am not sure and I haven't checked.
You need to generalize this to higher dimensions. Also you need to also show that for non-square matrices, this problem of linearly independent vectors does not arise and we get a linear transformation that maps many vectors to one vector etc. to complete the argument.
I don't count this as a proof because I still think there is something fishy about my argument but it could serve as a way to generate your own counterexamples if you want to convince yourselves.
Comment: Thanks for sharing. Post provided a refreshing perspective on the question.
Answer: Consider the equation AX = B, dimensions for A - m*n, X - n*1 and B - m*1. B can be any vector in space Rm. For AX to always have a solution, A should contain column vectors that make up the complete Rm space (there are n such vectors of m dimensions).
For m > n, We cannot span a complete 3 dimensional space with just 2 vectors of size 3*1.
For m < n, It means we have more variables than the equations itself, it is not possible to find a solution in this case
For m = n, things fall in place perfectly for AX to always have a solution (given column vectors are independent)
Now why inverse of a matrix has anything to do with AX = B, when AX=B always has solution and column vectors in A span the complete Space, X can be presented as X = $A^{-1 }$B. Inverse only comes into discussion when prior conditions are met, and this can only happen when m=n and column vectors of A are independent. Conversely, when taken transpose on both sides the solution has to still hold in that case the row vectors also has to be independent.
Note: For Singular matrices, since the column vectors are dependent, AX=B doesnt have solution for every B. The system becomes inconsistent and X cannot be represented with $A^{-1 }$
Comment: Please use mathjax in your answer https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference


Resultado inesperado em código de teste Lua

Question: Escrevi um pequeno código pra testar uma afirmação do livro através do qual estou estudando, Programming in Lua (3ª Edição).
A afirmação, que se encontra na página 10 do livro, traduzida é a seguinte: Testes condicionais (por exemplo, condições em estruturas de controle) consideram tanto o valor booleano false e nil como false e tudo mais como true.
function test (a)
    if a then print(type(a).." '"..tostring(a).."'".." corresponde a verdadeiro")
    else print(type(a).." '"..tostring(a).."'".." corresponde a falso") end
end

print("Teste 1: ")
test(true)

print("\nTeste 2: ")
test(0)

print("\nTeste 3: ")
test("")

print("\nTeste 4: ")
test("a")

print("\nTeste 5: ")
test(test)

print("\nTeste 6: ")
test(test("masuia"))

print("\nTeste 7: ")
test(false)

print("\nTeste 8: ")
test(nil)

print("\nTeste 9: ")
test(a) -- variável 'a' não foi inicializada, então corresponde a nil

Quando fui rodar o código, recebi o seguinte resultado no console:
Teste 1:
boolean 'true' corresponde a verdadeiro

Teste 2:
number '0' corresponde a verdadeiro

Teste 3:
string '' corresponde a verdadeiro

Teste 4:
string 'a' corresponde a verdadeiro

Teste 5:
function 'function: 000000000026F2A0' corresponde a verdadeiro

Teste 6:
string 'masuia' corresponde a verdadeiro
nil 'nil' corresponde a falso

Teste 7:
boolean 'false' corresponde a falso

Teste 8:
nil 'nil' corresponde a falso

Teste 9:
nil 'nil' corresponde a falso

Por que ocorre o resultado do "Teste 6"? Segundo a afirmação do livro o teste não era pra ter resultado em falso, já que o parâmetro passado não foi o valor booleano false nem nil? Além disso, de onde saiu essa segunda linha do resultado?
Answer: É totalmente consistente. Você percebeu que este passo 6 faz dois testes?
Primeiro ele executa test("masuia") e por isto a primeira linha é impressa. Até aí você deve estar achando tudo certo.
Depois ele executa novamente o teste chamando o resultado da função test("masuia"). Qual é este resultado, ou seja, qual é o valor retornado? Nenhum, ou seja, nil. Então a segunda chamada no fundo está executando test(nil), e o resultado está certo. Olhando de outra forma aquela expressão poderia ser vista desta forma, só para você entender melhor:
temp = test("masuia") -- vai resultar em nil já que a função sem retorna tem valor nil
print(tmp) -- só para você ver o resultado intermediário.
test(tmp)

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Não sei se você já aprendeu como funcionam expressões, de como funciona a chamada e retorno de funções.
Agora você deve estar se perguntando qual a diferença entre a chamada da função test() dentro da própria chamada da função test() e do exemplo 5 onde ele chama test(test). O primeiro tem uma sintaxe de chamada, ou seja, a função test é executada naquele momento. Os parênteses dizem isto. No segundo caso você está apenas passando o valor contido no identificador test, que por acaso é uma função. Então ele funciona como uma variável e não faz a chamada da função. Podemos dizer que ele está "passando a função" como argumento, que é bem diferente de executar a função e passar seu resultado como argumento, como é o caso do exemplo 6.
Ele não passa todo o código, mas sim algo que indica onde está o código (não vou entrar em detalhes, é cedo para você aprender sobre isto). Este indicador é aquele número esquisito que aparece no teste 5, que é um endereço de memória.
Comment: Eu já tenho um certo entendimento de funções e expressões (assim como ponteiros) graças aos meus estudos de outras linguagens, mas não sabia que as funções Lua retornavam nil quando não fosse especificado retorno. Ótima resposta e muito bem explicada!
Comment: Muitas linguagens fazem isto, especialmente as dinâmicas, onde você precisa ter valor para tudo para dar mais flexibilidade.


How to submit a form with javascript?

Question: I have an exposed views form, am geolocating in javascript and setting the co-ordinates in the exposed form.
This form submits properly when I click on the 'apply' button but does not when I use javascript to submit the form. The page refreshes, but the values have not been changed.
The form is standard FAPI. It is not a views-ajax form although I would like to move to ajax at some point in the future when I sort out the problems with gmaps + ajax.
Both of the following fail.
jQuery('#edit-submit-studio-locations').click();
jQuery('#views-exposed-form-studio-locations-page').submit();

The full code is in github.
Answer: Add this code inside Drupal.behaviors.
$('.views-exposed-form APPLY_BUTTON ID/class').click(function() {
  // Submit the form
  (this).parents('form').submit();
});

Hope it works.
Answer: The following would do the job:
jQuery('#edit-submit-studio-locations').mousedown();

Answer: You can submit form using jquery or add some trigger action
here is example code :
Drupal.behaviors.form_submit_processor = {
  attach: function (context, settings) {
    $("form#your-form").submit(function(e) {
     // some code here
    });
  }
}

Comment: Is there a way I can get this to fire when only a certain form is submitting. As this js runs for all form submissions true?
Answer: Apologies, the problem was that the geocoding was being done asynchronously. Both of these submission methods work.
The solution is to trigger an event in the geocoding closure and react to this event.
I thought FAPI was somehow validating my submission.
geocoder.geocode({'address': address_string}, function (results, status) {
  $(window).trigger('yhive_geocoded');
});

$(window).on('yhive_geocoded', function() {
      $('#views-exposed-form-studio-locations-page').submit();
});

How to submit a form with javascript?


Primes of the form $x^2 + ny^2$: necessary and sufficient condition not in terms of a "modulo equation"?

Question: For particular cases ($n=1,2,3$) we can find an "elementary" necessary and sufficient condition, i.e.
$$p = x^2 + y^2 \Leftrightarrow p \equiv 1 \mod 4$$
$$p = x^2 + 2y^2 \Leftrightarrow p \equiv 1,3 \mod 8$$
$$p = x^2 + 3y^2 \Leftrightarrow p =3 \textrm{ or  } p \equiv 1 \mod 3$$
However, the general case, as proven in David Cox's book, gives a polynomial expression:

How can I argue that it is impossible to find a more "elementary" modulo expression?
Comment: @fretty: Dear fretty, I'm not sure that your comment is addressing the question, but perhaps I've misunderstood your point.  It is certainly true that in general there is no congruence condition on $p$ (modulo $4n$ or any other modulus) which determines whether it can be written in the form $x^2 + n y^2$.    Regards,
Comment: Oh sorry I misunderstood the question...comment deleted
Answer: This is not easy to prove; it relies on class field theory.
This MO question and its answers give an explanation.  The point is that (for all but finitely many $p$), we can write $p = x^2 + n y^2$ iff $p$ splits in the Hilbert Class Field of $\mathbb Q(\sqrt{-n})$,
and so we get a congruence condition iff the HCF is abelian over $\mathbb Q$.
This fails e.g. for $n = 23$.  (In this case the polynomials $f_{23}(x)$ can be taken to be $x^3 - x - 1$, and the HCF of $\mathbb Q(\sqrt{-23})$ is the $S_3$ extension of $\mathbb Q$ obtained as the splitting field of this polynomial.)
In this case, one has the following statement: we can write an odd prime $p$,
different from $23$, in the form $x^2 + 23 y^2$ iff the coefficient of
$q^p$ in $q \prod_{n=1}^{\infty}(1-q^n)(q-q^{23 n})$ equals $2$. (It is always either $-1,0,$ or $2$.)
Answer: Got me. I think you can prove impossibility by clever use of Chebotarev density, especially Theorem 9.12 on page 188. The density of primes represented by a (positive) form is some $1/k.$ If these were collected in an arithmetic progression, except for a few that divide the discriminant, the progression would need to be $k n + b.$ And I think you can rule that out, at least by experimenting with any specific example; i encourage you to experiment with this, in the examples below.
Let me give you some examples to chew on.
For odd primes $p \equiv 1 \pmod 3,$ there is an expression in integers $p = u^2 + 27 v^2 $ if and only if $2$ is a cube $\pmod p.$ The others are represented by $4 u^2 \pm 2 u v + 7 v^2.$
For odd primes other than $3$ itself with $p \equiv 1 \pmod 3,$ there is an expression in integers $p = u^2 + u v + 61 v^2 $ if and only if $3$ is a cube $\pmod p.$ The others are represented by $7 u^2 \pm  3 u v + 9 v^2.$
For odd primes other than $23$ with $(p | 23) = 1$ there is an expression in integers $p = u^2 + 23 v^2 $ if and only there are three distinct roots to $ x^3 - x + 1 \equiv 0 \pmod p.$  The others are represented by $3 u^2 \pm  2 u v + 8 v^2.$
For odd primes other than $31$ with $(p | 31) = 1$ there is an expression in integers $p = u^2 + 31 v^2 $ if and only there are three distinct roots to $ x^3 + x + 1 \equiv 0 \pmod p.$  The others are represented by $5 u^2 \pm  4 u v + 7 v^2.$


Matrix transpose, how do I see this?

Question: I am unable to see this identity.
Let a in $R^n$, $B$ in $R^{n,n}$, c in $R^n$
$c^TBa + a^TBc = a^T(B^T+B)c$.
How do I see this?
Comment: Do you know $a^TBc=c^TB^Ta$ ?
Answer: Since $a^TBc$ is a $1\times1$ matrix, it's equal to its own transpose. But$$(a^TBc)^T=c^TB^Ta.$$Can you take it from here?
Comment: I see, so because it is a scalar, then you can basically take a transpose.
Comment: No. As I wrote, it's because it's a $1\times1$ matrix.
Answer: $(c^tBa)^t = a^tB^tc$ and so $c^tBa + a^tBc = a^tB^tc+a^tBc = a^t(B^t+B)c$, since the matrix product $c^tBa$ is only a value and so taking the transpose doesn't matter.
Comment: I c, I fail to see the step that $c^tBa$

Matrix transpose, how do I see this?


Is it possible to sequentially chain Google DataPrep flows?

Question: I have quite a long set of transforms, which I'd like to break into modules (each in it's own flow). I can't see a way of chaining these, other than scheduling consecutive timeslots. Has anyone managed this, or do I need to build one massive flow?
Answer: In your flow page, click on the three dots ... near your recipe. In the menu, you have Create Reference Dataset. Once created, you will see a new logo under your recipe, you can then click on the menu and choose Add to flow


why does the overlaying content in the admin mode not show up anymore?

Question: Okay, my Drupal admin interface used to work just fine until I introduced some jQuery and CSS changes this morning for the mobile adaptive interface. Now, When I'm in admin mode and for example click on the drop down to Configure block on my page, the page grays out but the white overlay interface to change the contents never shows up. I tried with Chrome, Chromium & Firefox which all yield the same result. The URL of my site is http://www.quaaoutlodge.com/ and if you resize the width <900px you'll see the little nav button poppintg up on to left - that's what I have changed... what did I mess up?
Comment: Users should not need to see your site to answer the question, which also means they should not need to look at the source of the page to see which JavaScript is used, and which CSS styles are used to tell you what is wrong. Take off the site URL, and the question gets too broad.
Answer: Sounds like there is a JavaScript error in your nmost recent changes which is stalling some other scripts.
To get your admin interface back temporarily disable the Overlay module (core).
http://www.quaaoutlodge.com/admin/modules
Then use the browsers developer console to find out where the JavaScript error is. If you've used the jQuery Update module you might need to set a different version of jquery for the Admin pages which is in the config page too.
http://quaaoutlodge.com/admin/config/development/performance
Comment: Hi, Thanks, disabling the overaly module fixed things for me actually, I don't see any advantage in the overlay module anyways...  I don't know what the "jQuery Update module" is nor have I used it. I don't see how I can set a different jQuery version on the link you pasted. But it might very well be that i've ran in some kind of version conflict... Thanks for your help!
Comment: jQuery Update updates Drupal's version of jQuery to a newer version. Unfortunately this sometimes causes a conflict on admin pages that are expecting older versions. So jQuery Update provides a mechanism for using different versions on the backend. https://www.drupal.org/project/jquery_update


Redirect standard error to a variable in PowerShell

Question: I would like to script a dcdiag test to alert me if it finds any errors. I thought I may able to do this in PowerShell by...
$test = dcdiag 2>$err

I don't have any errors from dcdiag at the moment, so I couldn't test that directly, but I wrote another PowerShell script to throw an exception, hoping I could test this method using that script. This didn't work using the method above so I opted for:
try {
    $test = dcdiag
}
catch {
    $err = $_.Exception.Message
}

It worked for my test case, but I don't know if this will pick up standard error from dcdiag.
How should I best achieve standard error redirect to a variable in PowerShell given I would like to use it with dcdiag?
Answer: try...catch wouldn't help in this case.
You might want to do:
$test = dcdiag 2>&1
$err = $test | ?{$_.gettype().Name -eq "ErrorRecord"}
if($err){
    # Error has occurred
}

Comment: Ah, I didn't say in the original question; is it possible to keep both stdout and stderr? i.e $test = stdout and $err = stderr?
Comment: @Ablue - `$test` will have both, that is why I am filtering out the error to `$err`.
Comment: @Simon Correct, I said DO NOT use SilentlyContinue.
Comment: Make sure $ErrorActionPreference is not set to "SilentlyContinue". When it is the errors stream is not available.
Comment: @cmcginty actually $ErrorActionPreference should be set to "Continue". Using SilentlyContinue will only capture stdout as stderr will be completely removed (at least on powershell 5)
Comment: Reverse the filter to get stdout without the error (but still capture stderr) `$test | ?{$_.gettype().Name -ne "ErrorRecord"}`


Safari on iPhone and iPad crashes while zooming (double-tap and pinch)

Question: I have a problem with a Wordpress-run website: http://www.igorlipinski.com - Safari freezes and eventually crashes on iOS devices while using the zoom option, either double tap or pinch to zoom option. It looks and works very well on desktop browsers. I can't quite locate the problem... any thoughts? Thanks in advance!
UPDATE: I disabled javascript on my iPhone and the site worked beautifully, so at least I know where to look now! I would appreciate if anyone had a direct solution for this particular site, but I will work on it in the meantime.
Comment: Did you figure out what the culprit was? I'm running into something similar, where zooming into our site causes image memory usage to skyrocket and crash the browser; however turning off JS fixes it. We use a lot of JS so figuring out where to start in terms of disabling things is tricky.
Comment: I suspect it might be due to one of the plugins used on the site.
Have you tried it on any other browsers on your iPhone/iPad?
Comment: I tried it on Opera Mini and the zoom problem disappears (it doesn't look great on it, but I can live with it for the time being). I will try out disabling different plugins and see if it works. Thanks! By the way, I'm using popular theme on themeforest called Equilibrium, but it seems like it's not optimized for Safari mobile, which is a shame, let me know if you have any other thoughts or solutions.
Comment: I have analysed the crash report about similar crash, It says "The exception code 0x8badf00d indicates that an application has been terminated by iOS because a watchdog timeout occurred. The application took too long to launch, terminate, or respond to system events. One common cause of this is doing synchronous networking on the main thread. Whatever operation is on Thread 0: needs to be moved to a background thread, or processed differently, so that it does not block the main thread"
Answer: I have faced similar kind of issue. Found issue with canvas drawing.
Basically there is one issue with canvas drawing. when we draw or erase something using canvas's methods like drawRect(), lineTo(), moveTo(), etc... it will create extra layer (like pixels on canvas) which causes memory leakage issue in safari browser for ipads/mobiles.
I am still looking for solution/alternative for memory leakage while using canvas.
Hope this will help you find any clue related to your project.


How To Get Intercept with Moore-Penrose Pseudo Inverse

Question: I am doing multiple linear regression.   I was directed to this question on how to solve MLR as a sequence of simple linear regressions, Question on how to normalize regression coefficient   and I understand this result.
However I have also been told that Moore-Penrose Pseudo Inverse can be used for MLR.  In doing so I see that it does indeed give the least squares result for a set of linear equations.   However I can't figure out how to use it for linear regression if I have a y intercept that is non-zero.
The Moore-Penrose Equation that I understand, which is ( (A' * A)^-1 * A' ) * y seems to force a regression through the origin.   Is there a way to use it and then calculate an intercept ?
Answer: The intercept term can be viewed as the coefficient of an independent variable that is always one. Therefore, adding a column of ones to the matrix $A$ will result in the intercept term surfacing at the corresponding position.


Does PLM package (PGMM function) use Windmeijer-corrected cluster-robust errors?

Question: I am performing a GMM analysis using the pgmm function in the plm package in R. I read a lot about different errors (nonrobust, cluster-robust, Windmeijer-corrected cluster-robust errors) and I wanted to know which of them is included in the PLM package (as the default version)?
How can I verify, which type of error was used?
Answer: I have never done GMM before, so I might misread your question as I don't understand it's background fully, but a simple quick search shows that there are different functions, vcovHC, vcovNW, vcovDC, vcovBK, and vcovSCC,  that provide a bunch of different options for the method of estimation.

Note that R uses different functions depending on the object type that is passed to the function. The vcovHC function will be different when used with an object of the class pgmm

## S3 method for class 'plm'
vcovHC(
  x,
  method = c("arellano", "white1", "white2"),
  type = c("HC0", "sss", "HC1", "HC2", "HC3", "HC4"),
  cluster = c("group", "time"),
  ...
)

## S3 method for class 'pcce'
vcovHC(
  x,
  method = c("arellano", "white1", "white2"),
  type = c("HC0", "sss", "HC1", "HC2", "HC3", "HC4"),
  cluster = c("group", "time"),
  ...
)

## S3 method for class 'pgmm'
vcovHC(x, ...)

and it uses the Windmeijer correction.

A special procedure, proposed by Windmeijer (2005) for pgmm objects is provided.
...
Weidmeijer, F. (2005) A finite sample correction for the variance of linear efficicent two--step GMM estimators, Journal of Econometrics, 126, pp.25--51.

(the quote contains a typo in spelling the name)
Comment: Good answer! Note that the type in the authors name (Weidmeijer instead of Windmeijer) is not present in current version of pkg `plm` but some websites having a copy of the old documentation have it.
Comment: When using the `summary` method for `pgmm`, argument `robust` default to `TRUE` and will give you the Windmeijer correction in summary's output.
Comment: Thanks, that helped. However, I still need some help for my understanding: It said that Windmeijer (2005) is provided for pgmm objects, does that mean that the robust standard errors are already shown in my summary of outcomes OR do I still need to calculate them and then add them afterwards using vcovHC?


php variables in another page

Question: im new to php, i just want to echo firstname can anyone please help me !
When i click on the submit button it redirects to action.php and then i want
to echo my firstname from the form from previous page.
Here is my code :
action.php
<?php

    echo "Great! Thanks" . $s1 . " for responding to our survey" ;

?>

index.php

    <title>Idiot Box Survey</title>
    <meta charset="utf-8">

    <form action="action.php" method="post">

        Firstname :
        <input type="text" name="fname">

        Lastname :
        <input type="text" name="lname">

        Year of birth :
        <input type="date" name="ybirth">

        Year at School :
        <input type="date" name="yschool">

        When will You Wake up :
        <input type="time" name="wake">

        How much time you spend on studying :
        <input type="time" name="study">

        How much time you spend on Video games :
        <input type="time" name="vgames">

        How much time you spend on tv :
        <input type="time" name="tv">

        How much time you spend with family :
        <input type="time" name="family">

        How much time you spend with friends :
        <input type="time" name="friends">

        When will You Sleep :
        <input type="number" name="sleep">

        <button type="submit" name="submit"> Submit Form </button>

    </form>

Comment: I think you are missing the code for `action.php`?
Comment: What is the Code im missing ? @Bijan
Answer: action.php appears to be missing from your question, but either way, your first name will be in $_POST['fname']
Comment: Add something that lets him/her know to check to make sure the submit button has the value of post.  Review my edit please.
Answer: <?php echo $_POST['fname']?>

use the name attribute of the input to print the other fields
<?php echo $_POST['lname']?> //for the last name and soo ..

Answer: Since my edits are apparently not accepted in other answers.  Instead of calling a non existing php variable in $s1, On your action.php page write this.
if($_POST["submit"]){
    $fname = $_POST["fname"];
    echo "Great! Thanks" . $fname . " for responding to our survey" ;
}

This allows your form to pass the submitted data to the desired script.  When you hit the submit button, you'll see the value that you put into the fname input field.
Comment: The down-vote is because this answer has two typos that will prevent your code from executing. Correct them and I'll happily undo the vote. The edits were rejected (not by me, but I agree with them) because they didn't actually add anything to the answer.
Comment: Down-vote undone. I totally get that. I'm tempted to add tips and pointers like that too all the time, but we're technically supposed to stick to the questions. Otherwise we might as well write the whole application for them. :D
Comment: Not sure why I got a down vote for this answer, seeing as how it's a correct and valid answer, but whatever.
Comment: Typos are fixed, thanks for letting me know about them.  I know my edit didn't really add to your answer, but I figured that since the OP is new to PHP, he/she would like to see what to do to get the variables when the form is submitted
Comment: Thanks for removing it.  I've got a bad habit of doing exactly that in writing an application to help people.  I should probably stop doing that.

php variables in another page


can't unassign role from user

Question: I am working on a site which uses someones custom module which makes some modifications on the user account page as well as his profile pages.
On this site, I registered myself as a user and logged in and found that I was assigned to all roles, even administrator. When I tried unclicking the checkboxes on the user page to unassign roles, it didn't work, the roles stayed the same. I tried this while logged in as the user himself and also as the admin.
What types of things could be causing this issue? Where should I look?
Answer: As per my understanding, there are custom modules from which it is updating.
Try searching hooks like hook_user_insert(&$edit, $account, $category) and hook_user_update(&$edit, $account, $category) from custom modules. I hope they might have written a piece of code to update the roles.

can't unassign role from user


My object is defined but doesn't exist. How to solve the problem?

Question: I defined several dummy variables and I can see them in my dataset. However, when I try to run a regression model, R says that Error: object "my_variable" not found. I also used exists(my_variable) and got the same error message. I checked for the spelling and it was not a problem.
I'd appreciate it if someone can help.
Comment: It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. How are you running your regression model? Are you passing the right data source to your regression function? It's very hard to guess what's going on without seeing data and code.
Answer: First, when you use exists(), you should put the variable in quotations (i.e., exists("my_variable")).
Second, be sure that you set up your regression model properly. For example:
lm(response ~ predictor1 + predictor2 + predictor3 + ...,
      data=my_variable)

Ultimately, you need to include some of your data via dput(head(my_variable)), and the regression code.


When She Loved Me: Opening Chord progression - replace the 3rd chord from G7/B to Bdim or Bb?

Question: This is the opening chord progression of "When She Loved Me," in Toy Story 2, sung by Sarah McLachlan. See a related question.

The chord progression goes like:
Dm -> AmC -> G7/B -> Bbm.
Which means:

Dm: DFA.

AmC: CEA

G7/B: BDFG

Bbm: BbDbF

My question is on the third chord. Why do we need this sound "extra" but "incoherent" G?
Why not replace this 3rd chord to either of the following:

Bdim: BDF

Bb (B-flat major): BbDF

What are the considerations to choose Bbm instead of Bdim or Bb?
p.s. See this for example for the piano:
Comment: Why not? Because he chose those sounds. They're valid choices. Your suggestions would be another way to do it. Not sure why you consider the G in the third chord "incoherent"? Here's a question for you. Do you LIKE this song? If not, just pass it by. It's perfectly well-crafted, but maybe it's a bit schmaltzy for your taste. That's OK.
Comment: I like the song that is why I tried to spend time digesting the arrangement. I am a Scientist.
Comment: I don't believe this can be answered. It is an artistic choice. You can play whatever chords you like, especially in the intro, where you're not limited by the melody line.
Comment: Then the question is more about: why this is a better choice (from the writer)? (the considerations)
Comment: If these sorts of questions cannot be asked, then I am not sure what chord theory is about... so let is keep the question opened for analysis. :) thanks.
Comment: "What are the considerations to choose Bbm instead of Bdim or Bb?" Did you mean Bbm or G7 here? Bbm doesn't seem to relate to the rest of the question as currently written.
Answer: Why not Bb Major?
This is the easier one to explain. The bass line with the given chords comprises a four-note descent: D-C-B-Bb. Using a Bb Major chord, would have two effects. First, the bass line would arrive at Bb "too early", making the overall line less effective. Second, all of the other chords are minor. Having such a starkly "bright" (major) chord is jarring and changes the intended mood of the song.
Why not B Diminished?
This would be better than Bb Major insofar as it preserves the descending bass line. And in one sense, there is a B Diminished chord: the B, D, and F are all present. So the "real" question, is
Why include G?
Two reasons, both linked to voice leading. The "tenor" voice is key.

The tenor could move A-A-B-F. The main problem here is that the leap down to F, combined with the fact that it's a leap by tritone into an octave with the soprano, really stands out to the ear, creating an unwanted emphasis on the lower F. The voice leading is anything but smooth.
The tenor could move A-A-F-F. This creates two double octaves between the soprano and tenor, which is a very static sound — so much so that it undermines the sense of a descending line created by the bass and alto. The intention of the passage is to invoke a sense of sadness and reminiscence, and the descending line is essential to this.
The tenor could move A-A-B-Bb. By itself, this sounds best of the three options; however, the substantial change in register to the F chord creates a sense of disconnect. It's too big a leap; the presence of the lower F (rather than Bb) smooths the transition.

Why G7?
Besides the avoidance of an "overly major" (cheerful) chord and the preservation of the sense of descent, using a dominant seventh chord helps preserve the poignancy because even while a "major-ish" chord, it has two built-in dissonances that keep things from getting to bright.
G7 specifically also creates some tonal ambiguity. Imagine we're hearing the song for the first time. We don't know what key it's in, and we don't know the minor iv chord is coming up. In that case, the chord progression could be ii-vi-V7-I (in C Major). Or the chord progression could be more than four chords: say, Am-Dm-G7-Am-EbM7-FM-BbM
Comment: One quibble: In the "Why include G?" section, what rules out the tenor line going A-A-B-Bb? Sure, it's octaves with the bass, but is there a reason it isn't considered? That's the solution I probably would have gone for if I were required to use only Bdim instead of G7. Regardless, +1 for a nice answer!
Comment: @user45266 - I'd personally suspect that the "tenor" line not going A-A-B-Bb is to avoid making the final transition out of the introduction and into Bar 3 involve a jump down from that Bb to the soprano's F, which is even nastier voice crossing than we already have.
Comment: @user45266 Thanks for catching that A-A-B-Bb voicing. I've updated by answer to offer an explanation for why it wasn't used.
Comment: @Dekkadeci I think you nailed it. I didn't put my update in quite those terms, but it amounts to the same thing. The downward leap in all of the voices interrupts the otherwise smooth voice leading.


conditional probability

Question: In a Blind tasting of wines from Bordeaux and Napa valley,a wine expert has 90% chance of correctly identifying that a wine is from Bordeaux and 80% chance of correctly identifying wine from Napa Valley.If 60% of wines at a tasting are from Napa,what is the probability that a random selected wine is from Napa Valley,given that the wine expert said it was from Napa?
N=event wine from a tasting is from Napa
B=even wine from a tasting is from Bordeaux
C=correctly identify wine
$P(N|C)=\frac{P(N)*P(C|N)}{P(N)*p(C|N)+P(B)*p(C|B)}=  \frac{0.6*0.8}{0.6*0.8+0.4*0.9$}=0.57$
correct answer is 0.92
Comment: "C=correctly identifying the wine" is what threw you.  The condition is "given that the wine expert *said it was from Napa*" rather than that the expert was correct (about it being from Napa).
Comment: **PS:** This is an *important* lesson. $~$ You may be given more problems where the conditional probabilities are presented in terms of *correctness* or *truthfulness* of some claim, when the actual event of interest is about *what the claimant sais*. $~$  Watch out for these in the future.
Comment: It's all clear now,so easy to get trick with these type of problems.Thank you
Answer: In the denominator, we should have $P(B) * P(I|B)$, since the expert incorrectly predicted the Bordeaux wine was from Napa. So switching 0.9 to 0.1 gives you the desired result.
$$P(N)=\frac{P(N)*P(C|N)}{P(N)*p(C|N)+P(B)*P(I|B)}=  \frac{0.6*0.8}{0.6*0.8+0.4*0.1}=0.92$$
Comment: thank you I see my mistakes now
Answer: You should be dividing by $P($wine expert says it is from Napa$)$.
They will say it is from Napa if (i) it is from Napa and they are correct or (ii) it is from Bordeaux and they are incorrect.

conditional probability


Radon-Nikodym for thress measures.

Question: Let $\mu_1$ and $\mu_2$ and $\nu$ be two finite measures on the measurable space $(\Omega, \mathcal{S})$ such that $\nu \ll \mu_i$, $i = 1, 2$, and $f_i = \frac{d\nu}{d\mu_i}$. Show that then $\nu \ll \mu_1 + \mu_2$ and
$$
\frac{d\nu}{d(\mu_1 + \mu_2)} = \frac{f_1 \cdot f_2}{f_1 + f_2}
$$
I have managed to prove the first part of it, but i have some question for the second part. Just by writing the definition of the f i and transforming the eqution i get to.
$$
\frac{d\nu}{d(\mu_1) + d(\mu_2)}
$$
is this equal to the statment above?
Answer: Hint: $\int_E (\frac 1 {f_1}+\frac  1{f_2}) d\nu=\int_E \frac 1 {f_1} f_1d\mu_1+\int_E \frac 1 {f_1} f_1d\mu_2=\mu_1(E)+\mu_2(E)$ and this implies $\frac {d\nu}{d(\mu_1+\mu_2)}=\frac 1 {\frac 1 {f_1}+\frac  1{f_2}}=\frac {f_1f_2}{f_1+f_2}$.
Comment: Thank you. I understand your answer but i have one question. What is the reason you wrote $\int_E (\frac 1 {f_1}+\frac  1{f_2}) d\nu $ .  I dont know how oyu got there
Comment: All I did was to bring RHS down to LHS and move $\mu_1+\mu_2$ to RHS. Simple algebraic manipulation.  @vwhg1050
Comment: but why$\mu_1(E)+\mu_2(E)$ and not $d(\mu_1(E)+\mu_2(E))$
Comment: $\int_E d(\mu_1+\mu_2)$  is nothing but $\mu_1(E)+\mu_2 (E)$.
Comment: thank you, i got it now

Radon-Nikodym for thress measures.


Probability limit formula for coefficient in errors in variables regression

Question: I found an online resource which lists the plim formula for a simple regression under the classic errors-in-variables assumption as:
$$
\text{plim }\beta_1=\frac{{\rm Cov}(y, x_1)}{{\rm Var}(x_1)}
$$

Why is this the case?
Where does this formula come from?
Comment: Can you provide a link to the "online resource" in question? Note that the formula you list is just the OLS estimator for a regular (non-errors in variables) simple regression model.
Comment: Two very similarly phrased questions in a very short period of time; the other is [here](http://stats.stackexchange.com/questions/84205/probability-limit-calculation). Is this the same person twice?
Answer: I'm not sure I understand the question, but for a simple regression model
$$
Y = \alpha + \beta X + \epsilon,
$$
where $X$ and $\epsilon$ are independent, we have
$$\frac{\mathop{\text{Cov}}(Y, X)}{\mathop{\text{Var}} X}=\frac{\mathop{\text{Cov}}(\alpha+\beta X + \epsilon, X)}{{\mathop{\text{Var}} X}}=\frac{\beta\mathop{\text{Cov}}(X, X)}{\mathop{\text{Var}} X}=\beta\frac{\mathop{\text{Var}} X}{\mathop{\text{Var}} X}=\beta.$$
Similar formulas hold for the sample estimates of these quantities. Taking limits on the sample estimates will then give you the requested convergence in probability.


How to prove $\lim_{a\to -\infty} \sup_n P(\sum_1^n X_j / \sqrt{n} \leq a) = 0$

Question: Let $(X_n)$ be a sequence of independent identically distributed $L^2$ random variables with mean $0$ and variance $1$. I want to prove that
\begin{equation}
\lim_{a\to -\infty} \sup_n P\left(\frac{\sum_1^n X_j} {\sqrt{n}} \leq a\right) = 0\text{.}
\end{equation}
I get this intuitively, since the distribution of $\sum_1^n X_j/\sqrt{n}$ gets close to the standard normal distribution and $a$ goes to $-\infty$. But how can I prove it?
Answer: Let $S_n = \sum_1^n X_j$ and let $a \lt 0$. By Chebyshev's inequality (and using Var$(S_n) = n$):
$$P\left(\frac{S_n}{\sqrt n}\lt a\right)  = P\left(S_n\lt a\sqrt n \right)$$
$$\le P\left(|S_n|\gt |a|\sqrt n \right) \le \frac{n}{a^2n} = \frac{1}{a^2}$$
Since this is true for all $n$,
$$\sup_n P\left(\frac{S_n}{\sqrt n}\lt a\right) \lt \frac{1}{a^2}$$
Now take $\lim$ as ${a\to-\infty}$.
Comment: Actually, I needed to prove the proposition in my question so that I can prove that $\lim_{n\to\infty}P(S_n/\sqrt{n}\leq a)=\int_{-\infty}^a\exp(-t^2/2)dt/\sqrt{2\pi}$ for all $a\in\mathbb R$. So is there a way to solve my question without using this formula? I already proved that the distribution of $S_n/\sqrt{n}$ converges vaguely to the standard normal distribution $\nu_0^1$, so I'm free to use this fact.
Comment: @zxcv Well I just realized I didn't need CLT at all, just Chebyshev's inequality.


Date Formatters in NSDateFormatter

Question: The documentation is not clear about the date formatters
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"EEE, d MMM yyyy HH:MM"];
What are the availabe dateFormats ????
Thanks
Answer: Any* Unicode-compliant date string. Specifications can be found here.
http://unicode.org/reports/tr35/tr35-6.html#Date%5FFormat%5FPatterns
*subject to certain locale dependencies. But you're unlikely to run into them for straightforward use cases.

Date Formatters in NSDateFormatter


How to extract table value from pdf using PYPDF2?

Question: I am trying to search through a pdf file to find the value associated with "Unit of Issue" or UI. I have a lot of pdfs to look through with potentially varying format. Here's a sample pdf and below is a screenshot of the top of the page with the table:

I would like to extract
UI:EA
on page 6. is there a way to accomplish this?
this is the code I use to open the file
import PyPDF2

try:
   pdfFileObj = open('test.pdf', 'rb')
   pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
   pageNumber = pdfReader.numPages
   page = pdfReader.getPage(0)
   print(pageNumber)

   pagecontent = page.extractText()
   print(pagecontent)
except Exception as e:
   print(e)

Answer: If you are open to using other tools, the following method is easier in my opinion.
Use the Bash command pdftotext. It extracts all the text inside the PDF and saves it in a text file.
Then use grep to find the line that contains the value of UI.
After testing on several of your PDF's, if the result of grep has a fixed pattern, use cut to get the value from this pattern.
pdftotext test.pdf  # this creates a test.txt file
grep "UI QUANTITY" test.txt  # output: UI QUANTITY EA 81.000

If the value you are looking for is always the third word in the output of the above command, then pipe it to cut to get the value:
grep "UI QUANTITY" test.txt | cut -d ' ' -f 3

You can make the whole process into a script (reading PDF's, extracting text, finding the value, writing the results to a file).


Determinant of a $3\times 3$ matrix in simplest form.

Question: Let $\alpha$ and $\beta $ be fixed non-zero reals and $f(n)=\alpha^n+\beta^n$ with $$A=\begin{pmatrix}
3&1+f(1)&1+f(2)\\1+f(1)&1+f(2)&1+f(3)\\ 1+f(2)&1+f(3)&1+f(4)
\end{pmatrix}.$$ How to find determinant of the matrix $A$ i.e. $|A|,$ in the simplest form? Firstly I thought that matrix may be of a particular form. But its neither circulant matrix nor Vandermonde type or tridiagonal type. Then I tried multilinear property on columns of given matrix as below:
$$\det\begin{pmatrix}
3&1+f(1)&1+f(2)\\1+f(1)&1+f(2)&1+f(3)\\ 1+f(2)&1+f(3)&1+f(4)
\end{pmatrix}=\det\begin{pmatrix}
3&1+f(1)&1\\1+f(1)&1+f(2)&1\\ 1+f(2)&1+f(3)&1
\end{pmatrix} +\det\begin{pmatrix}
3&1+f(1)&f(2)\\1+f(1)&1+f(2)&f(3)\\ 1+f(2)&1+f(3)&f(4)
\end{pmatrix} $$
I further apply multilinear property on columns but didn't get my answer. Please help. Thanks.
Answer: Hint: Consider
$$
\left(\begin{matrix}
1&1&1\\1&\alpha&\beta\\ 1^2&\alpha^2&\beta^2
\end{matrix}\right)\left(\begin{matrix}
1&1&1^2\\1&\alpha&\alpha^2\\ 1&\beta&\beta^2
\end{matrix}\right).
$$ Do you recognize it now?

Possibly more systematic way: Recognizing each column of $A$ is a linear combination of vectors$$
u=\left(\begin{matrix}1\\ 1 \\1 \end{matrix}\right),\quad \  v=\left(\begin{matrix}1\\\alpha\\ \alpha^2\end{matrix}\right),\quad \  w=\left(\begin{matrix}1\\ \beta\\ \beta^2\end{matrix}\right),$$  express the matrix as
$$
A=(u+\ v+ w\ ,\ \ u+\alpha  v+\beta  w\ ,\ \ u+\alpha^2  v+ \beta^2 w).
$$ Regarding $u,v,w$ as if they were numbers, if necessary,
$$
A=(u,v,w)\left(\begin{matrix}
1&1&1\\1&\alpha&\alpha^2\\ 1&\beta&\beta^2
\end{matrix}\right)=\left(\begin{matrix}
1&1&1\\1&\alpha&\beta\\ 1&\alpha^2&\beta^2
\end{matrix}\right)\left(\begin{matrix}
1&1&1\\1&\alpha&\alpha^2\\ 1&\beta&\beta^2
\end{matrix}\right).
$$
Comment: ohh yes it gives required matrix.....
Comment: Did you mean product of these matrix gives required matrix?
Comment: @neelkanth You can try it!
Comment: This is kind of "either you have ever seen it or it is impossible to guess" hint. lol.
Comment: @zwim yes that way it did't come in my mind....
Comment: @neelkanth Nope. If you let $u=(1,1,1), v=(1,\alpha,\alpha^2), w=(1,\beta, \beta^2)$ and manipulate $\det(u+v+w, u+\alpha u+\beta w, u+\alpha^2 u+\beta^2 w)$, you will get $$\det(u,v,w)\cdot \det\left(\begin{matrix}
1&1&1^2\\1&\alpha&\alpha^2\\ 1&\beta&\beta^2
\end{matrix}\right) $$ which is exactly what I obtained. Actually, I obtained it this way. I didn't recognize immediately.
Comment: @Song Ok and thank you very much....


How can I check whether a volume is mounted where it is supposed to be using Python?

Question: I've got a backup script written in Python which creates the destination directory before copying the source directory to it. I've configured it to use /external-backup as the destination, which is where I mount an external hard drive. I just ran the script without the hard drive being turned on (or being mounted) and found that it was working as normal, albeit making a backup on the internal hard drive, which has nowhere near enough space to back itself up.
My question is: how can I check whether the volume is mounted in the right place before writing to it? If I can detect that /external-backup isn't mounted, I can prevent writing to it.
The bonus question is why was this allowed, when the OS knows that directory is supposed to live on another device, and what would happen to the data (on the internal hard drive) should I later mount that device (the external hard drive)? Clearly there can't be two copies on different devices at the same path!
Thanks in advance!
Answer: I would take a look at os.path.ismount().
Comment: @McJeff: That's true it doesn't tell *which* it tells *if*. If no device is there, it'll return false and a write to that path will write to the underlying directory in the *parent* filesystem. So if it returns false, issue an error and don't write there. The directory `/external-backup` doesn't live on an external device, it lives on the parent filesystem. The system only knows what `mount` tells it, it doesn't have any idea what *ought* to be there. There's nothing special about a "mount point" on a Unix filesystem. It's just a regular directory.
Comment: The only problem is that it returns a boolean & doesn't specify whether the right device is there.
Comment: That does the job perfectly. I'm not going to protect against other volumes being mounted there, just that it's not the parent filesystem. Sorry to the other answerers, your answers may answer my question more exactly but I'm afraid I didn't quite know what to ask for in the first place as you might be able to tell ;) I've rated you all up anyway.
Comment: Good explanation!
Answer: For a definitive answer to something only the kernel knows for sure, ask the kernel:
cat /proc/mounts

That file can be read / parsed as if it was a normal file, using any tools you like.  Including Python.  Quick-n-dirty example:
#!/usr/bin/python

d = {}

for l in file('/proc/mounts'):
    if l[0] == '/':
        l = l.split()
        d[l[0]] = l[1]

import pprint

pprint.pprint(d)

Answer: The easiest way to check is to invoke mount via subprocess and see if it shows up there. For extra credit, use os.readlink() on the contents of /dev/disk/by-* to figure out which device it is.
Comment: As I see it the problem with that approach is that the output of `mount` is sloppily defined at best. What does `mount` output if I have mounted `/dev/evil device on tour` at `/directory on which I mount devices`? The parsing of the output might be unreliable in such cases...
Answer: Bonus answer. If external device is not mounted data is written to root partition at path /external-backup. If external device is mounted data on root partition is still there but it is not reachable because /external-backup is now pointing to external device.
Answer: Old question, but I thought I'd contribute my solution (based on Dennis Williamson's and Ignacio Vazquez-Abrams's's answer) anyways. Since I'm using it on a non-Linux environment to check remote directories being mounted, /proc and mtab cannot be used and no additional checks have been implemented:
def is_mounted(special, directory):
    search_prefix = '{} on {}'.format(special, directory.rstrip('/'))

    if os.path.ismount(directory):
        mounts = subprocess.check_output(['mount']).split('\n')

        for line in mounts:
            if line[:len(search_prefix)] == search_prefix:
                return True;

    return False

Improvements welcome!
Answer: The /etc/mtab file exists to tell you what is currently mounted. There is a getmntent call, but I don't think it's exported in the os module. The quick and dirty? Open /etc/mtab and split. Ensure your device is present in column 0 and the destination mount point in column 1 is correct.
Answer: You can try this but it won't work in every case:
from pathlib import Path

def guess_mounted(path) -> bool:
    for p in [Path(path)] + list(Path(path).parents):
        if p == Path('/'):
            return False
        elif p.is_mount():
            return True
    return False

Then later in your code you can do:
if not guess_mounted(save_path):
    raise Exception('Not mounted')


How to fetch a string out of "08-1_2-4_1517614" ie "1517614"

Question: If i have string like 08-1_2-4_1517614 and if i need to fetch the value "1517614" out of this for string manipulation in java
Any help will be much appreciated
Comment: the most easy way would be to `split("_")` and take the last one I guess; unless you know regex
Comment: `str.substring(str.lastIndexOf("_")+1,str.length())`
Comment: Thank you very much for your help. it worked.
Comment: btw, you don't put [solved], you actually [accept an answer that you found appropriate](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)
Answer: Here is a regex replace option:
String input = "08-1_2-4_1517614";
String output = input.replaceAll("^.*_", "");

A more general regex replace option using a capture group:
String output = input.replaceAll(".*(?<!\\d)(\\d+)$", "$1");

Or we could take a substring:
String output = input.substring(input.lastIndexOf("_") + 1);

Answer: String test = " 08-1_2-4_1517614";
String [] tokens = test.split("_");
System.out.println(tokens[tokens.length - 1]);

Or with regex:
String test = " 08-1_2-4_1517614";
System.out.println(test.replaceFirst(".+_", ""));

Or:
System.out.println(test.substring(test.lastIndexOf("_") + 1));

Comment: Or `Matcher matcher = Pattern.compile("(.+)_(.*)").matcher(test);
        System.out.println(matcher.find() ? matcher.group(2) : "");`
Answer: Or use
 str.substring(str.lastIndexOf("_") + 1, str.length())

Comment: you don't need the last parameter though
Answer: Is the pattern always the same?
https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#substring-int-int- could be your friend.
"08-1_2-4_1517614".substring(9, "08-1_2-4_1517614".length()) e.g.
Answer: Best way to do it, in case you want to resuse other parts of the original String.
  String num =  "08-1_2-4_1517614";
  String[] parts = num.split("_");
  String value = parts[parts.length - 1];
  System.out.println(value);

Answer: The most simple is to use regex to find all the numbers after the final underscore.
    Pattern patt = Pattern.compile("[^_]+$");
    Matcher matcher = patt.matcher("08-1_2-4_1517614");
    if(matcher.find()) {
        System.out.println(matcher.group());
    }else{
        System.out.println("No Match Found");
    }

Answer: I'd go for the one-liner:
System.out.println(myString.substring(9, 16));


A Question on Linear Operators (one to one condition statement)

Question: Let $T:X\to Y$ be linear operator.
I want to show that
$$
Tu = Tv \quad \text{for} \quad u,v \in Domain(T) \Rightarrow u=v
$$
if and only if
$$
Tu=0 \Rightarrow u=0.
$$
I saw this in a functional analysis book without any explain. But I'm a newbie so I could not prove this statement. Help me please.
Comment: I can show one direction with $v=0$ but the other direction I could not prove
Answer: You put a tag functional-analysis for your question though, this is actually a general (very basic) fact in linear algebra (this could be the reason why you wouldn't see any explanation for the fact in a Functional Analysis textbook which assumes one knows basic linear algebra):

Suppose $X$ and $Y$ are two vector spaces over $\mathbb{R}$ (or other field) and suppose $T:X\to Y$ is a linear mapping. Then $T$ is injective if and only if $\ker T=\{0\}$.

It is immediate from the linearity of the mapping $T$.
Note that for the proposition above, no norm structure is needed for $X$ and $Y$.
Answer: $(\implies)$ Note that $Tu=0=T(0)$. So by the hypothesis, $u=0$.
$(\impliedby)$ $Tu=Tv$ implies $T(u-v)=0$, so that $u-v=0$. Then $u=v$.
Answer: If $Tu=Tv\implies u=v$ then you have that
$$Tu=T0\underbrace{=}_{T\:\:\rm{linear}}0\implies u=0.$$
Conversely, if $Tu=0\implies u=0$ then one has
$$Tu=Tv\iff T(u-v)=0\implies u-v=0\implies u=v.$$
Answer: The key for the other direction is that $T$ is linear, so $Tu=Tv$ if and only if $Tu-Tv=0$, i.e., $T(u-v)=0$. So if $Tw=0$ implies $w=0$ and $T(u-v)=0$...


Disable auto-close on modal forms

Question: I'm working on an ASP.Net project using bootstrap and I'm using a modal form for my register system. The problem is that the form close automatically when I click on register. I would like it to stay open so I can take care of the registration server-side.
Here's the code of my register box...

                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Register

                            <button type="button" class="close" data-dismiss="alert">×</button>
                            <asp:Label Text="" id="AlertLabel" runat="server" />

                            Nom d'utilisateur
                            <asp:TextBox runat="server" class="form-control" ID="RegisterUserTextBox" />

                            Mot de passe
                            <asp:TextBox runat="server" type="password" class="form-control" ID="RegisterPasswordTextBox" />

                            Confirmez votre mot de passe
                            <asp:TextBox runat="server" type="password" class="form-control" ID="RegisterConfirmPasswordTextBox" />

                            Email
                            <asp:TextBox runat="server" class="form-control" ID="RegisterEmailTextBox" />

                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                        <asp:Button runat="server" Text="Register" class="btn btn-primary" OnClick="Register_Click" />

Comment: Whats inside Register_Click?
Comment: It's not coded yet, I still have to do the membership part, i'm pretty much checking if all the informations are correct
http://pastebin.com/4EuhFWz0
Answer: Looks like you are posting back data using the asp:Button.  That will cause a post back and refresh the page, as the Onclick is calling server side code.  if you want to keep the modal up, try posting the data from client side, using Ajax.
Comment: As much as I would like to use Ajax, i'm a student and I don't know how to use it yet, is there anything else I can use instead of Ajax? Else, I will just find a workaround and make the register form on a different page.
Comment: Without ajax would be tricky.  You could do the post back, update a session value or pass a parameter in the url to signify that it was done.  when the page load if that value is there it could trigger the popup via javascript.  try this: https://sandywebdesigner.wordpress.com/2014/08/18/using-c-code-to-force-bootstrap-modal-stay-open-after-page-postback/  otherwise just break it to another page like you said.
Comment: @Paritosh is correct, without AJAX this will probably need some dirty workaround.

One that comes to my mind is to reopen a model window on submit.

Disable auto-close on modal forms


Usar a tag select para alterar o conteúdo da pagina?

Question: Estou começando a usar JavaScript e gostaria de saber como posso usar o select para que de acordo com a linguagem escolhida, a página me mostre um retorno diferente (suas características).

$(document).ready(function() {

  var ling = ["Java", "JavaScript", "PHP", "Python", "Ruby", "c++"];

  var urlStr = "https://api.github.com/search/repositories?q=language:" + ling[5];

  var contr = 0;

  $.ajax({
    url: urlStr,
    type: "get",
    dataType: "json",
    success: function(data) {
      console.log(data);

      for (; contr < 10; contr++) {

        //console.log(contr);
        $("#nomeProj" + contr).text((contr + 1) + " - " + data.items[contr].name);
        $("#descr" + contr).text("Descriçao: " + data.items[contr].description);
        $("#nEstrlas" + contr).text("Nº Estrelas: " + data.items[contr].stargazers_count);
        $("#nCommits" + contr).text("Nº Commits: " + data.items[contr].forks);
        $("#url" + contr).text("URL: " + data.items[contr].html_url);

      };

    },
    error: function(erro) {
      console.log(erro);
    }

  });

});

Informe a linguagem:

<select id="lings" onchange="mudarLing()">
  <option value="Java">Java</option>
  <option value="JavaScript">JavaScript</option>
  <option value="PHP">PHP</option>
  <option value="Python">Python</option>
  <option value="Ruby">Ruby</option>
  <option value="C++">C++</option>
</select>

1 -

Descrição:

Nº Estrelas:

Nº Commits:

URL:

2 -

Descrição:

Nº Estrelas:

Nº Commits:

URL:

3 -

Descrição:

Nº Estrelas:

Nº Commits:

URL:

4 -

Descrição:

Nº Estrelas:

Nº Commits:

URL:

5 -

Descrição:

Nº Estrelas:

Nº Commits:

URL:

6 -

Descrição:

Nº Estrelas:

Nº Commits:

URL:

7 -

Descrição:

Nº Estrelas:

Nº Commits:

URL:

8 -

Descrição:

Nº Estrelas:

Nº Commits:

URL:

9 -

Descrição:

Nº Estrelas:

Nº Commits:

URL:

10 -

Descrição:

Nº Estrelas:

Nº Commits:

URL:

Answer: Você pode usar o evento change do JQuery:
$('#lings').change(function(){
 //Aqui você faz o que for necessário para mudar a língua
});

Mas também percebi que no seu select tem um onchange para a função mudarLing(), mas essa função não esta declarada em nenhum lugar do seu javascript.
Comment: a função mudarLing() foi uma tentativa q fiz mais n deu muito certo, mais vou tentar usar o evento change, Obrigado


regexp replacement depending on matched value

Question: Is it possible WITH A SINGLE REGEXP to execute a different replacement depending on the matched value?
For example, given the string "aaa bbb ccc aaa ddd" I would like to replace each occurrence of "aaa" with "alpha", "bbb" with "beta", "ccc" with "gamma" and "ddd" with "delta".
Very easy to do with four separate regexp replacements, I know:
my $s = "aaa bbb ccc aaa ddd";
$s =~ s/aaa/alpha/g;
$s =~ s/bbb/betaa/g;
$s =~ s/ccc/gamma/g;
$s =~ s/ddd/delta/g;

The question is whether that is possible to do the same with just one statement like:
$s =~ s/$pattern/$replacement/g;

If that matters, I'm using perl.
This is just a simplified example for a more complex problem I'm trying to solve; please do not start arguing that I'm asking the wrong question and that I should do it differently... if you really believe so, please just ignore the question.
Comment: I don't think so. But I might be wrong.
Answer: You can use hash to replace matches with desired values,
my %replacement = (
    "aaa" => "alpha",
    "bbb" => "beta",
    "ccc" => "gamma",
    "ddd" => "delta",
);
my ($pattern) = map qr/$_/, join "|", map quotemeta, keys %replacement;

$s =~ s/($pattern)/$replacement{$1}/ge;

Comment: Not sure I understand what you mean. What would $pattern and $replacement be in your statement?
Comment: You should use `my $pattern = join '|', map quotemeta, sort { length $b <=> length $a } keys %changes` to make sure that a match for, say, `aabbcc` is found before `aa`.
Answer: One thing that could serve is the /e modifier to s///, which means the right side is interpreted as code, and the matched text is replaced with the value returned by this code.
For your example, you would want something like:
$s =~ s/aaa|bbb|ccc/ $& eq 'aaa' ? 'alpha' : $& eq 'bbb' ? 'beta' : 'gamma' /eg;

Or better (as there is a performance penalty associated to using $&):
$s =~ s/(aaa|bbb|ccc)/ $1 eq 'aaa' ? 'alpha' : $1 eq 'bbb' ? 'beta' : 'gamma' /eg;

By the way, you may also want to use different separators and the /x modifier to improve readability if your expressions become really big. Example:
$s =~ s
        { ( aaa | bbb | ccc ) }
        {
            $1 eq 'aaa'
                ? 'alpha'
                : $1 eq 'bbb'
                    ? 'beta'
                    : 'gamma'
        }egx;

Edit: Quality
I proposed this answer because the question asked for a replacement depending on the matched value, but didn't specify whether, in their actual problem (as opposed to the simplified version they showed), the test on the match value would be a simple equality test.
A point was raised that a solution based on /e is of lesser quality than one based on a hash. This observation is valid, up to a point. In my opinion, the two factors of quality on which the solutions differ are:

Legibility: The hash solution is an unquestionable winner on this point.
Resource usage: On the example proposed by the OP, the /e solution wins on both time and space usage¹. In case the problem becomes bigger, the two solutions will scale differently: the /e solution will be linear in time and constant in space, whereas the hash solution will be (roughly) constant in time and linear in space.

Locally, /e is 5–10% faster, and %replacement uses 588 bytes of memory. The benchmark code is:
my $str         = 'aaa bbb ccc aaa ddd';
my $pattern     = qr{ ( aaa | bbb | ccc | ddd ) }x;
my %replacement = ( "aaa" => "alpha", "bbb" => "beta", "ccc" => "gamma", "ddd" => "delta", );
cmpthese( 10000000,
    {
        e => sub { my $s = $str; $s =~ s/$pattern/$1 eq 'aaa' ? 'alpha' : $1 eq 'bbb' ? 'beta': $1 eq 'c'? 'gamma': 'delta'/eg },
        h => sub { my $s = $str; $s =~ s/$pattern/$replacement{$1}/ge; },
    }
);
Comment: A hash is a *far* better mechanism to use here by almost any measure than a long string of conditional operators.


Salvar estado da pagina sem refresh,apos expirar session

Question: Aqui verifica se está logado
<code>public function isLogged()
{

    if (isset($_SESSION['ccUser']) && !empty($_SESSION['ccUser'])) {
        if ($_SESSION['registro']) {
            $segundos = time() - $_SESSION['registro'];
            if ($segundos > $_SESSION['limite']) {
                unset($_SESSION['registro']);
                unset($_SESSION['limite']);
                unset($_SESSION['ccUser']);
                session_destroy();
                return false;
            } else {
                $_SESSION['registro'] = time();
                return true;
            }
        }
    } else {
        return false;
    }
}
</code>
caso não redireciona para pagina de login e controller
<code> public function index(){
    $data = array();

    if(isset($_POST['email']) && !empty($_POST['email'])) {
        $email = addslashes($_POST['email']);
        $pass  = addslashes($_POST['password']);

        $user = new Users();

        if($user->doLogin($email, $pass )){
            header("Location: ".BASE_URL);
            exit;
        } else {
            $data['error'] = 'E-mail e/ou senha inválido.';
        }
    }
    $this->loadView('login', $data);
}

public function doLogin($email, $password)
{

    $sql = $this->db->prepare('SELECT * FROM user WHERE email = :email and password = :password AND TIPO = "USUARIO"');
    $sql->bindValue(':email', strtoupper($email));
    $sql->bindValue(':password', md5($password));
    $sql->execute();

    if ($sql->rowCount() > 0) {
        $row = $sql->fetch();

        $tempolimite = 1800; // equivale a 10 segundos

        $_SESSION['registro'] = time();
        $_SESSION['limite'] = $tempolimite;
        $_SESSION['ccUserPainel'] ='';
        $_SESSION['ccUser'] = $row['id'];
        return true;
    } else {
        return false;
    }
}
</code>
o que eu não estou conseguindo e, o cliente esta cadastrando um veiculo, ai sai um pouco, quando volta expirou a session, gostaria de relogar e manter o estado da pagina que estava
Esta foi minha solução temporária, salvar só url index.php
<code>$url = $_SERVER["REQUEST_URI"];
$_SESSION['url'] = $url;
</code>
ai no
<code>    <?php
    class loginController extends controller
   {

    public function index()
    {
        $data = array();

        if (isset($_POST['email']) && !empty($_POST['email'])) {
            $email = addslashes($_POST['email']);
            $pass = addslashes($_POST['password']);

            $user = new Users();

            if ($user->doLogin($email, $pass)) {
                if (isset($_SESSION['url']) && $_SESSION['url'] != "") {
                    if ($_SESSION['url'] == '/enginesystem/login') {
                        header("Location: " . BASE_URL);
                    } else {
                        header("Location: " . $_SESSION['url']);
                    }
                } else {
                    header("Location: " . BASE_URL);
                }
                exit;
            } else {
                $data['error'] = 'E-mail e/ou senha inválido.';
            }
        }
        $this->loadView('login', $data);
    }

    public function logout()
    {
        $user = new Users();
        $user->logout();
        header("Location: " . BASE_URL);
    }
    }
</code>
Answer: Sugiro você utilizar algum recurso de front, é menos oneroso para implementar na sua aplicação.
Utilize Session Storage ou Local Storage, é uma boa solução para se utilizar no seu caso.
Até mais.
Comment: vo salvar so o endereço mesmo
$url = $_SERVER["REQUEST_URI"];
$_SESSION['url'] = $url;
if (isset($_SESSION['url']) && $_SESSION['url'] != "") {
                    if ($_SESSION['url'] == '/enginesystem/login') {
                        header("Location: " . BASE_URL);
                    } else {
                        header("Location: " . $_SESSION['url']);
                    }
                } else {
                    header("Location: " . BASE_URL);
                }


Is it possible to apply country specific masking in Dynamics CRM 2016?

Question: Up through MS CRM 2015 we have been successfully using jquery.ui to set input and view masks for common address data based on the country of the address.  We store these masks with a custom country entity.  The default CRM field is hidden.  Using JQuery we create a simple textbox and apply the mask to the value in the field based on the country value submitted.
Is there a way to add phone masking to CRM Forms in 2016?  Any help is greatly appreciated!
Answer: I'm not sure why you say that CRM 2016 does not allow DOM manipulation.  It doesn't allow it any more than any other version of CRM.  No DOM manipulation is supported, although nothing is preventing you from doing so, except that Microsoft may completely change the DOM and break everything you customized.
Actually 2016 happens to be the only version of CRM that this actually is possible in a supported manner without using an iFramed Web Resource.  Your basic setup with be as follows
In the OnLoad of the form

Retrieve the Country Phone Number Mask
Apply the mask to the field.
Add an OnKeyPress function to the field that removes the mask as the user types.
Answer: Use a web resource for that. Is the supported alternative version. Manipulating the DOM directly is bad practice as it might change across versions.


Why do these posterior plots have multiple curves?

Question: I fit a Student's t-distribution to some data using the No-U-Turn sampler, and called PyMC3's traceplot function to visualize the posteriors.
What do the different solid, dashed, and dotted lines in the histogram mean? I was expecting to see only one curve.
Answer: Each line represents a different chain, or independent MCMC run, and is useful for diagnostics. You should expect, for example, that if MCMC is working well, the sigma parameter will look the same across all four chains, which it doesn't (more tuning, more sampling, or rewriting the model may help).
When you are computing expectations, you should use all four chains.


if $xP(x)=x^t+P(x-1)$ find the $t\equiv ?\pmod 3$

Question: Let  polynomials $P(x)\in Z[x]$,and such $\deg{(P(x))}=t-1$,and such for any real  $x$ have
$$xP(x)=x^t+P(x-1)$$
Find the $t\equiv ?\pmod 3$?
I try Let  $P(x)=x^{t-1}+a_{t-2}x^{t-2}+\cdots+a_{1}x+a_{0}$ where $a_{i}\in Z$
so we have
$$a_{t-2}x^{t-1}+a_{t-3}x^{t-2}+\cdots+a_{1}x^2+a_{0}x=(x-1)^{t-1}+a_{t-2}(x-1)^{t-2}+\cdots+a_{1}(x-1)+a_{0}$$
Comment: you can see the http://math.stackexchange.com/questions/690714/if-ppx-px16x48qx-find-the-smallest-possible-degree-of-q?rq=1
Answer: Let $P(x) = \displaystyle\sum_{k = 0}^{t-1}a_kx^k$ where $a_k \in \mathbb{Z}$. Also, for $r = 0,1,\ldots,5$ define $S_r = \displaystyle\sum_{\substack{k = 0\\k \equiv r \pmod{6}}}^{t-1}a_k$.
Note that for $x = e^{i\tfrac{\pi}{3}} = \tfrac{1}{2}+\tfrac{\sqrt{3}}{2}i$ we have $x-1 = -\tfrac{1}{2}+\tfrac{\sqrt{3}}{2}i = e^{i\tfrac{2\pi}{3}}$.
By plugging $x = e^{i\tfrac{\pi}{3}}$ into the identity $xP(x) - P(x-1) = x^t$ and using the fact that $e^{i\tfrac{\pi}{3}k}$ and $e^{i\tfrac{2\pi}{3}k}$ are $6$-periodic, we get:
$$e^{i\tfrac{\pi}{3}}P\left(e^{i\tfrac{\pi}{3}}\right) - P\left(e^{i\tfrac{2\pi}{3}}\right) = e^{i\tfrac{\pi}{3}t}$$
$$\sum_{k = 0}^{t-1}a_ke^{i\tfrac{\pi}{3}(k+1)} - \sum_{k = 0}^{t-1}a_ke^{i\tfrac{2\pi}{3}k} = e^{i\tfrac{\pi}{3}t}$$
$$\sum_{k = 0}^{t-1}a_k\left(e^{i\tfrac{\pi}{3}(k+1)} - e^{i\tfrac{2\pi}{3}k}\right) = e^{i\tfrac{\pi}{3}t}$$
$$\left[-\tfrac{1}{2}+\tfrac{\sqrt{3}}{2}i\right]S_0 + \left[-\tfrac{1}{2}+\tfrac{\sqrt{3}}{2}i\right]S_2 + \left[-\tfrac{3}{2}-\tfrac{\sqrt{3}}{2}i\right]S_3 + \left[1-\sqrt{3}i\right]S_4 + \left[\tfrac{3}{2}+\tfrac{\sqrt{3}}{2}i\right]S_5 = e^{i\tfrac{\pi}{3}t}$$
Equating real and imaginary parts gives:
$$\tfrac{1}{2}\left[-S_0-S_2-3S_3+2S_4+3S_5\right] = \cos\left(\tfrac{\pi}{3}t\right)$$
$$\tfrac{\sqrt{3}}{2}\left[S_0+S_2-S_3-2S_4+S_5\right] = \sin\left(\tfrac{\pi}{3}t\right)$$
Then, $2$ times the real part equation plus $\tfrac{2}{\sqrt{3}}$ times the imaginary part equation gives:
$$4(S_5-S_3) = 2\cos\left(\tfrac{\pi}{3}t\right)+\tfrac{2}{\sqrt{3}}\sin\left(\tfrac{\pi}{3}t\right)$$
Since the $a_k$'s are integers, the $S_r$'s are also integers. So, $4(S_5-S_3)$ must be a multiple of $4$. But, $$2\cos\left(\tfrac{\pi}{3}t\right)+\tfrac{2}{\sqrt{3}}\sin\left(\tfrac{\pi}{3}t\right) = \begin{cases}2 & \text{if} \ t \equiv 0 \ \text{or} \ 1 \pmod{6} \\ 0 & \text{if} \ t \equiv 2 \ \text{or} \ 5 \pmod{6} \\ -2 & \text{if} \ t \equiv 3 \ \text{or} \ 4\pmod{6}\end{cases}.$$
Therefore, $t \equiv 2 \ \text{or} \ 5 \pmod{6}$, and thus, $\boxed{t \equiv 2 \pmod{3}}$.
Note: It is easy to check that $t = 2$ and $P(x) = x+1$ is a solution. There may be other solutions for larger $t \equiv 2\pmod{3}$.

Further Analysis: By substituting the sum for $P(x)$ into $xP(x) = x^t+P(x-1)$, we have:
$$\sum_{k = 0}^{t-1}a_kx^{k+1} = x^t + \sum_{n = 0}^{t-1}a_n(x-1)^n$$
$$\sum_{k = 1}^{t}a_{k-1}x^k = x^t + \sum_{n = 0}^{t-1}a_n\left(\sum_{k = 0}^{n}\dbinom{n}{k}(-1)^{n-k}x^k\right)$$
$$a_{t-1}x^t + \sum_{k = 1}^{t-1}a_{k-1}x^k = x^t + \sum_{k = 0}^{t-1}\left(\sum_{n = k}^{t-1}a_n\dbinom{n}{k}(-1)^{n-k}\right)x^k$$
By equating corresponding coefficients, we get:
$$a_{t-1} = 1$$
$$a_{k-1} = \sum_{n = k}^{t-1}a_n\dbinom{n}{k}(-1)^{n-k} \ \text{for} \ k = 1,\ldots,t-1$$
$$0 = \sum_{n = 0}^{t-1}a_n(-1)^{n}$$
The first two equations uniqely determine the coefficients $a_k$ for $k = 0,\ldots,t-1$. Then, the polynomial $P(x) = \displaystyle\sum_{k = 0}^{t-1}a_kx^k$ satisfies $xP(x) = x^t+P(x-1)$ iff the third equation is satisfied.
I tested this recursion for $1 \le t \le 56$ using a computer program. It appears that $t = 2$ was the only value of $t$ in that range for which $P(x)$ satisfies $xP(x) = x^t+P(x-1)$.
Answer: Given the equation $\space xP(x)=x^t+P(x-1)$, where $\deg(P(x))=t-1$, I would first solve for a general form for $P(x)$.
$$P(x)=x^{t-1}+\frac{P(x-1)}{x}$$
Where the general form for $P(x)$ is
$$P(x)=a_{t-1}x^{t-1}+a_{t-2}x^{t-2}+\dots+a_1x+a_0 = \sum_{i=0}^{t-1}a_ix^i$$
Plugging in to our equation yields
$$\sum_{i=0}^{t-1}{a_ix^i}=x^{t-1}+\frac{1}{x}\sum_{i=0}^{t-1}{a_i(x-1)^{i}}$$
Using the binomial theorem,
$$\sum_{i=0}^{t-1}{a_ix^i}=x^{t-1}+\sum_{i=0}^{t-1}{a_i{{t-1}\choose{i}}x^{i-1}(-1)^{t-1-i}}$$
Matching coefficients,
$$a_{t-1}=1\\a_{t-2}={{t-1}\choose{t-1}}a_{t-1}=1\\a_{t-3}=-{{t-1}\choose{t-2}}a_{t-2}=1-t\\a_{t-4}={{t-1}\choose{t-3}}a_{t-3}=\frac{(t-1)(t-2)}{2}a_{t-3}=\frac{1}{2}(t-1)^2(t-2)\\\dots\\a_{t-n}=(-1)^{n}{{t-1}\choose{t-n}}a_{t-n+1}$$
I hope this helps!


jqGrid grouping - hiding the group header and footer when only one row

Question: I use the grouping feature in a jqGrid.
But I want to display the group header (jqgroup) and group footer (jqfoot) only when there is more than one element in the group.
I am trying to do it with JQuery selectors in the loadComplete callback.
I have already succeeded in hiding the group header by checking the number of items in the group header text.
groupingView : {
  ..
  groupText: ['{0} ({1})'],
}

loadComplete: function(data) {
  // group header text is "value (number of elements)"
  $("#grid tr.jqgroup:contains('(1)')").hide();
}

But I cannot find the correct selector to hide the group summary row.
I have tried the following for example:
$("#grid tr.jqgroup:contains('(1)') + .jqfoot")

Answer: I found it in fact: "+" operator gives the really next element
$("#grid tr.jqgroup:contains('(1)') + .jqgrow + .jqfoot").hide();


Somar linhas e colunas no R

Question: Bom dia,
Estou utilizando o R há pouco tempo e tenho aprendido na prática. Agora me deparei com uma dificuldade com uma tabela. Como posso somar todas as linhas de determinadas colunas e exibir o resultado em uma nova coluna?
No caso minha tabela inicial tem seis colunas que serão somadas em dois blocos de três colunas. Exemplo: Contratos de Tecnologia, Programa de Computador e Desenho Industrial. Mas eu queria os resultados por países que estão separados por linhas, em uma nova coluna que vai ser Produção Tecnológica.
Um exemplo da planilha que estou trabalhando: https://docs.google.com/spreadsheets/d/1_HTtYC6h8ycXJO83jJiFRfWviqz-EOCHsytV0PtC2kU/edit?usp=sharing
Comment: Para acelerar a resposta a sua pergunta sempre use um `dput` da sua tabela no R e poste aqui o que sair no seu console.
Answer: Assumindo que Produção Tecnologica = CONTRATOS DE TECNOLOGIA + DESENHO NDUSTRIAL + PROGRAMA DE COMPUTADOR e Registros = INDICAÇÃO GEOGRÁFICA + MARCA + PATENTE. Usando o pacote básico do R basta usar o código abaixo. O código não é bonito e nem sofisticado, mas ele é básico e de fácil entendimento. O operador $ serve para acessar as colunas de um data.frame e o R automaticamente soma as linhas de suas posições correspondentes.
base.dados <- read.delim2("clipboard", as.is = T)

base.dados$PRODUCAOTENCOLOGIA <- base.dados$CONTRATOS.DE.TECNOLOGIA + base.dados$DESENHO.INDUSTRIAL + base.dados$PROGRAMA.DE.COMPUTADOR

base.dados$REGISTRO <- base.dados$INDICAÇÃO.GEOGRÁFICA + base.dados$MARCA + base.dados$PATENTE

Só para registrar usei o o comando read.delim2, pois dei um ctrl+c na base que você enviou via Google Docs.

Somar linhas e colunas no R


Efficient mapping of game entity positions in Java

Question: In Java (Swing), say I've got a 2D game where I have various types of entities on the screen, such as a player, bad guys, powerups, etc.  When the player moves across the screen, in order to do efficient checking of what is in the immediate vicinity of the player, I would think I'd want indexed access to the things that are near the character based on their position.
For example, if player 'P' steps onto element 'E' in the following example...
| | | | | |
| | | |P| |
| | |E| | |
| | | | | |

... would be to do something like:
if(player.getPosition().x == entity.getPosition().x &&
              entity.getPosition.y == thing.getPosition().y)
{
    //do something
}

And thats fine, but that implies that the entities hold their positions, and therefor if I had MANY entities on the screen I would have to loop through all possible entities available and check each ones position against the player position. This seems really inefficient especially if you start getting tons of entities.
So, I would suspect I'd want some sort of map like
Map<Point, Entity> map = new HashMap<Point, Entity>();

And store my point information there, so that I could access these entities in constant time. The only problem with that approach is that, if I want to move an entity to a different point on the screen, I'd have to search through the values of the HashMap for the entity I want to move (inefficient since I dont know its Point position ahead of time), and then once I've found it remove it from the HashMap, and re-insert it with the new position information.
Any suggestions or advice on what sort of data structure / storage format I ought to be using here in order to have efficient access to Entities based on their position, as well as Position's based on the Entity?
Answer: Space partitioning could be effective.
You can either do fixed divisions, such as a uniform grid, or a weighted grid if you except there to be hot spots on your map where things gets unusually clustered.  For each occupied partition, create a container of all entities it contains.
Insertion is constant time.  Removal is a practically infinitesimal fraction of n (your total number of entities) assuming n is very large and you've set up your partitions efficiently.  Proximity looksups share the same runtime as removals.  Still technically O(n) however small the fraction, though.  This would become apparent if a partition ever become unusually crowded.
To get a list of all entities within x units of an entity, you must first get a list of all partitions spanned by a 2x wide square square centered on your entity.  If you use a grid partition, this is fairly trivial.  Next, you loop through all entities in those partitions and return each one with a distance of x or less to the entity in question.
A more complicated method of partitioning is to dynamically partition space in a tree, ensuring that no partition can contain more than a given number of entities.  If a partition becomes full, you divide it along the spacial mean and create two two space partitions such that each one holds half of the original partition's entities.  This makes insertions and lookups have logarithmic runtime since you can no longer discover the desired partitions in constant time, but removals become constant time given the capped partition populations.
Comment: Thanks for the tips, I'll research space partitioning more.
Comment: I types up two game board implementions for holding 1,000,000 entities randomly added to a 1920x1080 area.  Using a 1080x1920 array of containers, I had 0.004 ms for insertion, 0.003 ms on removal and 0.004 ms to request a list of all containers in a 3x3 area.  Using dynamic binary space partitioning, I had 0.007 ms inserts, 0.003 ms removals and 0.007 ms queries for partitions intersecting a 3x3 region.  Performance and memory usage on the BSP should be even better for non-uniformly distributed entities.
Answer: If there is a one-to-one mapping between Entity and Point, and you want to be able to map in both directions, then a bimap is the most natural data structure.
Guava has a BiMap<K,V> implementation, which supports a BiMap<V,K> inverse() view operation. It's only a view, so it's not costly at all.
Alternatively you can manage your own Map<Entity,Point> and Map<Point,Entity>, but that'd be reinventing the wheel.
Answer: inefficient since I dont know its Point position ahead of time
Am I correct, that entity object doesn't have position information in it? I would suggest adding it. Or, otherwise, you can have map of current entity positions Map<EntityIdType, Point> and fetch position first. Nothing fancy.
Comment: Either you've just restated the problem at hand, or you didn't understand the question fully, because there's no solution provided here. Based on the 2 proposed methods in the original post, the object either does or does not contain the position information. Similarly, the Map depends on which approach was taken. Either way the original problem of finding middle ground is nowhere in your answer.


Definition of measurability

Question: The alternative definition of measurability is:

A subset $E \subset \mathbb{R}^n$ is measurable if for every $\epsilon > 0$ there is a closed set $F \subset E$ such that $m^*(E\setminus F)<\epsilon$.

I am asked to show that this is equivalent to the usual definition of measurability:

A subset $E \subset \mathbb{R}^n$ is measurable if for every $\epsilon > 0$ there is an open set $O \supset E$ such that $m^*(O \setminus E)<\epsilon$.

My approach is:
If $E$ is measurable, then $E^c$ is measurable. So for all $\epsilon > 0$, there exists a closed $F \subset E^c$ such that $m^*(E^c-F)<\epsilon$. Let $O=F^c$

Since $F$ is closed, $O=F^c$ is open.
If $F \subset E^c$, then $O=F^c \supset E$.
Finally, $E^c-F=F^c-(E^c)^c=F^c-E=O-E$, which implies $m^*(O-E)=m^*(E^c-F)<\epsilon$.

Other direction:
Suppose for all $\epsilon > 0$ there exists an open $O \supset E^c$ such that $m^*(O-E)<\epsilon$. This means $E$ is measurable, which in turn means $E^c$ is measurable. So there exists an open $O \supset E^c$ such that $m^*(O-E^c)<\epsilon$. Let $F=O^c$. If $O$ is open, then $F=O^c$ is closed. If $O \supset E^c$, then $F=O^c \subset E$. Finally, $$O-E^c=(E^c)^c-O^c=E-O^c=E-F,$$ which means $m^*(E-F)=m^*(O-E^c)<\epsilon$.
Answer: Your idea is on the right track.
To prove this equivalence, first suppose $E$ is measurable using the closed set definition.
We need to show the open set definition holds.  Let $\epsilon > 0$.  Since $E$ is measurable, so is $E^{c}$.  But $E^{c}$ measurable means there is some closed $F \subseteq E^{c}$ such that $m(E^{c} - F) < \epsilon$.
But if $F \subseteq E^{c}$, then $E \subseteq F^{c}$, and since $F$ is closed, $F^{c}$ is open.  Finally, $m(E^{c} - F) = m(E^{c} \cap F^{c}) = m(F^{c} - E)$, and so since $m(E^{c} - F) < \epsilon$, we have $m(F^{c} - E) < \epsilon$.  So, given an arbitrary $\epsilon > 0$, we found an open set $O = F^{c}$ containing $E$ such that $m(O - E) < \epsilon$, and this was exactly the definition of measurability using the open sets.
You should try proving the other direction (assume the definition for open sets, and prove it for closed sets), which is very similar, on your own.
Comment: I read only the first part of your answer, up to the sentence "Since $E$ is measurable, so is $E^c$," just so I can treat it as a hint first. Then I updated my question to reflect my latest attempt. I was wondering if my work is correct; I wanted to *really* understand by basically writing your solution in my own words (without looking at your solution prior). If so, then I can take it on from here on my own for the other direction.
Comment: @dragon Your work looks great to me.  Good job!  Now you should prove the other direction (i.e., assume the open definition of measurability and prove the closed definition).
Comment: I have proved the other direction (since it did ask to prove that the two definitions are equivalent, after all), and that proof is indeed very similar to the one for the forward direction. I guess the key idea of this exercise is that, even though we would not reach our destination working with measurability of $E$, we could work with the measurability of $E^c$ instead.
Comment: @dragon You're right.  It's a little tricky at first to realize that you have to work with $E^{c}$, but once you figure that out, the proof comes straight forwardly, as you figured out for yourself.

Definition of measurability


Surface integral over hemisphere $z = \sqrt{R^2 - x^2 - y^2}$

Question: Evaluate: $$\iint_S y\,dS,$$ where $S$ is the hemisphere defined by $z = \sqrt{R^2 -x^2 - y^2}.$
Attempt:I found two tangents, a normal and said $$dS = \frac{R}{\sqrt{R^2 -x^2 - y^2}} dx\,dy$$ In polars, $y = r\sin\theta,$ so I believe I should compute$$ \int_0^{2\pi} \int_0^R \frac{r\sin\theta \cdot R}{\sqrt{R^2 - r^2}} r\,dr\,d\theta$$ Is this okay?
Answer: The surface element on a spherical surface is given by $dS = r^2 \sin\theta d\theta d\phi$ in spherical coordinates $(r, \theta, \phi)$. Thus your surface integral can be evaluated as follows:
$$\iint_S y \,dS = \int_{\phi=0}^{2\pi} \int_{\theta=0}^{\pi/2} R \sin\theta \sin\phi \cdot R^2 \sin\theta \,d\theta \,d\phi =$$
$$= R^3 \cdot \left[-\cos\phi\right]_{\phi=0}^{2\pi} \cdot \left[\frac{\theta}{2} - \frac{\sin(2\theta)}{4}\right]_{\theta=0}^{\pi/2} = R^3 \cdot 0 \cdot \frac{\pi}{4} = 0$$
However, by noting that the integral of an odd function over a symmetric interval is always zero, it is possible to obtain the same result without any calculations.
Comment: Thanks. The reason I opted for cylindrical coords was the fact that we had symmetry with respect to the z axis. Why is my answer not correct?
Comment: Your answer is correct; try to carry out the integration! Sorry for the late reply.


Avro Records -> Kafka -> Kafka Connect Sink -> Amazon S3 Storage. Idempotency?

Question: So my employer has Avro messages going through Kafka. We want to archive all messages to Amazon S3. Ideally, they would be stored in S3-like-directories by day and use a path structure something like:
s3://my-bucket/data/day=2016-03-04/data.avro
Is there a reference or best practices for how to do this well?
My one question is idempotency: How do I provide write idempotency, where a record may be sent to my sink writer more than once yet only be stored on S3 once.
Am I correct that I need idempotency? If I implement a simple append (non-idempotent), Kafka Connect may send the same records twice and they may get stored redundantly?
Answer: AFAIK, you cannot append to an S3 object (file): https://news.ycombinator.com/item?id=10746969 - unless something changed very recently....
You also do not want to keep writing each event into S3 individually, but rather do it in batches - for obvious performance reasons.
So, the way we do it - is by using Cassandra as an intermediate storage to collect events for some time period (timeslice) - store them grouped by event times , not processing times - and then write those timeslices that were touched into S3 periodically. One timeslice would be stored into one S3 object - with the timeslice info being part of the file name.
If/when more events come for some past timeslice - it is added to that timeslice table in Cassandra, and a re-write into S3 is [eventually] triggered - which would again get all events for that timeslice and write into S3 with the same file name, effectively overwriting the existing file if any.
You have to decide how long you want to keep data in Cassandra - based on how your pipeline works and how "old" your incoming events might be.
This is how we achieve idempotency. It's probably not the most efficient way - but it works well for us, since we have very high event processing volumes and rates and Cassandra is great for fast writes.
I'd love to hear how others solve similar problems!
Answer: Why not use something like secor? It also has some guarantees for exactly once delivery.
You could also consider "kafka connect" based implementations like streamx.
Answer: From the description, it looks like what you are looking for is
1) Avro data write to S3
2) Data to be partitioned in S3
3) Exactly-once support while writing.
Qubole StreamX supports rich variety of format conversions, avro being one of them, along with data partition.
And, exactly once is in our pipeline which will be out soon.
Whereas secor is getting deprecated(mentioned in one of their responses on google group) and it also do not support avro.
So you can use qubole streamx to start with.
Comment: I've heard StreamX is also being deprecated, or at least not maintained or updated


openrecordset only showing one result

Question: When I use a recordset to read from a table everything works fine and the recordcount function shows me the correct amount, but when I use this simple query or any query I always get 1 as a recordcount.
Here's whats working
Option Compare Database
Option Explicit

Public Sub LoadQ2()

Dim db As DAO.Database
Dim rs As DAO.Recordset

Set db = CurrentDb
Set rs = db.OpenRecordset("test")'test is the name of my table which contains 13 rows

With rs
    Debug.Print .RecordCount
   .Close
End With

Set db = Nothing
Set rs = Nothing

End Sub

and here's whats not working
Option Compare Database
Option Explicit

Public Sub LoadQ2()

Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim strSQL As String

strSQL = "SELECT test.number_id FROM test"

Set db = CurrentDb
Set rs = db.OpenRecordset(strSQL)

With rs
    Debug.Print .RecordCount
   .Close
End With

Set db = Nothing
Set rs = Nothing

End Sub

I should get the same result with both recordcount right?? Also I'd like to see the line I have in the recordset in the debug is it possible to print the content of the recordset in the debug window??
Answer: To print the contents of the recordset, you can do one of these two options..
debug.print rs.fields(0) & ", " & rs.fields(1)

or
debug.print rs("ColumnNameHere") & ", " & rs("AnotherColumnName")

Answer: .... found the answer
before doing the Debug.Print .RecourdCount i added .MoveLast and got the right number of recordcount
Looks like recordcount just means at what record that he is not how many records
Answer: Just to complement as you already found the answer yourself :)
The Dynaset data type (default for DAO recordset) doesn't fully populate until you go through all its records - since the need to do a .MoveLast before checking how many records it actually has.
I presume that DAO just returns 1 for the recordcount as an easy way to check beforehand if the recordset is empty or not (e.g. recordcount > 0) without having to go through the hassle of moving between records.

openrecordset only showing one result


Using LFO to Control Amplitude

Question: I want to be able to route an oscillator through an LFO that controls the amplitude.
This is what I have tried:

It sort of works, however, the amplitude control on the LFO functions as On/Off.
In the noise module I'm working on, the same (?) configuration isn't having any effect:

How is this supposed to work?
Answer: Okay. I'm starting to realize that digging into the Factory Ensembles (and blocks) is probably the best way to figure out how Reaktor works.
I opened up Carbon, Kaleidon and Nanowave and it was pretty overwhelming. However Nanowave has a pretty simple implementation of an LFO in it's waves module:

Through which I saw that it's (more complex) LFO receives the gate input, and is previous to the oscillator, with output feeding into the Linear Amplitude input on the oscillator.
I briefly experimented with pasting that module itself into my project, but for now am just using the basic approach, here in the MVP:

And here in the little noise module:

Using LFO to Control Amplitude