Name of a particular probability distribution

Question: Suppose the probability mass function $\{p_n\}_{n \geq 0}$ takes the form
\begin{equation}\label{eq:p*n_example}
p_n = \left\{
    \begin{array}{ll}
     n\,p_0\,r^n, & \quad \text{if}~ n \geq 1,\\
     p_0, &\quad \text{if}~ n = 0
    \end{array}
  \right.
\end{equation}
for some $0 < r < 1$. May I know is there any "standard name" for such (discrete) probability distribution?
Comment: Hello, you clearly forgot the factor $n$ in front of the $p_n\,r^n$  term
Comment: Geometric distribution. You can write it as $p_n = r(1 - r)^n $, for $n = 0, 1, 2, ...$
Comment: Sorry, long day xD So it looks like kind of modified geometric distribution anyway.
Comment: Of course I know this distribution is some sort of modification of the famous geometric distribution, that's why I am asking if there is any "standard name" to which I can refer this distribution...
Comment: Shifted geometric distribution?
Comment: Hello, I disagree. I am asking if there is any "standard name" for that...
Comment: Maybe a specific zero-inflated ${}_1F_0$ distribution, though I doubt there's anything standard about that.
Answer: This distribution does not have a special name but it can be related back to known distributions.
Let $Z\sim\operatorname{Bernoulli}(p_1)$ with
$$
p_1=\frac{\frac{r}{(1-r)^2}}{1+\frac{r}{(1-r)^2}}
$$
and $X\sim\operatorname{NegativeBinomial}(2,1-r)$ be independent Bernoulli and negative binomial random variables. Now define
$$
W=Z(X+1).
$$
Now notice that
$$
\mathsf P(W=0)=\mathsf P(Z=0)=1-p_1=\frac{1}{1+\frac{r}{(1-r)^2}}.
$$
Likewise, for $n=1,2,\dots$
$$
\begin{aligned}
\mathsf P(W=n)
&=\mathsf P(Z=1\cap X=n-1)\\
&=\mathsf P(Z=1)\mathsf P(X+1=n)\\
&=\frac{\frac{r}{(1-r)^2}}{1+\frac{r}{(1-r)^2}}nr^n.
\end{aligned}
$$
Thus
$$
\mathsf P(W=n)=
\begin{cases}
1-p_1, &n=0\\
p_1nr^n, &n\geq 1,
\end{cases}
$$
which is the distribution in question.
Comment: Ok, so this distribution car arise from a product random variable.... But still, maybe there is no "standard name" for such a distribution... Also I believe your computation is problematic. For instance, for $n = 4$ the probability $\mathbb{P}(W = 4)$ should contain the term $\mathbb{P}(Z =2)\cdot \mathbb{P}(X = 1)$ as well.
Comment: Not quite.  $P(W=4)=P(Z=1)P(X+1=4)$ since $Z$ can only take on values of zero and one.
Comment: @MathandYuGiOhlover In this case, the distributiondoesn't have it's own name but it can be related back to distributions with known names.


Is value of $\alpha$ defined?

Question: Consider three quadratic functions:
$$P_1(x)=ax^2-bx-c$$
$$P_2(x)=bx^2-cx-a$$
$$P_3(x)=cx^2-ax-b$$ Where $a,b,c \in \mathbb{R}\backslash \left\{0\right\}$
If there exists real number $\alpha$ such that
$$P_1(\alpha)=P_2(\alpha)=P_3(\alpha)$$
Prove that $a=b=c$
My Try:
Using $$P_1(\alpha)=P_2(\alpha)=P_3(\alpha)$$
 we get
$$(a-b)\alpha^2-(b-c)\alpha-(c-a)=0 \tag{1}$$
$$(b-c)\alpha^2-(c-a)\alpha-(a-b)=0 \tag{2}$$
$$(c-a)\alpha^2-(a-b)\alpha-(b-c)=0 \tag{3}$$
Letting $p=a-b$,$q=b-c$ and $r=c-a$ we get the above three equations as:
$$p\alpha^2-q\alpha-r=0$$
$$q\alpha^2-r\alpha-p=0$$
$$r\alpha^2-p\alpha-q=0$$
Using $p+q+r=0$ and Eliminating $\alpha$ from last two equations above we get:
$$\alpha=\frac{p^2+pr+r^2}{p^2+pr+r^2}=1 \tag{4}$$
Substituting $\alpha=1$ we get:
$$p-q-r=0$$
$\implies$
$$p=0$$
Similarly $$q=r=0$$
But $p=r=0$ is contradicting the result in $(4)$
So is $\alpha=1$ or $\alpha$ is not defined?
Comment: If $p^2+pr+r^2=0$ then the deduction of $(4)$ is unjustified.  There is no contradiction.
Comment: But without $\alpha=1$ we cannot prove $a=b=c$
Comment: Actually you cannot prove that $\alpha =1$. For example, $(a,b,c, \alpha ) = (2,2,2,3)$ satisfies your hypothesis, and $\alpha \neq 1$. In other words, your proof cannot use in any way the statement "$\alpha = 1$": if you use it, then the proof is uncorrect.
Answer: The result in (4) is only valid if $p^2+pr+r^2\neq 0$, so that you can divide by it.  So there is no issue with reaching a contradiction from (4); that just is a proof by contradiction that $p^2+pr+r^2=0$.  (Actually, there is no problem reaching a contradiction even without this comment, since that would just prove the hypotheses are impossible and so the conclusion $a=b=c$ is vacuously true.)
To complete your solution, then, you just have to prove that $a=b=c$ if $p^2+pr+r^2=0$.  This is easy: $p^2+pr+r^2=0$ for real $p,r$ implies $p=r=0$ (if $p\neq 0$ you can divide by $p^2$ and find that $r/p$ is nonreal, and similarly if $r\neq 0$).  This then gives $a=b=c$.
Comment: If $p \ne 0$ we get $\alpha =1$ which again substituting in $p\alpha^2-q\alpha-r=0$ is giving $p=0$ right?
Answer: Your main error occurred while eliminating $\alpha^2$ from equations
$q\alpha^2-r\alpha-p=0$ and $r\alpha^2-p\alpha-q=0$.
Reason:
Once you eliminate $\alpha^2$ we get
$$(r^2-pq)\alpha=p^2-qr$$
Here actually you have taken the term $r^2-pq$ to the denominator without knowing its non zero nature.
Now here is the solution:
In case $r^2-pq=0$ we get $p^2+pr+r^2=0$, But since $p,r$ are reals, this gives $p=0=r$ and so $q=0$ too.
So your equation $(4)$ has no meaning, that means for any $\alpha$ its always true that
$$(r^2-pq)\alpha=p^2-qr$$
Now in case $r^2-pq \ne 0$, then as you pointed out $\alpha=1$, which gives again $p=q=r=0$ which is contradicting $r^2-pq \ne 0$, hence $r^2-pq$ should be zero.
So finally $r^2-pq=0$ which gives $p=q=r=0$ which implies $a=b=c$ for any $\alpha$.
So essentially value of $\alpha$ is irrelevant here.

Is value of $\alpha$ defined?


Formatting a float value

Question: In my IPhone App Development, I'm using a timestamp value for an order id value.
I want to format the timestamp value in such a way that it contains only decimal value.
Like
timestamp value= 343434234.78900633
Now I want to format that time stamp value, so that it returns the decimal value 78900633.
Answer: You need to use the modf function that breaks a double/float into an int an a fraction.
double intpart;
double param = 343434234.78900633;
double fractpart = modf (param , &intpart);
printf ("%lf = %lf + %lf \n", param, intpart, fractpart);

char buf[32];
sprintf(buf, "%f", fractpart);
int fpart = atoi(buf+2);
printf("Fractional as int = %d\n", fpart);

Comment: That doesn't make any sense.  The fractional part has a variable number of significant digits.  If the time were 343434234.27, would you want 27 or 27000000 or what?  Are you just looking for the number of nanoseconds or something?
Comment: @prasad1250 Good point - I edited the answer; it should be a `double`.
Comment: Thanx very much.

But, what value should I specify for intpart.
Comment: well, i just need the fractional part for a given time stamp value.
Comment: @prasad1250 Since it's a fractional part, you can add as many zeros as you please: `1.78900633` is the same as `1.7890063300000`, but of course `78900633` is not the same as `7890063300000`. If you need, say, 10 digits, simply multiply the fraction by `10000000000` (ten to the power that is equal the number of digits you want), and assign the result to an integral (`int` or `long long`) variable.
Comment: Heyy.I think u didn't got my problem..I'm not worried about the number of digits in the fractional part . Suppose, I have a value 4567.8989898, so my output should be 8989898 (any no of digits). Right now, i'm getting value something like .8989898.
Comment: @prasad1250 It does not make much sense to produce a number like that, because the results cannot be even compared directly without reinterpretation (e.g. `0.95` becomes `95`, while `0.10003` becomes `10003`, i.e. a smaller number becomes much bigger after the transformation). If you insist on making it happen, take a look at the edit, it should do the trick.

Formatting a float value


How to implement a horizontal set of translation links for every node?

Question: I want to add a hardcoded translation block to my page.tpl.php, to link to a translated version of every node + a translated interface.
The Language Switcher Dropdown module did the trick, but I want a horizontal set of links and need something simpler.
Answer: Maybe Displaying and configuring a drop down using Language Switcher Dropdown helps to achieve what you're trying to do with this module anyhow.
If not then the answers to the question about How to theme language translation links in Drupal? may help to actually answer your qestion. Though that question is for D6, and hence its answers might need some review to also make it work in D7. Here is the relevant part of it that might do the trick:
$node = menu_get_object();
if ($node->links) {
  print theme('links', $node->links);
  }

Comment: The problem is that I do not want a drop down list. I have been trying to modify the code of the dropdown module, but I think this is innecessarily complex.   Trying the print theme solution, I get: Notice: Trying to get property of non-object


Qual "status code" usar quando não há um um dado no corpo de uma requisição POST?

Question: Estou criando uma aplicação para o cliente realizar o upload de um arquivo para o servidor e eu gostaria de saber qual o Status Code ideal para retornar caso na requisição o arquivo ou qualquer outro dado importante não seja enviado no body.
Veja esse exemplo abaixo:
{dado1: "3457", dado2: "0110xFC"} // Status Code: 200  (todos os dados são enviados)

{dado1: "3457"} // Status Code: ??? (faltou enviar o segundo dado)

Comment: `{dado:[{dado1:"3457", dado2:'0110xFC'}]}` Será tratar o Objeto +- desta maneira? Apenas estou usando a lógica, realmente não sou o "programador" quando se trata de JavaScript.
Answer: Se fez um request que não está válido, a reposta é do grupo 4xx.
Pode por exemplo ser um 400 "Bad request", ou  "Request inválido".
Mais detalhes dos erros 4xx podem ser vistos aqui: https://restfulapi.net/http-status-codes/


Proof of Jordan-Holder theorem

Question: I am trying to prove the following:

Let $G$ be a finite non-trivial group with the following two composition series:
  $$ \{e\} = M_0 \triangleleft M_1 \triangleleft M_2 = G $$ $$ \{e\} = N_0 \triangleleft N_1 \triangleleft \cdots \triangleleft N_r = G. $$ Prove that $r = 2$ and that $G/M_1 \cong G/N_1$ and $N_1/N_0 \cong M_1/M_0$.

I know that if $r < 2$ we have a contradiction since $G$ is non-trivial and not simple (since $M_1 \triangleleft G$). However, I am having a hard time writing down a contradiction for when $r > 2$. We know that $N_{r-1} \triangleleft G$ and $G/N_{r-1}$ is simple, but how can I use the fact that $M_1$ and $G/M_1$ are simple? By the second isomorphism theorem I know that $M_1N_2/N_2 \cong M_1/(N_2\cap M_1)$, which means $N_2\cap M_1 = \{e\} $ or $N_2\cap M_1 = M_1$, since $M_1$ is simple. Can we also conclude, by the second isomorphism theorem, that $$N_2/(N_2\cap M_1) \cong N_2M_1/M_1 \cong G/M_1.$$ So if $N_2\cap M_1 = \{e\}$ then $ G/M_1 \cong N_2/(N_2\cap M_1) \cong N_2$ is simple, which is a contradiction since $\{e\} \ne N_1 \triangleleft N_2$? The part I am confused about is showing $N_2M_1/M_1 \cong G/M_1$. It feels like it should be true since $N_2$ and $M_1$ are maximal, but I don't have a good way of writing it down.
Answer: Let $p_2:G\rightarrow G/M_2$ be the projection, $p_2(N_r)$ is normal since $N_r$ is normal, we deduce that $p_2(N_r)=1, N_r\subset M_2$, since $G/N_r$ is simple, $q_r(M_2)=1$ where $q_r:G\rightarrow G/N_r$ is the natural projection, $M_2\subset N_r$, henceforth, $M_2=N_r$.
Apply the same argument to show that $N_{r-1}=M_1$ and $M_0=N_{r-2}$, and deduce $r=2$ since $M_0$ is simple.

Proof of Jordan-Holder theorem


Matlab 3D plots

Question: I am currently in high school and is writing a maths research paper on a calculus problem. In the conclusion, I would like to include a 3D plot of a function I found. It goes something like this:
a, b, are constants and m is the first positive solution to the equation.
So far I have Matlab available though I've never used it before. Just looking for some pointers into how would I plot this function.
Answer: First, before seeking help, you should provide some demonstration of how you'd like to approach the problem. In this case, what are some valid techniques you can use? The function appears at first glance to not be continuous and will have a lot of jumps.
Graphing in Matlab is pretty easy, so once you come back with a strategy of what you'd like to graph and how to graph it, we could graph it for you. Good luck
Comment: Hi, thank you for the reply.
That function is not my actual function that I wanted to plot. Could you please elaborate on what you mean by 'valid techniques'? Here's the function: [link](http://i.imgur.com/AgaifDH.png)
Answer: When @bloodtypebpos uses the term "strategy", he may think the same thing as me; the most important feature of your problem is that you have a transcendental equation to solve many times (first strictly positive root of $t-tan(t)=a$ in order to get $t=f(a)$). The main idea, for an efficient programming, is to tabulate first (using matlab's "fsolve") the values of this function $f$ with a reasonable degree of accuracy and on a reasonable range. Then use this table whenever you need a value. Plotting is definitely not the problem...

Matlab 3D plots


Find a function so that for integer $k>1$ and $\lambda>0$: $ \sum_{t=0}^{\infty} h(t) \frac{e^{-n\lambda}(n\lambda)^t}{t!}=\lambda^k, $

Question: If I want to find a function $h(\cdot): \mathbb R\to \mathbb R$ so that for integer $k>1$ and $\lambda>0$:
$$
\sum_{t=0}^{\infty} h(t) \frac{e^{-n\lambda}(n\lambda)^t}{t!}=\lambda^k,
$$
The answer is that $h(t)=t(t-1)\cdots (t-k+1)/n^k$. But I have no idea how to get this and I got a different result: note that this is same as
$$
\sum_{t=0}^{\infty} h(t)\lambda^{-k} \frac{e^{-n\lambda}(n\lambda)^t}{t!}=1
$$
Since we have
$$
\sum_{t=0}^{\infty}\frac{e^{-n\lambda}(n\lambda)^t}{t!}=1,
$$
then we can just take
$$
h(t)\lambda^{-k}=1
$$
That means $h(t)=\lambda^k$... Where am I wrong?
Comment: $$
\lambda ^k {\rm e}^{n\lambda }  = \frac{{{\rm d}^k {\rm e}^{n\lambda } }}{{{\rm d}n^k }} = \frac{{{\rm d}^k }}{{{\rm d}n^k }}\sum\limits_{t = 0}^\infty  {\frac{{(n\lambda )^t }}{{t!}}}  = \sum\limits_{t = 0}^\infty  {\frac{{{\rm d}^k }}{{{\rm d}n^k }}\frac{{(n\lambda )^t }}{{t!}}}  = \sum\limits_{t = 0}^\infty  {\frac{{t(t - 1) \cdots (t - k + 1)}}{{n^k }}\frac{{(n\lambda )^t }}{{t!}}}
$$
Comment: Then $$
\sum\limits_{t = 0}^\infty  {\frac{{t(t - 1) \cdots (t - k + 1)}}{{n^k }}\frac{{(n\lambda )^t }}{{t!}}}  = \lambda ^k \sum\limits_{t = k}^\infty  {\frac{{(n\lambda )^{t - k} }}{{(t - k)!}}}  = \sum\limits_{t = 0}^\infty  {\lambda ^k \frac{{(n\lambda )^t }}{{t!}}}
$$
Comment: The  set of acceptable $h$ is enormous and you have exhibited two simple examples....
Answer: You have
$$\sum_{t=0}^{\infty} h(t) \frac{e^{-n\lambda}(n\lambda)^t}{t!}=\lambda^k$$
Or, $$\sum_{t=0}^{\infty} \frac{h(t) n^t}{t!}\lambda^t=\color{blue}{e^{n\lambda}}\lambda^k=\color{blue}{\sum_{j=0}^\infty \frac{(n\lambda)^j}{j!}}\lambda^k=\sum_{j=0}^\infty \frac{n^j}{j!}\lambda^{j+k}$$
That is,
$$\sum_{t=0}^{\infty} \frac{h(t) n^t}{t!}\lambda^t=\sum_{t=k}^\infty \frac{n^{t-k}}{(t-k)!}\lambda^t$$
Comparing coefficients of $\lambda^t$ on both sides, you get
$$h(t)=\begin{cases}
\frac{t!}{n^t}\cdot\frac{n^{t-k}}{(t-k)!}&,\text{ if }t\ge k
\\ 0 &,\text{ else }
\end{cases}$$
Or,
$$h(t)=\frac{t!}{n^k(t-k)!}\mathbf1_{\{t\ge k\}}=\frac{t(t-1)(t-2)\cdots(t-k+1)}{n^k}\mathbf1_{\{t\ge k\}}$$
This is just one way of finding the best unbiased estimator of $\lambda^k$ when $X_1,X_2,\ldots,X_n$ are i.i.d $\text{Poisson}(\lambda)$. There are other ways of course, like using the Rao-Blackwell theorem.
Comment: https://math.stackexchange.com/q/1794929?rq=1


What is $\operatorname{ord}_{22}(5^6)$?

Question:
Find $\operatorname{ord}_{22}(5^6)$.

So, basically we want to find:$$\operatorname*{arg\,min}_k 5^{6k} \equiv 1\pmod {22}$$
I found that $5^5 \equiv 1\pmod {22}$ so I know that for $k=5$ we have $5^{6k} \equiv 1 \pmod {22}$. Therefore, $\text{ord}(5^6) \le 5$.
I guess that I could proceed with the somewhat tedious checking:

$k=4$: $(5^6)^4 \equiv (5^4)^6 \equiv 5^4 \equiv 9 \pmod {22}$
$k=3$  $(5^6)^3 \equiv (5^3)^6 \equiv 5^3 \equiv 15 \pmod {22}$
$k=2$  $(5^6)^2 \equiv (5^2)^6 \equiv 5^2 \equiv 3 \pmod {22}$
$k=1$  $(5^6)^1 \equiv (5^1)^6 \equiv 5 \pmod {22}$

So $\text{ord}_{22}(5^6) = 5$.
Questions:

Is that what I'm expected to do? Or is there a simpler way? (I had to use a calculator or to tediously calculate it myself)
Why can we get rid of the exponent when we do modular arithmetic? (I actually used it along the proof) i.e. $$x \equiv a \pmod m \iff x^b \equiv a \pmod m$$
Comment: When you found $5^5\equiv 1\pmod{22}$ you could have noted that $5^6\equiv5\pmod{22}$ so  that $\text{ord}_{22}(5^6)=\text{ord}_{22}(5)$. Then since $5^5\equiv1\pmod{22}$, the order is either $1$ or $5$, and it's not $5$.
Comment: It should be `\operatorname{ord}` rather than `\text{ord}` and `\operatorname*{arg\,min}_k` rather than `\arg\min_k`
Comment: okay, I'll edit accordingly
Answer: You have found that $5^5 \equiv 1 \pmod {22}$. So as $5^6 \equiv 5 \pmod {22}$. Then we must have $\text{ord}(5^6) = \text{ord}(5)$. But from the first equation we have that $\text{ord}(5) \mid 5$ and as $5$ is prime and $5^1 \not \equiv 1 \pmod {22}$ we must have that $\text{ord}(5^6) = \text{ord}(5) = 5$

Note that we used the fact that if $a^{k} \equiv 1\pmod {p}$, then $\text{ord}_p(a) \mid k$. This can be easily proven by the Division Algorithm. Let $k = \text{ord}_p(a)\cdot m + r$, where $0 \le r < \text{ord}_p(a)$. Then:
$$1 \equiv a^k \equiv (a^{\text{ord}_p(a)})^m \cdot a^r \equiv a^r \pmod {p} $$
So $r=0$, as $\text{ord}_p(a)$ is the smallest positive integer $t$ s.t. $a^t \equiv 1 \pmod {p}$ by definition
Comment: Thank you and thanks all for helping!
Answer: First observe that
\begin{eqnarray*}
5^6 \equiv 5 \pmod{22}.
\end{eqnarray*}
So we only need to calculate powers of $5$ modulo $22$, they are $5,3,15,9,1$ (by tedious calculation), the minimal value of $k$ is $\color{red}{5}$.
Answer: By the Chinese remainder theorem, it is enough to find the order of $5^6$ $\!\!\pmod{2}$ (which is obviously $1$) and the order of $5^6\equiv5$ $\!\!\pmod{11}$. Since $5$ is a quadratic residue $\!\!\pmod{11}$, due to
$$\left(\frac{5}{11}\right)=\left(\frac{11}{5}\right)=\left(\frac{1}{5}\right)=1$$
the order of $5\pmod{11}$ is five and that is also the order of $5^6\pmod{22}$.

What is $\operatorname{ord}_{22}(5^6)$?


Space of continuous functions linear operator eigenvalues

Question: Let $V$ be the vector space of continuous functions from $\mathbb R$ to $\mathbb R$. Let $T$ be the linear operator on $V$ defined as $$(Tf)(x)=\int_0^x f(t)\,dt$$
Prove that $T$ doesn't have eigenvalues.
I want to show that it doesn't exist any continuous function $f \neq 0$ with $$(1) \space \int_0^x f(t)\,dt=\lambda f(x), \space \text{for some} \space\lambda \space\text{and for all }x \in \mathbb R $$
So suppose it does, then $\lambda f(0)=\int_0^0f(t)\,dt=0$, from here it follows $f(0)=0$. From equation (1) we also arrive to the inequality $$\lambda|f(x)| \leq |x|\max |f(t)|$$
where $\max |f(t)|$ is the maximum the function attains on the $[0,x]$ or $[x,0]$ respectively.
I would like to arrive to an absurd but I couldn't, any hints or suggestions would be greatly appreciated.
Answer: It follows from your equation (1) that $f$ is differentiable and
$f(x) = \lambda f'(x)$ for all $x \in \mathbb R$. The general solution of
this differential equation is $f(x) = C \exp(x/\lambda)$ for some $C \in \mathbb R$.
Since $f(0) = 0$, $f$ is identically zero.


Grails "One to Many" relationship without a table join

Question: I'm new to Grails and GORM and I try to implement a "One to Many" relationship.
I tried the example in the doc :
class Book {
    String title
}
class Author {
    static hasMany = [books: Book]
    String name
}

Here are the tables that are generated :
AUTHOR
- Id (PK)
- Name

BOOK
- Id (PK)
- Title

AUTHOR_BOOK
- Author_Books_Id
- Book_Id

I was expecting something more like :
AUTHOR
- Id (PK)
- Name

BOOK
- Author_Id (PK)
- Book_Index (PK)
- Title

Is there a way to achieve this (get rid of the join table) ?
Answer: You should declare that Book belongs to Author. With belongsTo you declare that there is foreign key in a Book table that keeps reference to Author's id column. Like this:
class Book {
    String title
    static belongsTo = [author: Author]
}

class Author {
    static hasMany = [books: Book]
    String name
}

Answer: class Book {
String title
static belongsTo = [author: Author]
}
class Author {
static hasMany = [books: Book]
String name
}
Answer: Just do it the other way around.
A Book has an Author.
class Book {
    String title
    Author author
}

class Author {
    String name
}


Tiktok authentication for using api

Question: Can anybody tell me that is it necessary that tiktok webapp should be approved for getting access token cuz my app is under reviewed and when I go to authentication page for callback authorization after login it is showing error
I followed all the instructions that were given in there documentation but i am stucked at the call back authorization
Answer: The status of your app should be Live in production. They usually give you feedback if there are any issues and in case it's declined. You have to make fixes accordingly to get the API functionality to work.
The reviewal process shouldn't take longer than 3 working days.

Tiktok authentication for using api


Giving a default value to a password element in D7 form API?

Question: I wrote a custom feeds fetcher class that does an authentication call before it gets the feed. In its settings, I have username and password fields in the form. I tried to set the field #type to password, but it seemed not to use the #default_value element, thus obliterating the saved password when you hit the 'save' button.
This maintains the password, but shows it in plaintext:
$form['password'] = array(
  '#type' => 'textfield',
  '#title' => t('Password'),
  '#description' => t(''),
  '#default_value' => $this->config['password'],
);

This shows dots for the password, but does not populate the field using the #default_value, causing you to have to enter the password any time you want to change and save any value on the form:
$form['password'] = array(
  '#type' => 'password',
  '#title' => t('Password'),
  '#description' => t(''),
  '#default_value' => $this->config['password'],
);

I need to be able to have the user enter a password and have it stay no matter what other values they change on the form and save. Does this preclude me from using the password field type, since it appears not to use the #default_value element?
Answer: You can try to add your default value directly with #attributes option just like that :
$form['password'] = array(
  '#type' => 'password',
  '#title' => t('Password'),
  '#description' => t(''),
  '#attributes' => array('value' => $this->config['password']),
);

After I'm not sure if you will be able to get that value on validate and submitcallback, you should check.
Answer: This is a pretty common use-case, but you wouldn't want to re-expose the password to the client at any point by setting a password field's default value. So either the user can change a password by updating the password input, or leave it unchanged by leaving the field blank.
To implement this in code, you can add another submit handler to your form:
$form['password'] = array(
    '#type' => 'password',
    '#title' => t('Password'),
    '#description' => t(''),
);

$form['#submit'] = array_merge(array('my_default_password'), (array) $form['#submit']);

And in this handler, put the password back in:
function my_default_password($form, &$form_state) {
    if (empty($form_state['values']['password'])) {
        $form_state['values']['password'] = variable_get('the_password');
    }
}

This way you don't have to expose the existing password to the user, which wouldn't be considered a good security practice, but you also get the expected workflow.
Note that I assumed the default password is stored in 'the_password' variable, but your code likely would have it elsewhere.
Answer: A password field can't have a default value, that makes no sense. It would be written in plaintext in the attribute so all that password specific stuff would be pointless (*, copy-protection, ...).
Either use a normal textfield with a default value (that's what most of those forms do I think) or leave it empty, add some special code to only overwrite the existing value if not empty and add a corresponding description.
Comment: > A password field can't have a default value, that makes no sense. Password tags with default values are perfectly valid X?HTML. It may make no sense to you, but it may be useful to others. The point is: we (i.e. Drupal and framework developers in general) should not try to dictate what is good or bad to other developers, by crippling our interfaces, just because something does not smell good to you personally. Maybe you should write to the W3C and ask them to forbid default values for password fields in the next revision of the X?HTML DTD. But in the meantime, there's no excuses to prevent t
Answer: I was able to accomplish this with validation and hook_update_N. In my case, I had a settings page with a few form elements, one of them being a password field. If they filled out other settings, but not the password and clicked Save, it would set the password to a blank string.
In my case, I validated the form like this in mymodule.module:
<?php

function mymodule_form_callback($form, &$form_state) {
  $form = array();
  // code for other elements here...
  $form['my_password_field'] = array(
    '#type' => 'password_confirm',
    '#title' => t('Enter password'),
  );
  return $form;
}

function mymodule_form_callback_validate($form, &$form_state) {
  if (empty($form_state['values']['my_password_field'])) {
    $form_state['values']['my_password_field'] = variable_get('my_password_field');
  }
}

Then created a default value in mymodule.install:
<?php

function mymodule_update_7001() {
  variable_set('my_password_field', 'Jabron1jabroni');
}

To get this default to be set initially, you have to run Drupal updates in the UI or with drush updb -y if you use Drush.


scp to google cloud-shell fails (ssh works)

Question: I'm trying to use scp to copy a large file over to cloud shell.
Using the suggested command from this SO answer
gcloud alpha cloud-shell scp \
  localhost:~/Sites/my-app/big_file cloudshell:~/big_file

But even though I can see it adding a key for the server, it fails with Permission denied (publickey).
If I do
gcloud alpha cloud-shell ssh

it logs in to the server just fine
Answer: Turns out google's invocation of scp was omitting the correct username.
Solution
I successfully uploaded by doing
/usr/bin/scp -P 6000 -i /Users/me/.ssh/google_compute_engine -o \
  StrictHostKeyChecking=no ~/Sites/my-app/bigfile \
  email@example.com:~/big_file

How to figure this out
I was able to discover this using the --verbosity debug flag
# gcloud alpha cloud-shell scp --verbosity debug localhost:~/Sites/my-app/big_file cloudshell:~/big_file
    DEBUG: Running [gcloud.alpha.cloud-shell.scp] with arguments: [(cloudshell|localhost):DEST: "cloudshell:~/big_file", (cloudshell|localhost):SRC:1: "['localhost:~/Sites/my-app/big_file']", --verbosity: "debug"]
    DEBUG: Running command [/usr/bin/scp -P 6000
      -i /Users/chrisjensen/.ssh/google_compute_engine
      -o StrictHostKeyChecking=no
      ~/Sites/my-app/big_file 184.108.40.206:~/big_file].
[...more debug info...]

^ This is the line that shows the command that was run
Then I ran ssh to see if there was a difference in the arguments
gcloud alpha cloud-shell ssh --verbosity debug
DEBUG: Running [gcloud.alpha.cloud-shell.ssh] with arguments: [--verbosity: "debug"]
DEBUG: Running command [/usr/bin/ssh -t -p 6000
  -i /Users/chrisjensen/.ssh/google_compute_engine
  -o StrictHostKeyChecking=no firstname.lastname@example.com].
[...more debug info...]

^ Notice it prepends by username to the server ip.
So then I copied the scp command and added my username, and it worked a charm.
Hope this helps others trying to figure this out.
Answer: This should be fixed in the latest version of gcloud, which you can get by runnign gcloud components update. Thanks for trying the alpha!


Check that a users authentication is valid

Question: So I have the following function I'm using to try and connect the IBM Connections:
<code>private boolean checkCredentials(String username, String password){
    // Connect to IBM Connections
    HttpClient client = new HttpClient();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
    AuthScope authscope = new AuthScope("w3-connections.ibm.com", AuthScope.ANY_PORT, AuthScope.ANY_REALM);
    client.getState().setCredentials(authscope, credentials);
}
</code>
But I have no way of knowing if the user gets signed in or not. from what I can tell there is no difference when you give valid or invalid credentials.
The ONLY way I've found is doing a post request, but that doesn't work as I'd end up creating a useless thread or reply.
Any ideas?
Answer: You should make a call (GET) to /forums/atom/topics/my  you'll get the service doc back, the service document will include user details if the credentials are correct.  if they are wrong you'll get a 401 error code if not able to read the forum You can read more about the service doc at http://www-10.lotus.com/ldd/appdevwiki.nsf/xpAPIViewer.xsp?lookupName=API+Reference#action=openDocument&res_title=Getting_the_My_Topics_feed_ic50&content=apicontent
Comment: Ohh wow, thought this question was a longshot! I'll try that out in a sec. Thank you!


Best Way to Build a Second Bridge

Question: I'm considering building a secondary bridge to insert into a guitar much like a Koto bridge. This is a good example of what I mean(notice the piece of wood that is around the 14th fret). What are some considerations I keep in mind when building one?
I'm thinking of using a decent maple wood but besides that am clueless on best dimensions, etc. Should I try to design a plastic piece for the top of the bridge that touches the strings or is wood on string fine?
Also are there any decent tunings that people have found success in when playing with this second bridge?
Answer: I have never seen anything like that, very cool.
As for the material, I wouldn't use wood, use something harder and with a lower coefficient of friction eg nut or saddle materials such as corian, bone, brass, or some fret wire etc. I recommend black TUSQ XL
http://www.graphtech.com/products/product-categories/acoustic-saddles
As you need to tune both sides of the 'middle bridge' there will be string movement across it and with the significant break angle minimizing friction and wear will be important. As there's no fretting involved presumably you would retune often to get a variation of intervals and available harmony so material choice is important.
I would try making some that sit on the fingerboard (like in the vid) and some that sit on the sound board, I think the later would give better volume. Be aware the soundboard will withstand much less pressure than the FB so bake the contact area larger to lower the pressure.
As for dimensions, I'd just go off whats in the video and work from there (looks 15-20mm to me) there's no big investment so why not make a few and see what you like best. The taller it is the more pressure will be on the FB/SB which may increase volume for the headstock end and improve overall tone but also risks damaging your guitar.
As for tuning I think it's E A C E G A on the body side and A D F A C D on the neck side.
So with the bridge where it is in the vid. the body side is a 5th higher than the neck side. its a nice Am type tuning, if you adjust two strings you'll get an A major tuning:
EAC#EF#A on the soundhole side and ADF#ABD on the headstock side.
As for other tunings, you're limited to only use notes where the complimentary note on the other side of the bridge is also in the key you want. e.g. you may want to have a B when in Am but you may end up with an F# on the other side which you may not want as it's the major 6 not the minor 6 most commonly found in minor keys.
Comment: Excellent answer. I'll take a look at getting a saddle and working from there.

Best Way to Build a Second Bridge


Find general equation for the following sequence

Question: Given the following sequence: $$a_1 = 1, a_{n+1}=2*a_{n} + 1$$
what is the general equation for $a_n$?
I couldn't find it because the sequence is not in the form of $a_{n+1} = a_n * c$ neither is it
in the form of $a_{n+1} = a_n + c$, but more like a combination of the two.
Comment: @CalvinLin I am sorry, someone edited my question and misinterpreted my equation. I have fixed it now.
Comment: A) Are you familiar with recurrence relations and characteristic equations? B) Alternatively, how about induction? C) Can you list out some initial values to make a guess at the form?
Answer: Hint:$a_1 = 1, a _ 2 = 3, a_3 = 7, a_4 = 15, a_5 = 31$.
What does this sequence look like? Can you guess the form?
Can you prove this is the equation for $a_n$ via induction?

If you are still stuck, write down what you've tried and where you're stuck at.
Comment: seems like 2^n - 1? But how can I prove it? This is part of an algorithm that later need to be proven
Comment: @avivgood2 Did you read the last line? Or questions A and B in my comment above?
Comment: induction seems like an efficient method for this problem. I will try it
Answer: $$
\begin{align}
a_{n+1} &= 2a_{n} + 1 = 2(2a_{n-1}+1) + 1 \\
&= 4a_{n-1} + 2 + 1 = 4(2a_{n-2} + 1) + 2 + 1 \\
&= 8a_{n-2} + 4 + 2 + 1 = ... \\
&= 2^na_1 + \sum\limits_{k=0}^{n-1} 2^k
\end{align}
$$
Using the formula for the geometric series and using the fact that $a_1 = 1$, we are able to obtain:
$$
\begin{align}
a_{n+1} = 2^na_1 + \sum\limits_{k=0}^{n-1} 2^k = 2^na_1 + 2^n-1 = 2^{n+1}-1
\end{align}
$$
Answer: $$a_1 = 1, a_{n+1}=2a_{n} + 1\tag{1}$$
Substitute $n$ with $n+1$
$$a_{n+2}=2a_{n+1}+1;\;a_2=2a_1+1=2+1=3\tag{2}$$
Subtract $(2)-(1)$
$$a_{n+2}-a_{n+1}=2a_{n+1}+1-(2a_{n} + 1)$$
$$a_{n+2}-3a_{n+1}+2a_n=0;\;a_1=1;\;a_2=3$$
solve
$$\lambda^2-3\lambda+2=0\to \lambda=1;\;\lambda=2$$
solutions have the form
$$a_n=a\cdot 1^n+b\cdot 2^n$$
plug the index $n=1,n=2$. Get the system
$$
\begin{cases}
a+2b=1\\
a+4b=3\\
\end{cases}
$$
$a=-1;\;b=1$ is the solution, so the solution of the recurrence is
$$a_n=2^n-1$$
Answer: $$a_{n+1}+1=2(a_n+1) \implies a_n+1=2^{n-1}(a_1+1)=2^n \implies a_n=2^n-1$$
It works for any $a_{n+1} = ka_n+b$.
Answer: Just another way to solve
$$a_{n+1}=2\,a_{n} + 1$$
Let $a_n=n_n+k$ and replace
$$b_{n+1}+k=2\,b_{n} +2k+ 1$$ If you make $k=2k+1$, that is to say $k=-1$ you have
$$b_{n+1}=2\,b_{n}$$
Solve it and, when done, go back to $a_n$.


Event registration for events with multiple dates/places

Question: I'm making a event content type (representing academic conferences) for a Drupal 7 site, and I'm thinking of give visitors the posibility of registering in these events.  But in some cases, these conferences can occur several times, in different dates and places. When registering, the registrant must choose in which date/place he wants to go.
For now, the date/place pairs are being stored in the event via a Field Collection. I've also checked two common modules for registrations in D7: Node Registration and Entity Registration.
Right now I'm thinking in 2 alternatives to implement this:

Several registrations forms per event, one for each date/place:
Pros:

I could (in theory) manage each presentation separately, with different capacity/end of registration date.

Cons:

As now, I don't find a module that permits multiple registrations in a node. (custom code?)

One registration form per event, with a list field that permits to choose the date/place
Pros:

Implementable right now through Node Registration module + private fields per node

Cons:

I can't manage capacity/end of registration date separately, and when the end date of one presentation comes, I must update the list field manually (custom code?)
The list options are defined per field (not by field instance) so I have to create a new field on each event that has multiple dates/places (each one with different machine name. Consider this is going to be done not by site admins, but event organizators with its own user role)

Is there another way to implement this feature? An module I haven't found? A hidden feature or creative use of Node/Event Registrations? Custom code/module?
Answer: I would suggest that you create two different content types. Event Display and Event Entity

Event Display : Will be just used as a placeholder or display item. It will contain all jazzy text fields and images. It will also contain Node References to the Actual Event Eneities.
Event Entity : This will just contain Location, Date and Capacity.

Now Enable Entity Registration for the content type Event Entity.
Suggestion : Use Inline Entity Form so that you can edit the Event Entities directly from the Event Display Content.


Is there an unpaired version of the sign test?

Question: I wasn't able to find one on Google, and was wondering if one exists...
Answer: Good (2005) defines the one-sample sign-test for the location parameter $\theta$ for a continuous symmetric variable $X$ as follows:

Take the difference $D_i$ of each observation to the location parameter $\theta_0$ under the null hypothesis.
Define an indicator variable $Z_i$ as $0$ when $D_i < 0$, and as $1$ when $D_i > 0$. Since $X$ is continuous, $P(D_i = 0) = 0$.
Calculate test statistic $T=\sum_i Z_i$.
The distribution of $T$ is is found by generating all $2^N$ possible outcomes of the $Z_i$ indicator variables (2 possibilities for each observation with equal probability $\frac{1}{2}$ under H0). This leads to the binomial distribution as in the sign test for 2 dependent samples.

The justification for step 4 is:

Suppose we had lost track of the signs
  of the deviations [...]. We could
  attach new signs at random [...]. If
  we are correct in our hypothesis that
  the variable has a symmetric
  distribution about $\theta_0$, the
  resulting values should have precisely
  the same distribution as the original
  observations. That is, the absolute
  values of the deviations are
  sufficient for regenerating the
  sample. (p34f)

I agree that this reasoning seems somewhat different from a 2-sample permutation test where you re-assign experimental conditions to observations with the justification of exchangeability under H0.
Good, P. 2005. Permutation, Parametric, and Bootstrap Tests of Hypotheses. New York: Springer.
Comment: Thank you Caracal, that was a great explanation/reference of the sign test.  I guess the answer to my question is "no"...
Comment: Update - I found that there is a relevant non parametric test - I added it as an answer.
Answer: I'm not sure if such a test can exist conceptually. The sign test uses the pairing of the data to decide whether one value is bigger than the corresponding other value. But in an unpaired situation there is nothing like a corresponding other value (every value in the other group could be a potential counterpart for comparison). Correct me please, if I'm not getting the point...
Comment: You have just described the Mann-Whitney U test!  Also, you use "every value in the other group [as] a potential counterpart for comparison" and compute the median of all such paired differences you obtain the Hodges-Lehman estimate of the difference in medians of the two datasets: http://en.wikipedia.org/wiki/Hodges%E2%80%93Lehmann_estimate
Comment: Hi psj, your answer gives a good explanation as to why I asked my question :) - exactly because I am not aware of how to generalize the sign test to unpaired data.  However, there might be a solution out there, thus my question :)
Answer: O.k,
I found that there is an unpaired solution to a sign test (A test of medians).  It is called "Median test" And you can read about it in Wikipedia.
Answer: The extension goes thorugh introducing rank to somewhat regulate the order of data and the result are Wilcoxon tests (Mann-Whitney in particular).
Comment: @mbq, @Tal The Wilxocon-Mann-Whitney test is an unpaired test based on ranks.  It has two interpretations (the Wikipedia article has a good discussion).  One of them is that it's a test of equality of *medians* relative to an alternative hypothesis that's essentially a shift of median.  BTW, the Wilcoxon test (not to be confused with the Mann-Whitney test!) is a sign test for paired data.  Is this the "Sign Test" referred to in the question?
Comment: Perhaps it's useful to distinguish the three Wilcoxon tests: 1. one-sample test: "Wilcoxon signed rank test" 2. two dependent samples -> can be reduced to 1. by taking the observation-wise difference and testing for location parameter of 0. 3. two independent samples: "Wilcoxon rank sum test". This is equivalent to the Mann-Whitney U-test: both test statistics are conceptually different but numerically identical.
Comment: @Tal Yep, your "sign test" is also known as the Wilcoxon test.  The Mann-Whitney U test is its unpaired counterpart.  The *Mann-Kendall* test is its extension to more than two sets of data.  Although it doesn't seem to be commonly known, the U statistic can be obtained as the t-statistic for the ranks of the *combined* dataset (using midranks for tied groups) and the Mann-Kendall test is really just ANOVA on the ranks of the combined data.  This insight allows you to avoid the complex formulas often cited and use simple software to do the calculations.
Comment: Thanks mbq, but that will give us a test on the rank, not on the median - wouldn't it?
Comment: @Tal Yes, but as I wrote -- this is all one can get. Yet they both answer the same holistic question "Is there a significant difference?", so both are considered nonparametric t-test variants.
Comment: Hi Whuber, this is the sign test:  http://en.wikipedia.org/wiki/Sign_test
Comment: Whuber, if I understand correctly, it can be called wilcoxon-sign-test, but not wilcoxon-sign-rank-test.  Other then that - thanks for your references - all are interesting to know.
Comment: @Tal There is a total chaos with these nomenclature; I used Wilcoxon as a keyword, since it is most common. And the whole bundle of such tests is located under `wilcox.test` function in R.


How to add ref to CSVLINK in react typescript?

Question: I want to click the CSV download link after the data loaded from the server.
I tried all the approaches from https://github.com/react-csv/react-csv/issues/237
const csvLinkRef = React.useRef<CSVLink & HTMLAnchorElement & { link?: HTMLAnchorElement }>();

<CSVLink
  ref={csvLinkRef}
  data={tableDataToDownLoadAsCSV}
/>

Answer: look at this code it will help to tweak your code
export default function dataListPage(props: DataListProps) {
const csvLinkRef = useRef<
    CSVLink & HTMLAnchorElement & { link: HTMLAnchorElement }
  >(null); // setup the ref that we'll use for the hidden CsvLink click once we've updated the data

const [data, setData] = useState<dataTypeObj[]>([]);

 const hanldeExportButton = async () => {
    const data: dataTypeObj[] = await fetchData();
    setData(data);
    csvLinkRef?.current?.link.click();
  };

 return (
<CSVLink
        data={data}
        className="exportButton"
        filename="file.csv"
        ref={csvLinkRef}
      >
      </CSVLink>
        <Button
          color="primary"
          variant="contained"
          size="small"
          startIcon={<GetAppIcon />}
          onClick={hanldeExportButton}
        >
          Export As CSV
        </Button>
        );
} //func dataListPage end


Why is this language not Regular - w^Rw (i.e. a word concat. with its reverse)?

Question: Consider the language L = {$w^R w$ | $w \in \{a,b\}^* $} - why is this not regular?
I'm very new to the idea of formal languages and computer science, so I've likely missed something basic. However, my thoughts on this are as follows - I recently learned two things relevant to my question: 1) that the concatenation of two regular expressions is also regular 2) That if a language is regular, the reverse of its strings is also regular.
Now, granted $w^R$ nor $w$ are not regular expressions, but since each on their own would be a regular language (given that $\{w\}$ is regular, and so through 2 so is $\{w^R\}$), each can be written as a reg expression. Concatenating these two expressions together then, as the two terms in L are concatenated together, yields a new regular expression.
If a regular expression can be generated for L, why is L not regular?
I know that you can show via e.g. the pumping lemma how L is non regular, but could you show me where I've gone wrong in my reasoning above (probably many places), as my goal is to properly understand the concepts?
Many thanks, indeed! Really appreciate it.
Answer: The problem is that what you call $w$ and $w^R$ are not independent. Probably your expression for $w$ is an expression that generates all words; similarly the expression for $w^R$ generates all the reverses of words (which. by the way, is the same set).
To put together your language you now do not need catenation, but the operation "catenate every string with its reverse, but not with others" - this is not regular, and the expression you propose is not a regular expression.
A tiny example: words $\{ab, aa\}$; reverses $\{ba,aa\}$. The pure catenation contains $abaa$ and $aaba$, which are not of the required form.
Answer: Hint. Suppose that $L$ is regular. Since regular languages are closed under intersection, then $L \cap a^*bba^* = \{a^nbba^n \mid n \geqslant 0 \}$ should be regular.
Comment: Thanks, though unfortunately your answer goes over my head. The one thing I know though is that your (a^n)(bb)(a^n) was cited as a counter example in my text as to why L is not regular because of the pumping lemma. But how that relates to my above reasoning/understanding the bigger picture though, unfortunately I'm not sure?

As an aside, if (a^*)(bb)(a^*) is not regular, why isn't its intersection with L the empty set? Thanks very much! Really appreciate the help.
Comment: Ah, wait a sec on my last question, you meant to say that since a^*bba^* is a member of L, then if L is regular then L n (Member of L) = (Something regular, in fact simply the Member) since regular languages are closed under intersection. Given that the result is not regular, then L must not be regular. So I understand that particular counter example, and thank you very much for it, but where have I gone wrong in my original reasoning? I.e. why can you say two RegExp concat together is also a RegExp, but not generally so for two reg terms together - what's the corrrect general rule? Thanks!
Answer: Can you draw DFA for $w^R$, if DFA of $w$ exists?

Yes, you can draw this DFA too, by reversing existing DFA.

Can you draw DFA for concatenation of two strings of same language?

Yes, you can draw this DFA too.

Can you draw DFA for language $w^Rw$, if it is not finite language, means contains Kleene star(*)?

No,  not at all.
  Because you need comparison $w$ with $w^R$, since language is not finite (i.e, $w \in (a+b)^*$) and you can not store more than one bit in a DFA state. Each DFA state can store only 1 bit data (either 0 or 1).

Infinite comparisons is not allowed in DFA, but infinite condition is allowed.
$L = \{w^Rw \mid w \in \{a,b\}^*\}$ has infinite number of comparisons not condition.


The way to use mouse over SSH on Mac OSX?

Question: Does the gpm have a client on Mac OSX?
update 1:
Could the X11 on Mac OSX be help?
Update 2:
I would like to use mouse on Gentoo server, via a terminal environment on Mac.
Answer: Total shot in the dark, but perhaps piping synergy through an ssh tunnel will help. Know what I'm suggesting here? Need more details?
Comment: Yes, please let me know your suggestions.
Comment: Synergy is a tool for letting you share a single keyboard & mouse to control pretty much as many machines as you like. It works across Operating Systems (Linux, Windows, Mac OS) and is fairly easy to setup. In short one machine actually has a keyboard/mouse and it's configured as a server to share them with other machines - which happens when you move your mouse to a screen boundry - the input will then be redirected to the appropriate machine.

You can apply ssh with synergy to secure your keyboard/mouse traffic. Syngery Website: http://synergy2.sourceforge.net/

Want more info?
Answer: We need some clarification, Are you connecting to the OS X computer or from it? What is your goal? Do you just want to be able to use a mouse in a terminal environment or do you want to remotely control another computer?
Comment: Hi, question updated.
Comment: I was able to replicate the answer on this post: http://stackoverflow.com/questions/1918758/how-to-delete-highlighted-text-in-a-ssh-terminal

But I couldn't get it to work in the native ssh client on my Mac. You might want to try using a different SSH client that might better support passing the mouse movements.
Answer: Yes, I think X11 is the way to go here. Make sure that your Gentoo install will allow remote X sessions (or just go ahead and try it), open X11 on the Mac (from Utilities, or install it from the OS X CD or via http://xquartz.macosforge.org/trac/wiki ). Then open a standard Terminal session (not the X11 session) and do "ssh -X username@gentooserver". Once you have logged in, you should be able to start X-Windows applications from the regular Terminal session and they will start in the OS X X-Windows server.
As I'm usually a SUSE user, I tend to use a lot of "yast2" this way.
Comment: You can skip the "open X11 on the Mac" — since OS X 10.5 it will start automatically when you connect an X application within that "ssh -X".
Answer: VNC.
You can enable VNC access (built-in to OSX) and then just use a VNC Client on the linux desktop.
Answer: All of the answers related to X11 forwarding, VNC, etc are all well and good when connecting to a remote system which has X and/or X programs installed. If you're connecting to a server with NO GUI components the real question of the OP still hasn't been answered.
It's the MAC terminal, not the ssh client, which messes with the mouse-passing to ssh sessions. By starting X11 (from utilities as stated by Johnnie) and xterm, running the native MAC SSH client from xterm instead of  mac terminal, nano -m on the remote system can process the mouse clicks. There may be other terminals for MAC which will behave this way without having to start x11, and there may be a setting which I haven't been able to find which allows the MAC terminal to behave this way. This doesn't require X on the remote system, and works for AT LEAST vi(m) and nano.
Comment: As of OS X El Capitan 10.11, Terminal supports Mouse Reporting.


Use only the rules of inference to derive a logic statement

Question: Question: Given the two propositions: P1: (a $\lor$ b) $\land$ (c $\lor$ d). P2: $\neg$b $\land$ $\neg$ c. Use only the rules of inferences to derive ($\neg$a $\lor$ d) $\land$ ($\neg$d $\lor$ a).
I can only get to the following steps by using rules of inferences:
(1) $\neg b \land \neg c$ => $\neg b \space and \space \neg c$
(2) (a $\lor$ b) $\land$ (c $\lor$ d) => (a $\lor$ b) and (c $\lor$ d)
(3) (a $\lor$ b) $\equiv \neg a$ -> b and (c $\lor$ d) $\equiv$ $\neg c$ -> d
(4) Because $\neg a$ -> b and $\neg b$, therefore, a
(5) Because $\neg c$ -> d and $\neg c$, therefore, d
(6) Because a, d, therefore, $a \land d$
(7) $a \land d \equiv \neg(d \rightarrow \neg a) \equiv \neg (\neg a \lor \neg d)$
These are the farest steps I have gone to derive the final statement by using rules of inferences only.
Comment: What are your inference rules ? See e.g. [List of rules of inference](https://en.wikipedia.org/wiki/List_of_rules_of_inference).
Comment: @MauroALLEGRANZA I didn't list them, but generally they are those simple inference rules.
Answer: It depends on the rules of inference you are allowed to use...
For example, with Simplification (or Conjunction Elimination) from premise $P_1$ we get :
1) $(a ∨ b)$
2) $(c ∨ d)$.
In the same way, from $P_2$ we get :
3) $¬b$
4) $¬c$.
Then, using Disjunctive syllogism we get :
5) $a$ --- from 1) and 3)
6) $d$ --- from 2) and 4)
7) $(a ∨ ¬d)$ --- from 5) by Addition (or Disjunction Introduction)
8) $(d ∨ ¬a)$ --- from 6)

9) $(a ∨ ¬d) \land (d ∨ ¬a)$ --- from 7) and 8) by Adjunction (or Conjunction Introduction).
Comment: I can use all the inference rules and I think I have already got the given hints.
Comment: Like I also got your (5) and (6)
Comment: @KaiweiLuo - okay. From 5) $(a \lor \lnot d)$ and from 6) $(d \lor \lnot a)$. Then use Conjunction intro and it is done.
Comment: Yeah, I just figured out! Thanks!


Explaining the distributions in Tensorflow's Tensorboard

Question: I'm trying to train a cGAN network on Tensorflow and have all the summaries of the Discriminator, but I'm having difficulty understanding what they mean...
There are currently 5 layers in the Discriminator and the distributions are like below:

I'm using the LSGAN loss for training the network and the 5 Conv layers are activated by a LeakyReLU function, but I feel as if the gradients of Layer 5 aren't propagated back properly and it's as if the gradients are diminishing...
Do the images show this or am I mistaking the distributions for something else?
Answer: Your gradient is very strong in all your layers for your first steps. It seems that your model is learning very fast first (normal with gradient learning), and then only the last layer continue to learn to be able to fix the last issues of your model.
So if your model doesn't learn, you have an issue of vanishing gradient (conv too deep or gradient step too low). Or maybe an issue with your dataset if he is able to learn all (overfitting) in some steps.
Maybe check your batch too, if your batch is too big it will average too much your weights (and your gradients won't change after the first steps)
I am still new in deep learning, but it seems to be because of these reasons, according to my low knowledge yet.


Solve the polar coordinate integral $\int_{0}^{3\pi/2}\int_{1}^{4}(4-r)(2+\sin\theta)r dr d\theta$

Question: I am doing a certain problem and I ended up with the following...
$$\int_{\pi/2}^{3\pi/2}\int_{1}^{4}(4-r)(2+\sin\theta)r dr d\theta$$
I am having a difficult time solving it. I did the following...
$$\int_{3\pi/2}^{\pi/2}[4r^2 +2r^2\sin\theta - (2/3)r^3 -(1/3)r^3\sin\theta]_{0}^{4}$$
$$\int_{3\pi/2}^{\pi/2}(54/3 - (37*\sin\theta)/3)d\theta$$
I have no idea how to proceed from here. How can I solve this?
Comment: What are you having a problem with in the last integral?
Comment: $\frac {54}{3} \pi$
Answer: Note
\begin{eqnarray}
&&\int_{\pi/2}^{3\pi/2}\int_{1}^{4}(4-r)(2+\sin\theta)r dr d\theta\\
&=&\int_{\pi/2}^{3\pi/2}\int_{1}^{4}(8r+4r\sin\theta-2r^2-r^2\sin\theta) dr d\theta\\
&=&\int_{\pi/2}^{3\pi/2}(4r^2+2r^2\sin\theta-\frac23r^3-\frac13r^3\sin\theta)\bigg|_{r=1}^{r=4} d\theta\\
&=&\int_{\pi/2}^{3\pi/2}(18+9\sin\theta)d\theta\\
&=&18\pi.
\end{eqnarray}


change quicktabs default tab

Question: according to current documentation of for change alter quicktabs should use this method
in my module
mymoule_quicktabs_alter(&$quicktabs){
    $quicktabs->default_tab=2;
   }

when i print result with dsm  it changed applied, but it not apply to visual output of quicktabs.
tell me how i can change quicktabs default tab ?
tnx
Comment: any drupal 8 solution?
Answer: Its not done simple, by default quicktabs ordered by wieght,
Quicktabs has quickly become one of my favorite Drupal modules of all time. To think that I was actually wasting time creating tabs by using jQuery plugins, and writing custom AJAX. Creating tabbed content is one of the most popular techniques used on the web today, and with Quicktabs it has never been easier to add tabs to your Drupal site - even with AJAX!
First you'll want to install Quicktabs
Once you have Quicktabs installed, there are a couple of ways to generate tabs. You can do it through the Drupal interface, or you can do it programmatically, but first, make sure you have some content that you want to show in tabs! Quicktabs works with your existing content. You can tab between views, blocks, nodes, or a mixture of these.
For this demo, we'll use Views and set up 2 displays filtered by a certain taxonomy term. We will then create a tab that displays nodes of each taxonomy term respectively. Make sure you have some taxonomy terms to choose from for each post. Then you'll want to create a view called "my_listing", or whatever makes sense for you.
Once you have created your View, create a couple of different "page" displays. Name each display according to your taxonomy term, so if you want to tab between say "Development" and "Theming" nodes, each page display will be named respectively.
Since you're creating page views, you'll have to specify a URL for each under the Page Settings section. You can use something like "list/development" and "list/theming" respectively. This is required by page displays, but it is also good if a user for some reason does not have javascript enabled, they will still be able to see the listings, just not through AJAX.
Also, for simplicity, make "Row style" node, so we don't have to play with fields.
Under "Filters" filter on each display for that specific taxonomy term, so that each display is only displaying nodes of whichever taxonomy you choose. Save the view.
Now that you have some content to play with it's time to create some tabs. Browse to admin/build/quicktabs and click on the "New QT block tab".
By default, Quicktabs creates a block for you which you can then place anywhere in the site like a regular block, but there is also a way to output your quicktabs in code, which i'll show you further down.
In the Block Title field, give your block a meaningful title. Next is the style dropdown, where you can select between various styles of tabs. You can also select "no style" so you can theme them your own way
The next field allows you to select whether or not you want your tabs to be AJAX. In most cases you will want to use AJAX so that you only load the second view when the user requests it.
The "Hide empty tabs" will only work if you do NOT use AJAX, which is kind of unfortunate. But, an easy way to deal with this is to use the "empty text" area in your views to give the user a friendly "There is no content here" message.
The next section is where you will start creating your tabs
Let's say the view you created with the 2 page displays are for a taxonomy term "Development" and one for "Theming". Give each tab their respective title. For the Tab type, select "view". In the tab content section, select the view you created (my_listing). Then select the display you want to show. For the Development tab, show the display that filters on Development. For the Theming tab, show the display that filters on Theming. You can also pass arguments into your Quicktabs to use with Views that accept arguments which is really cool, but I won't be covering that here.
Click save. You now have a block available for you to place anywhere on your site, that will tab between nodes of each taxonomy term! Very cool! But, what if you dont' want to use a block...what if you want a bit more control to place these tabs wherever you want? It's easy.
On your tabs listing page (admin/build/quicktabs) hover over the 'edit' link and take note of your quicktabs ID in the url. (quicktabs/1/edit). If this is your first quicktab, the ID will be 1.
Now to print out your quicktabs, all you need to do is call this function and run it through theme("quicktabs"); like this:
$tabs = quicktabs_load(1); // where 1 is your quicktabs id
$mytabs = theme("quicktabs", $tabs);

return theme("my_custom_template", $mytabs);

Then in your custom template, just print out the mytabs variable and you should see your quicktabs!
Comment: As a Quicktab pro maybe you can answer this - If you have 2 different quicktabs blocks which use the same tabs, although you have changed the default tab to tab#2 on the second block, why would both blocks show the same default tab every time?
Answer: mymoule_quicktabs_alter(&$quicktabs) {
  $quicktabs->default_tab=2;
}

This works fine.
Please check if any JS script is overwriting your default tab. Normally if other module or JS script that alters the default tab and executes after current module; you might not see the effect in front-end.
Answer: own module must be sort after quicktab module - when i added module name webmodule and there insert
webmodule_quicktabs_alter(&$quicktabs) {
  $quicktabs->default_tab=2;
}
everything works fine
Answer: mymoule_quicktabs_alter(&$quicktabs) {
  $quicktabs->default_tab=2;
  return $quicktabs;
}
This works fine.
Answer: The easiest is qt- =  in the new version of quick tab it takes as a query string
Comment: Welcome to Drupal Answers! May you expand your answer? As it is, it is not much clear.

change quicktabs default tab


Can I change the minSdk from 2.3 to 4 for an existing Google Play Store app with an upgrade

Question: If I have an existing app on the store with minSdk = 2.3.4 and now I change that to 4.1.2, will the store accept the new apk? What will happen to users with 2.3.4?
Answer: Yes, Play Store will accept the new APK.
As long as you keep both APKs uploaded on Play Store, your existing customers will be able to get that version. They will not receive the new version as an update, if their software version is not compatible
Answer: Yes you can. This means that only users with API level 16 or higher will get updates of your app. User with lower versions will get no updates and cannot install your app.
But it is possible to keep the older version, so that user with lower version can install your old app version.


How to run jquery function on every page load

Question: I have a Views grid that contain images in DIV containers. I want these containers to have one of two possible heights 60px or 104px, depending on the images height. So I came up with this function (contained in a $(document).ready function())  that I have added in my theme's JS file.
  $('div.givarbild img').each( function() {
    var container = $(this).closest('div.givarbild');
    var pic = new Image();
    pic.src = $(this).attr("src");
    var picHeight = pic.height;
    console.log(picHeight);
    if(picHeight < 60){
        container.height(60);
    }else if(picHeight > 60){
        container.height(104);
    }

  });

Now, my problem is that this only works once, after clearing the caches in Config -> Performance. If I simply reload the page after clearing all caches in Drupal all DIVs are 60 px high and the container.height value is zero in the js console (Firebug).
How can I force this little function to run after every page load?
EDITED:
Hmmm, I am obviously doing something wrong here :-)... but with this code:
(function($) {
    Drupal.behaviors.related_content = {
        attach: function (context) {
            $('div.givarbild img').each( function() {
                var container = $(this).closest('div.givarbild');
                var pic = new Image();
                pic.src = $(this).attr("src");
                var picHeight = pic.height;
                console.log(picHeight);
                if(picHeight < 60){
                    container.height(60);
                }else if(picHeight > 60){
                    container.height(104);
                }
            });
        }
    }
})(jQuery);

... I get the exact same result. It works immediately after clearing all caches in Drupal 7 but not when I reload the page after that. Is there something fishy with my custom script itself?
EDITIED AGAIN: I post this change to my js code in case anyone else is having the same issue. This code does the same thing as the previous one, except that it works every time, and not just the first time after clearing all caches in D7. The only thing I changed was the method for getting the natural image height. It would be interesting to know why this latter code works though and not the first one... it actually works every time even without the added Drupal.behaviors rows.
(function($) {
    Drupal.behaviors.related_content = {
        attach: function (context) {
            $('div.givarbild img').each( function() {
                var container = $(this).closest('div.givarbild');
                $("").attr("src", $(this).attr("src")).load(function(){
                    var picHeight = this.height;
                    console.log(picHeight);
                    if(picHeight < 60){
                        container.height(60);
                    }else{
                        container.height(104);
                    }
                });
            });
        }
    }
})(jQuery);

Answer: (function ($) {
  Drupal.behaviors.custom_scripts = {
    attach: function (context) {

      //write your custom code

    }
  }
})(jQuery);

Along with this for the first time you have to clear cache, and this will work in all pages and all the times.
Comment: It would be good to mention that "custom code here" will run every time Drupal behaviours are attached, not just on page load. That could be after an AJAX call on the same page, for example. If that's not desirable, `$.once` should be used
Comment: That looks like the right answer, but at my first try, I didn't get it to work. Should I replace custom_scripts with something?
Comment: Yes you can write anything there.
Comment: OK, thanks a lot! I have edited my question, I still don't get it to work more than once and I am beginning to think it also has something to do with my code... maybe I should try to find some other method to get the natural height of the image.
Answer: You could try to disable the caching of the view.
To do this go admin/structure/views and edit your view under the advanced section there is a caching option.


*ngFor loop through an array of arrays Angular6

Question: I have array like this,
[[{"user":"1","nice":"0","sys":"1","CPU":"93","irq":"0"},
{"user":"1","nice":"0","sys":"1","CPU":"92","irq":"0"},
{"user":"1","nice":"0","sys":"1","CPU":"92","irq":"0"},
{"user":"1","nice":"0","sys":"1","CPU":"92","irq":"0"}],
[{"user":"0","nice":"0","sys":"0","CPU":"91","irq":"0"},
{"user":"0","nice":"0","sys":"1","CPU":"91","irq":"0"},
{"user":"1","nice":"0","sys":"0","CPU":"91","irq":"0"},
{"user":"0","nice":"0","sys":"0","CPU":"90","irq":"0"}]]

I want to loop through this array of object in an HTML table using ngFor

      User
      Nice
      Sys
      CPU
      IRQ

      {{post.user}}
      {{post.nice}}
      {{post.sys}}
      {{post.CPU}}
      {{post.irq}}

But my code doesn't work
Comment: Try `*ngFor="let post of posts[0]"` (not tested) but I think you can access to your nested array like this.
Answer: You can use ng-container to hold one ngFor and do the second ngFor in the tr tag like this:

    <ng-container *ngFor="let group of posts">

            {{post.user}}
            {{post.nice}}
            {{post.sys}}
            {{post.CPU}}
            {{post.irq}}

    </ng-container>

Answer: Its not array of arrays, you have two arrays. if you want to iterate over the first one use the index as posts[0]

      {{post.user}}
      {{post.nice}}
      {{post.sys}}
      {{post.CPU}}
      {{post.irq}}

STACBKLITZ DEMO


Can one know if $P(A \cap B) > P(A)P(B) $ or $P(A \cap B) < P(A)P(B) $?

Question: I understand the following definition:
$P(A \cap B) = P(A)P(B) $ if $A$ and $B$ are independent and
$P(A \cap B) = P(B|A)P(A)$ and $P(B|A)P(A)\neq P(A)P(B)$ if $A$ and $B$ are not independent.
My question is:

For the case of dependence, does $P(A \cap B) > P(A)P(B) $ or $P(A \cap B) < P(A)P(B) $ or is it not possible to know without any values ?
Comment: Both can be true. You need more information to know which of the two. Btw "$P(A\cap B)=P(A)P(B)$ if $A$ and $B$ are independent" is not a theorem but a definition.
Comment: thanks ! and also edited :)
Answer: There exists a rough estimate about $P(A\cap B)$ and $P(A)P(B)$ whether events $A$ and $B$ are dependence or not, which is
$$ \left| P(A\cap B) - P(A)P(B) \right| \leq \frac{1}{4} $$
The proof of this inequality can be proved by discussing the relationship of events $A$ and $B$.
Comment: I'm a bit late to comment on this, but does anyone know a name for this inequality or a link to a proof?
Answer: I guess this might help:
Assuming $\mathsf{P}(A)\neq 0,1$ and $\mathsf{P}(B)\neq 0,1$.
Consider the random variable $1_A$, where $1_A(\omega)=1$ if $\omega\in A$ and $1$ if $\omega\notin A$.
Now $\mathsf{Cov}(1_A,1_B)=\mathsf{E}(1_A\cdot 1_B)-\mathsf{E}(1_A)E(1_B)=\mathsf{E}(1_{A\cap B})-\mathsf{E}(1_A)\mathsf{E}(1_B)$
Now $\mathsf{E}(1_A)=1\cdot \mathsf{P}(A)+0\cdot \mathsf{P}(A^c)=\mathsf{P}(A)$
Hence $\mathsf{Cov}(1_A,1_B)=\mathsf{P}(A\cap B)-\mathsf{P}(A)\mathsf{P}(B)$
So $\mathsf{P}(A\cap B)>\mathsf{P}(A)\mathsf{P}(B)$ implies $\mathsf{Cov}(1_A,1_B)>0$ and $\mathsf{P}(A\cap B)<\mathsf{P}(A)\mathsf{P}(B)$ implies $\mathsf{Cov}(1_A,1_B)<0$.
So $\mathsf{Cov}(1_A,1_B)>0$ implies if $A$ occurs then it is more likely to $B$ also occurs or if $B$ occurs then it is more likely to $A$ also occurs.
Similarly, $\mathsf{Cov}(1_A,1_B)<0$ implies if $A$ occurs then it is less likely to $B$ also occurs or if $B$ occurs then it is less likely to $A$ also occurs.
Answer: Since $P(A\cap B)=P(B\mid A)P(A)$, the equation $P(A\cap B)>P(A)P(B)$ is equivalent to $$P(B\mid A)>P(B)$$ (assume that $P(A)\neq 0$ to avoid trivial cases). This equation, says that: given that $A$ occured, $B$ has become more probable. For example, let $A$ be the event "there are clouds in the sky" and $B$ the event "it rains". Assume that you know from past data the probability $P(B)$ (perhaps you are a meteorologist). Now, knowing that $A$ applies (you open your window and you see many clouds outside), then certainly this increases the probability of $B$.
But it can also be the other way: let "A" be the event "there are no clouds in the sky" (you open your window and it is so sunny that you close it again). Then, certainly $P(B\mid A)<P(B)$.
Comment: great ! intuitive examples always helps


Obtenho NA quando converto character para tempo (POSIXlt)

Question: Por que obtenho NA quando faço essa conversão de character para POSIXlt?
    library(bReeze)
    data(winddata)

    tempo <- winddata[,1]
    tempo[1:6] # Preview
    # [1] "06.05.2009 11:20" "06.05.2009 11:30" "06.05.2009 11:40"

    tempo_POSIX <- strptime(tempo, format = "%d.%m.%Y %H:%M")
    sum(is.na(tempo_POSIX))
    # [1] 6

    valores_NA <- which(is.na(tempo_POSIX))
    tempo[valores_NA]
    # [1] "18.10.2009 00:00" "18.10.2009 00:10" "18.10.2009 00:20"
    # [3] "18.10.2009 00:30" "18.10.2009 00:40" "18.10.2009 00:50"

Como se pode ver, os valores que foram convertidos para NA se comportam normalmente... eles seguem o mesmo formato dos demais.
Curiosamente, o erro NÃO OCORRE se passo um valor para o argumento tz
    tempo_POSIX <- strptime(tempo, format = "%d.%m.%Y %H:%M", tz = "GMT")
    sum(is.na(tempo_POSIX))
    # [1] 0

As minhas informações de sistema são:
    > sessionInfo()
    R version 3.0.2 (2013-09-25)
    Platform: x86_64-w64-mingw32/x64 (64-bit)

    locale:
    [1] LC_COLLATE=Portuguese_Brazil.1252  LC_CTYPE=Portuguese_Brazil.1252
    [3] LC_MONETARY=Portuguese_Brazil.1252 LC_NUMERIC=C
    [5] LC_TIME=Portuguese_Brazil.1252

    attached base packages:
    [1] stats     graphics  grDevices utils     datasets  methods   base

    other attached packages:
    [1] bReeze_0.4-0

    loaded via a namespace (and not attached):
    [1] tools_3.0.2

Comment: Aqui funciona sem problemas.
`tempo_POSIX <- strptime(tempo, format = "%d.%m.%Y %H:%M")
sum(is.na(tempo_POSIX))
[1] 0
# [1] 6`
Comment: @Djongs, não entendi seu output... Afinal, o número de missings que vc consegue é `0` ou `6`?

E o erro continua acontecendo comigo... Por isso editei a pergunta e coloquei informações do meu sistema lá.
Comment: Rogério, este resultado varia de acordo com a locale, por causa do horário de verão. O sistema do Djongs deve estar com outra locale. @Djongs para reproduzir o exemplo, rode `Sys.setenv(TZ='America/Sao_Paulo')`  antes.
Answer: No help do as.POSIXlt, há a seguinte passagem que destaca que a conversão de formatos date time precisa de um time-zone e irá validar este horário e que isso pode causar problemas em horários de verão (Daylight Savings Time - DST):

Character input is first converted to class "POSIXlt" by strptime:
  numeric input is first converted to "POSIXct". Any conversion that
  needs to go between the two date-time classes requires a time zone:
> conversion from "POSIXlt" to "POSIXct" will validate times in the
  selected time zone. One issue is what happens at transitions to and from DST

Quando você faz o strptime(tempo, format = "%d.%m.%Y %H:%M"), você está convertendo o objeto para a classe POSIXlt.
class(tempo_POSIX)
[1] "POSIXlt" "POSIXt"

Mas quando você faz o is.na(), você está convertendo para POSIXct. Veja que o método is.na.POSIXlt usa a função as.POSIXct:
is.na.POSIXlt
function (x)
is.na(as.POSIXct(x))
<bytecode: 0x26519a14>
<environment: namespace:base>

O horário de verão no Brasil, em 2009, começou no dia 18 de outubro às 00:00. Isto é, considerando o horário de verão, não existe 00:00 no Brasil no dia 18 de outubro de 2009, pois quando o relógiou virou 23:59 do dia anterior, pulou automaticamente para 01:00 da manhã.
Então, quando você faz o is.na() você está transformando a data em POSIXct e esta conversão valida a data fornecida com a sua locale (que provavelmente é Brasil/São Paulo, pois como você não especificou a time zone, será usada a do sistema). E como não existe 00:00 do dia 28 de outubro nesta time zone, isso resulta (corretamente, mas inesperadamente) em NA. Quando você coloca a time-zone GMT ou outra que exista a data que você está passando (como Londres) , ele faz a conversão normalmente, por isso que funcionou com tz = "GMT" (e por isso que funcionou com o Djongs, ele deve estar em outro locale).
Comment: Sensacional, @Carlos!


Showing that two triangle have the same content Euclidean style proof.

Question:
We know that D is the midpoint of AB and that E is the midpoint of AC.
We wish to show that Triangle DBC has the came content as Triangle BEC. if we can do so we have a theorem that will tell us that DE is parallel to the line BC.
This question is asked in the spirit of euclid. no midpoint theorem or proving the midpoint theorem in anther way is allowed.
Edit: Could we perhaps argue that Triangle DEC and Triangle ADE have the same base and Height somehow?
Comment: Do you only wish to prove that $\overleftrightarrow{DE}$ and $\overleftrightarrow{BC}$ are parallel?  Because that follows from the fact that $\triangle ADE$ and $\triangle ABC$ are similar.
Comment: It can also be shown by extending DE and marking of length DE from E then connecting that new point to C by SAS of triangle ADE this new triangle is congruent hence   the angle formed on the line AC observes the Alternative angle bisector and we have DE and BC are parallel. Sadly as i said above the result has to be proved by showing that Triangle BDE has the same content as Triangle BEC
Comment: Interesting.  The only observation I can see is that the two triangles have the same base line segment, and "obviously" the same height.  But that obviousness is equivalent to the fact that DE and BC are parallel.
Comment: yeah it makes the question rather difficult without knowing that, its from Hartshorne a translated version of Euclids elements  problem 3.11 on page 45 of the book. i cant seem to think of how to do it without proving that DE is parallel to BC but the question seems to imply there is such a way...
Comment: It would have been to put that citation in the original question.
Answer: SKETCH OF PROOF
Find two ways to 'shear' triangle $\Delta{CDE}$ into $\Delta{BDE}$. One of these shearing transformations is 'indirect' and keeps the content of the triangle constant at all times, ensuring that $\Delta{CDE}$ = $\Delta{ADE}$ = $\Delta{BDE}$ in content. Such equality of content means the second shearing action, being 'direct', must be constrained by two parallel lines. Those parallel lines are $\overleftrightarrow{BC}$ and $\overleftrightarrow{DE}$, Q.E.D. While shearing is strictly speaking not a Euclidean concept, the Euclidean propositions I.36 to I.39 required for this proof can be expressed in the modern language of shearing transformations. Note as well that this rather modern logic based on the 'shearing' of equal-content figures is actually very basic in Euclid's proof system. It appears in Elements I, while SAS similarity must await his sixth (!) volume.
DETAILS OF PROOF

Euclid's Proposition I.36, expressed in modern language, says that a parallelogram keeps its area, i.e., its 'content', even as it is sheared by sliding its 'top' and 'bottom' bases relative to each other along their 'baselines'.
Viewing a triangle as a degenerate parallelogram whose 'top' side has zero length (but Euclid may have had problems understanding the concept of zero, forcing him to prove I.37 first), we get I.38: a triangle keeps its content even as its 'top' vertex and 'bottom' base slide relative to each other along their 'baselines'.
Fix 'top' vertex $D$ in place, but slide 'bottom' base $\overline{CE}$ along $\overleftrightarrow{AC}$ until the base coincides with $\overline{AE}$. By I.38, $\Delta{CDE}$ and $\Delta{ADE}$ have equal content.
Then, view $\Delta{ADE}$ as having 'top' vertex $E$ and 'bottom' base $\overline{AD}$. Fix $E$ in place, but slide 'bottom' base $\overline{AD}$ along $\overleftrightarrow{AB}$ until the base coincides with $\overline{BD}$. By I.38 again, $\Delta{ADE}$ and $\Delta{BDE}$ have equal content.
By the transitivity of equality (a.k.a. 'Common Notion 1' in Euclid's time), $\Delta{ADE}$, $\Delta{BDE}$, and $\Delta{CDE}$ have equal content. More specifically, $\Delta{BDE}$ = $\Delta{CDE}$ in content.
I.39 is the converse of I.37: A shearing transformation that maintains the area of a triangle whose 'bottom' base is fixed must slide the 'top' vertex along a line parallel to the fixed 'bottom' baseline.
By I.39, the shearing transformation defined by the equal-content triangles $\Delta{BDE}$ and $\Delta{CDE}$, whose fixed 'bottom' base is $\overline{BC}$, must be a shearing action wherein $B$ slides to $C$ along a line $\overleftrightarrow{BC}$ that is parallel to the 'bottom' baseline $\overleftrightarrow{DE}$, which was what we wanted.

NOTES

First, strictly speaking, Euclid did not view I.36 to I.39 as statements on shearing transformations. While Euclid defined congruence in terms of superposition, which is one kind of transformation, mathematicians viewed transformations suspiciously until the 19th Century.
Two tools Euclid used to prove I.36 to I.38 are adding and subtracting content, i.e., cut-and-paste. He, however, neither explicitly axiomized nor axiomatically proved that content is a quantity amenable to cut-and-paste.
Euclid also used reductio ad absurdum, i.e., proof by contradiction, to prove I.39. Some mathematicians do not accept proof by contradiction, though, given that apparent proofs of contradiction stalled the rise of non-Euclidean geometries for nearly two millennia.
Note as well that while Euclid's logic based on the 'shearing' of equal-content figures is surprisingly compatible with modern transformation-based geometry, it is actually near-foundational in his proof system. All the Euclidean propositions used above appear in Elements I, while the SAS similarity argument most contemporary students would employ in this proof had to await Euclid's sixth (!) volume. $\blacksquare$


How to compute $\frac{\Gamma(n-\alpha)}{\Gamma(\alpha)}?$

Question: How to simplify the gamma function:
$$\frac{\Gamma(n-\alpha)}{\Gamma(\alpha)}?$$
where $n\in \mathbb{Z}$ and $\alpha$ some real number.
Comment: Why do you believe this simplifies?
Comment: Gamma functions are pretty fundamental objects already, reducing a complicated formula down in terms of only Gamma functions would be a success.
Comment: $\Gamma(z)$ has a simple pole at $z=0$, so this is immediate, isn't it?
Comment: @PeterForeman Can you tell me how to prove $\Gamma(x)\sim 1/x$?
Comment: @PeterForeman If I use the answer of MPW, then the limit is $O(\alpha^{-2})$, right?
Answer: Hint: If you assume $0<\alpha<1$, you should be able to express this in terms of $\Gamma(\alpha/2)$ and $\Gamma(1-\alpha/2)$ using the fact that $n!= n(n-1)!$. Once you have that, you may be able to use the reflection formula
$$\Gamma(z)\Gamma(1-z) =\frac {\pi}{\sin \pi z}$$This is only speculation on my part, but I think it is a path worth exploring.
Addendum: The reflection formula means you could write $$\frac{1}{\Gamma(1-z)}= \frac{1}{\pi}\Gamma(z)\sin \pi z$$ so $$\frac{\Gamma(z)}{\Gamma(1-z)}= \frac {1}{\pi}\Gamma(z)^2\sin \pi z$$
Comment: but.. $\Gamma(\alpha/2)$ In the denominator.
Comment: Yes, but you may still be able to improve the expression. See the addendum to my answer.


proof of isomorphism in exact sequence and outer semi direct product

Question:

I have trouble showing why $\theta'(k,h)=\beta(k)s(h)$ is bijective between $K\rtimes_\varphi H\to G$
I tried showing the injectivity, ie. if $\beta(k)s(h)=e_G$ only if $k=e_K,h=e_H$, by showing that has to staisfy $\beta(k)=e_G,s(h)=e_g$ and $k,h$ has to be $e_K,e_H$ each.
I can show that $s(h)=e_G,$ then $\alpha(s(h))=\alpha(e_G)=e_H$, but I have trouble showing that why $k$ has to be $e_K$.
I have no much idea how to show the surjectivity.
Comment: Please do not rely on i ages to convey information not otherwise available in your posy. [See here for an explanation](https://math.meta.stackexchange.com/a/34123/742).
Comment: You cannot establish injectivity by showing the kernel is trivial before you establish that the map is a group homomorphism.
Comment: @ArturoMagidin After showing that $\theta'$map is a gropu homomorphism, how can I show injectivity and surjectivity?
Thank you for the information that I better upload in texts
Answer: You cannot use the method you suggest to check injectivity unless you have already established that $\theta'$ is a group homomorphism. I do not believe you have shown that.
To show injectivity, suppose that $\theta'(k,h) = \theta'(k',h')$. Then $\beta(k)s(h) = \beta(k')s(h')$. Therefore, since $\beta$ and $s$ are known to be group homomorphisms, we have:
$$\begin{align*}
\beta(k)s(h) &= \beta(k')s(h')\\
\beta(k')^{-1}\beta(k) &= s(h')s(h)^{-1}\\
\beta(k'^{-1})\beta(k) &= s(h')s(h^{-1})\\
\beta(k'^{-1}k) &= s(h'h^{-1}).
\end{align*}$$
But now, since $s$ is a section of $\alpha$, and $\mathrm{Im}(\beta)=\mathrm{ker}(\alpha)$, then applying $\alpha$ to both sides we get
$$\begin{align*}
\beta(k'^{-1}k)&=s(h'h^{-1})\\
\alpha\beta(k'^{-1}k) &= \alpha s(h'h^{-1})\\
e &= h'h^{-1}.
\end{align*}$$
Thus, $h'=h$. Then from $\beta(k)s(h) = \beta(k')s(h')$ we conclude $\beta(k)=\beta(k')$. Since $\beta$ is one-to one, we get $k=k'$. Thus, $\theta$ is one-to-one.
To show $\theta'$ is surjective, let $g\in G$, and consider $s(\alpha(g))g^{-1}$. Applying $\alpha$ we get
$$\alpha(s(\alpha(g))\alpha(g^{-1}) = \alpha(g)\alpha(g^{-1}) = e.$$
Thus, $s(\alpha(g))g^{-1}\in\mathrm{ker}(\alpha)=\mathrm{Im}(\beta)$. Taking inverses, we have $g(s\alpha(g))^{-1}\in\mathrm{Im}(\beta)$, so there exists $k\in K$ such that $g(s(\alpha(g)))^{-1} = \beta(k)$. Therefore,
$$g = \beta(k)s(\alpha(g)).$$
Hence, $g = \theta'(k,\alpha(g))$, proving that $\mathrm{Im}(\theta')=G$, as desired.
This shows bijectivity. Note we haven't shown that $\theta'$ is a group homomorphism, though.
Comment: @momo Yes: the fact that it is a (short) exact sequence tells you three things: (i) the kernel of $\beta$ is the image of $1\to K$; (ii) that $\mathrm{Im}(\beta)=\ker(\alpha)$; and (iii) That $\mathrm{Im}(\alpha)=\ker(H\to 1)$. In particular, the first tells you that $\ker(\beta)=\{e_K\}$, and the last that $\mathrm{Im}(\alpha)=H$.
Comment: Do we know that $\beta$ is one-to-one because it is exact sequence? I only know that it must be surjective on G if $G \to 1$
Comment: This is so cool! Thank you!


javascript cannot add element into dictionary

Question: I want to create a structure of dictionary lineChartData{ datasets:[ {dataset },{dataset }...{ dataset} ] } and in each dataset, {data:[1,2,3,...]}. But whenever I try to print console, I always get "[object object]", can anyone help me out please??
var lineChartData = {}; //declare an object
lineChartData.datasets = [];
for (line = 0; line < symptomSet.size; line++) {
    y = [];
    dataset = {};
    dataset.data = [];
    for(i=0; i< Object.keys(dataMap).length ; i++) {
      if(dataMap[Object.keys(dataMap)[i]][symptoms[line]]==null) {
        dataset.data.push(0);
      } else {
        dataset.data.push(dataMap[Object.keys(dataMap)[i]][symptoms[line]]);
      }
    }
    console.log("dataset:"+dataset); //always print "[object object]"
    lineChartData[datasets].push(dataset);
}

Comment: Do `console.log("dataset:", dataset)` instead... Concatenating a string with an object will execute `dataset.toString` which returns `"[object object]"`.
Comment: Oh great it works!! I thought my mechanism is not working, but it's actually the displaying not working! Thanks a lot!
Comment: No problem, glad it's working fine.
Answer: Turning Derek 朕會功夫's comment into an answer:
Do console.log("dataset:", dataset) instead. Concatenating a string with an object will execute dataset.toString, which returns "[object object]".


Magento thumbmail quadrada

Question: estou criando uma loja virtual em magento utilizando o tema porto, mas estou com o seguinte problema: As imagens estão ficando retangulares e desproporcionais, segue uma foto de exemplo:

Como faço para deixar um tamanho padrão para as fotos? algo quadradinho tipo 200x200
Comment: Já tentei mudar o codigo da imagem no list para keepFrame(TRUE) e os $ratio_width,$ratio_height para 150,150 e não resolve :(
Answer: a alteracao q vc fez em $ratio_width e $ratio_height afetam a geracao do codigo em PHP... isso modifica a qualidade da imagem renderizada... mas nao afeta o tamanho de sua exibicao na tela/navegador.
o q controla o tamanho da imagem exibida, eh o HTML/CSS.
dependendo de como o tema foi criado... vc pode modificar o width e height destas imagens em um style.css proprio do tema (deve estar dentro do package theme porto).
procure pelo class da imagem (se houver).. vc deve encontrar o nome do class no html gerado no navegador (clicando com botao direito em cima da imagem).. deve ser algo parecido com "class=product_image".
ou entao .product .img dentro do style.css do tema.
em alguns casos (pq tudo depende de como o tema foi escrito)... o tamanho width e height estarao dentro da tag img do html, ex.: ""
nesse caso vc precisa modificar direto no codigo HTML.
sucesso ai.

Magento thumbmail quadrada


Selecting iframe element - "Blocked a frame with origin "http://localhost:3000" from accessing a cross-origin frame"

Question: I'm trying to access inside a TradingView stock chart widget (https://www.tradingview.com/widget/advanced-chart/), which loads in an iframe.  The goal is to programatically draw on the canvas tag of the widget after it has loaded, but I'm getting the following error:

Blocked a frame with origin "http://localhost:3000" from accessing a
cross-origin frame

I tried basically every answer here: How to enable cors nodejs with express?, but I think this might be a different context than trying to access an iframe.  I saw some other information about using postMessage, but I also don't think that's relevant for interacting with HTML elements.
Here's the full code.  It's the last line within the draw function that creates the error.
index.js
const cors = require('cors');
const express = require('express');
const app = express();

app.use(cors())

app.get('/', (req, res, next) => {
    res.sendFile(__dirname + '/index.html');
});

app.get('/test', (req, res, next) => {
    res.send("success")
});

const port = 3000
app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})

index.html

</script>

AAPL stock chart by TradingView

script>

I'm wondering if there's a workaround to this.  If not, I'm wondering if I could overlay another canvas on top of the widget but still allow the user to interact with the widget at the same time.
Comment: See https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy#cross-origin_script_api_access
Comment: CORS applies to HTTP requests, that is not your issue here. You are fighting the good old Same-Origin-Policy. _"wondering if I could overlay another canvas on top of the widget but still allow the user to interact with the widget at the same time"_ - if they don't need to interact with _your_ canvas, then you should be able to use `pointer-events: none` to let everything "go right through."
Comment: "I saw some other information about using postMessage, but I also don't think that's relevant for interacting with HTML elements." — It's highly relevant. `postMessage` is how you communicate between frames on different origins. You can't access the DOM of a cross-origin frame directly, you can only post a message to the frame, have JS running in that frame access the DOM and then send a message back (again using `postMessage`).
Comment: @CBroe - The only issue I can think of is that TradingView charts can be dragged to go further back in time, which would cause the overlay to become misaligned with underlying chart widget.  Ideally, the user could interact with both the overlay and the widget at the same time.
Comment: No, that won't be possible.
Comment: @Quentin - This line of code results in an error before I even get to the `postMessage` stage:  `document.querySelector('iframe').contentWindow.addEventListener('message', () => {});`
Comment: @SuperCodeBrah — I said "You can't access the DOM of a cross-origin frame directly, you can only post a message to the frame" — Since you can't access the DOM, you can't add the event listener across origins. The page *in the frame* has to include the code that listens for the message.
Comment: I guess I should have been more clear in the question, but that's what I was getting at.  I don't control the iframe, so `postMessage` doesn't help me.
Comment: @SuperCodeBrah — Let's put it this way. You want to edit a webpage, on a site belonging to someone else, which you do not control. It is not reasonable for a browser to provide a way for you to do that. It isn't your site!
Answer: This appears to be a CSP issue, they have specified which domains may interact in which way and your inline script is not allowed to interact with the iframe. So this solution is not possible.
I am not that familiar with iframes to answer the question if you can use an overlay and pass the event down to the iframe. I would probably look into where the data comes from and if I can get that data via an endpoint which does not have any problem with being called cross domain and make this dashboard myself.
Comment: "This appears to be a CSP issue" — It isn't. Cross-origin frame access outside of postMessage is impossible. A CSP couldn't tighten security any further.
Comment: "if you can use an overlay and pass the event down to the iframe" — This sounds like you are suggesting using a [clickjacking attack](https://en.wikipedia.org/wiki/Clickjacking). That's a really bad idea, and browsers do try to defend against them.


Existe alguma diferença entre a função is_file e file_exists?

Question: Por acaso, existe alguma diferença entre a função is_file e file_exists?
var_dump(file_exists('public/index.php'); // bool(true)

var_dump(is_file('public/index.php')); // bool(true);

Teóricamente, os dois teriam o mesmo sentido, já que is file é equivalente à "é arquivo?" e file_exists é equivante a "arquivo existe?"
Se é um arquivo que existe, é um arquivo. E se é um arquivo, ele existe.
Então, qual é a diferença entre essas funções?
Comment: `is_file` acho que é pra ver se não é diretório... só ver o manual http://php.net/manual/en/function.is-file.php
Comment: Pra ver se não é diretório eu só uso `!is_dir($file)`
Comment: Puts, muitas respostas iguais! efeito cascata
Answer: Sim existem algumas diferenças:
file_exists() verifica se existe o diretório ou o arquivo, passado como argumento.
is_file() A definição do manual é

Tells whether the given file is a regular file.
Informa se o arquivo/string passado como argumento é um arquivo regular

Segundo essa resposta do SOen, alguns exemplos de  arquivos não regulares são:

devices
pipes
sockets

Basicamente o que a função faz é checar se a string($filename) informada é válida ou seja não contém caracteres estranhos caso positivo verifica se $filename representa um arquivo, do contrario retorna false.
Fiz alguns testes comparando as duas funções, o resultado é tabela abaixo
Estrutura do projeto
Raiz
  foo
    3.txt - Atalho.lnk
  txt
    1.txt
    abců.txt
    ů.txt
  ů

<?php
   var_dump(is_file('foo')); //pasta
   var_dump(is_file('txt/1.txt')); //arquivo
   var_dump(is_file('C:\\')); //device
   var_dump(is_file('txt/abců.txt')); //arquivo com caracter estranho
   var_dump(is_file('txt/ů.txt')); //arquivo com caracter estranho
   var_dump(is_file('txt/ů')); // pasta com caracter estranho

   var_dump(file_exists('foo')); //pasta
   var_dump(file_exists('txt/1.txt')); //arquivo
   var_dump(file_exists('C:\\')); // device
   var_dump(file_exists('txt/ů.txt')); //arquivo com caracter estranho
   var_dump(file_exists('txt/abců.txt')); //arquivo com caracter estranho
   var_dump(file_exists('ů'); //pasta com caracter estranho

Resultado:
     X      |Pasta |Arquivo|Device|Pasta ou arquivo com caracter estranho
is_file     |false |true   |false |false
file_exists |true  |true   |true  |false

Comment: Acha que fui troll no meu comentário: _Se é um arquivo que existe, é um arquivo. E se é um arquivo, ele existe._?
Comment: Puts! Essa eu não sabia! Quando quero saber se um diretório existe, eu uso `is_dir`. PHP confuso!
Comment: vamos combinar: `file_exists` pra saber se um diretório existe, é muito sem noção! Muito incoerente!
Comment: Ta na documentação =\. O PHP não é coerente em nada. Quer dizer so em confusão :D rs
Comment: É que _file_ também pode ter um significado mais amplo, de um item qualquer do _file system_ que pode ser tanto um arquivo como um diretório. Veja por exemplo na [Wikipedia](https://en.wikipedia.org/wiki/Computer_file): _"Within this definition, it is of paramount importance that the term "file" includes directories."_
Comment: @Piovezan, entendi sua colocação. Faz sentido
Comment: @Piovezan, editei a resposta, rs nunca tinha ouvido esse termo 'arquivo regular'.
Answer: O is_file retorna true apenas se o caminho for de um arquivo(não diretório/symlink). O file_exists não faz essa distinção e retorna true se "algo" existir no caminho.
EDIT (só pra complementar)
Há funções equivalentes ao is_file para verificar diretórios e symlinks, estas são is_link1 e is_dir2.

http://php.net/manual/en/function.is-link.php
http://php.net/manual/en/function.is-dir.php
Comment: +1 Essa informação dos links simbólicos são importantes.
Answer: Documentações dos métodos:
file_exists() - Checa se um arquivo ou diretório existe
is_file() - Informa se o arquivo é um arquivo comum (não é diretório)
Referências:
http://php.net/manual/pt_BR/function.file-exists.php
http://php.net/manual/pt_BR/function.is-file.php
Answer: is_file verifica se o arquivo é um arquivo válido/existente. Mas não funciona se verificar apenas diretórios.
var_dump(is_file('a_file.txt')) . "\n";
var_dump(is_file('/usr/bin/')) . "\n";

retorno:
bool(true)
bool(false)

Em contrapartida, file_exists funciona, também, para verificar a existência de diretórios.
Um ponto a se levantar é:
O que se espera de uma função que faz/verifica mais de uma coisa? Que ela seja mais lenta em comparação a outras. Seria interessante fazer testes a respeito disso e ver qual se sai melhor no seu contexto.
Referências:
Manual: is_file,
file_exists


How to use cuda stream priority on GTX970?

Question: Recently nvidia released cuda 7.5, and announced that the interface should be able to be used on other Video cards, not just quadro and tesla.  But as I tested on my GTX 970, the cudaDeviceGetStreamPriorityRange retuns -1 and 0. The compute capability of GTX 970 is 3.5, and it should support configurable stream priority as of cuda 6.0.
Comment: Many thanks, Because I'm working on a subject that could support multiple kernel for the same time. The point is I want to schedule them in a priority queue. I want to make sure the one with the highest priority could always run first. But because I'm working on a work station that based on a PC, so I can't use a tesla instead.
Answer:
Is it possible to use cuda priority on GTX970?

Yes, it is possible, and the return values from the cuda runtime API function cudaDeviceGetStreamPriorityRange of 0 ("LOW PRIORITY") and -1 ("HIGH PRIORITY") are correct (<-- refer to slide 70, it has not changed for Maxwell GeForce).  There are only 2 priority levels offered in this case.  (That could change in the future, for future GPUs or CUDA versions.  That is why the runtime API function is provided.)
You may also be interested in reading the relevant documentation or running or studying the relevant cuda StreamPriorities sample code.
Comment: Thanks,In fact I wish to launch multiple kernel. And I'm working on a PC station, I can't use tesla instead. If I still want to make GTX 970 to support priority with larger range(more than two), I guess I must use some trick, such as: launch a kernel, lock and wait until it finishes, then pull a kernel with the highest priority in my queue, launch it again. Is it possible to do so? I do hate it but my boss force me to figure out an idea.
Comment: Yes, you'll have to use "some trick".  There are only 2 priority levels supported in this case.  As you say, you could dispatch kernels by priority on the host, if that fits your application design.