Show that $x^4-x^2+1$ is irreducible over $\mathbb{Q}$

Question: My attempts:
I cannot apply the Eisenstein's criteria here, because there is no prime number that divides the constant term i.e. $1$ Taking a translation of the form $x \rightarrow x+a$ does not solve this issue either.
Next, I tried the mod tests: $\operatorname{mod}2$ doesn't work since $x^4-x^2+1=(x^2+x+1)(x^2-x+1)$, similarly in $\operatorname{mod}3$ $x^4-x^2+1=(x^2+1)^2$. Now I can go on and maybe eventually find a $\operatorname{mod}p$ that works, but that is very time consuming, specially in examinations.
So, I'll use the rational root test. The possibilities for roots are $\pm 1$ and it is easy to see that neither is a root.
The only possibility left then are quadratic factors, say, $(x^2+ax+b)(x^2+cx+d)=x^4-x^2+1$
This gives me a set of equations $bd=1, a+c=0, b+d+ac=-1$. So either $b=d=1$, in which case $a=\pm \sqrt3 \notin \mathbb{Q}$, or $b=d=-1$, which gives $a=\pm i \notin \mathbb{Q}$.
So such factorization is not possible and hence the given polynomial is irreducible.
Is this solution correct? Also, is there an easier way to solve this? Thank you.
Comment: Or better note that the given polynomial can be written as $x^{4}+2x^{2}+1-3x^{2}$ and thus factorize it as $(x^{2}+\sqrt{3}x+1)(x^{2}-\sqrt{3}x+1)$.
Comment: The polynomial is the $12$ th cyclotomic polynomial.
Comment: @RoddyMacPhee: Since the factorization is unique (via fundamental theorem of algebra) it is clear that the factorization is not possible over $\mathbb{Q} $.
Comment: Curiously, this polynomial is not irreducible modulo any prime. That is because its Galois group has no elements of order four (the Galois group is Klein four). Alternatively, the fact $12\mid (p^2-1)$  for all primes $p>3$ implies that $\Phi_{12}$ has a zero in $\Bbb{F}_{p^2}$ and hence a quadratic factor modulo $p$.
Comment: For finding its roots I recommend  writing it in the form $(x^6+1)/(x^2+1)$. Assuming you know how to use complex polar form to find all the roots.
Comment: As Peter said this is the 12th [cyclotomic polynomial](https://en.wikipedia.org/wiki/Cyclotomic_polynomial). They are all irreducible, but the proof is [not quite trivial in general](https://paramanands.blogspot.fi/2009/12/gauss-and-regular-polygons-cyclotomic-polynomials.html). In the present case you can still find the zeros in closed form, and, following Paramanand Singh's advice, check that no combination gives rise to a factor with rational coefficients. Edit: I corrected the link to point at Paramanand's blog, because that is more thorough.
Comment: Finding enough primes of the form $x^4-x^2+1$ also shows the irreducibility. In the range $[1,100]$ there are already $29$  $x$-values such that $x^4-x^2+1$ is prime , more than enough. Does anyone know, how many primes we exactly need depending on the degree to ensure the irreducibility ?
Comment: The factorization over $\mathbb{R}$ that @Paramanand Singh: gave should take care of it.
Comment: You can easily find roots of this polynomial and thus confirm the factorization as a product of two quadratics and each of them has some irrational coefficients.
Comment: @ParamanandSingh but the sqrt of 3 is not rational so this is not showing what is wanted.
Comment: @JyrkiLahtonen, see also [On the Reducibility of Cyclotomic Polynomials over Finite Fields](http://web.mit.edu/rsi/www/pdfs/papers/2005/2005-bretth.pdf).
Comment: @lhf Thanks for the reference. I have [covered](https://math.stackexchange.com/a/536029) [that](https://math.stackexchange.com/a/153471) [too](https://math.stackexchange.com/a/172558) [many](https://math.stackexchange.com/a/812622) [times](https://math.stackexchange.com/a/305123) [here](https://math.stackexchange.com/a/1399170) already, so I should hold back :-). For a while at least.
Comment: @lhf: I apologize about the knee-jerk movement. The link actually **is** interesting. Thank you!
Comment: See also: [Factoring $x^4 - x^2 + 1$](https://math.stackexchange.com/q/726316)
Answer: There are no rational roots, so no linear factors.
If $p(x)$ is a factor of $x^4-x^2+1$ then $p(-x)$ is, too.
If $x^4-x^2+1 = (x^2+a)(x^2+b)$ then $x^2-x+1=(x+a)(x+b)$. Show that $x^2-x+1$ is irreducible.
On the other hand, you'd have to have $x^4-x^2+1=(x^2+ax+b)(x^2-ax+b)$ where $b^2=1$ and $a\neq 0$. This means that $x^4+(2b-a^2)x^2+b^2 = x^4-x^2+1$.
So you need $2b-a^2=-1$. If $b=-1,$ then this means $a^2=-1$, and if $b=1$ then $a^2=3$.
Comment: The polynomial is $x^4-x^2+1$, not $x^4+x^2+1$.
Comment: Whoops, yes, fixed. Same argument applies, and actually works for $x^4-x^2+1$. :)
Answer: Another approach which I saw Robert Israel use here would be to note that $x^4-x^2+1$ takes on prime values for $x=\pm2,\pm3,\pm4,\pm5$ and $\pm9$.  That's ten points, so that one of the quadratic factors would have to take on the value $\pm 1$ at least five times.  Finally one of the quadratic factors would have to take on either $+1$ or $-1$ at least 3 times which is impossible for a quadratic, since a non-constant polynomial that takes the same value three times must have degree at least three.
Answer: $$(x^4-x^2+1)(x^2+1) = x^6+1$$
implies:
$$ x^4-x^2+1 = \frac{x^6+1}{x^2+1} = \frac{(x^{12}-1)(x^2-1)}{(x^6-1)(x^4-1)} = \Phi_{12}(x) $$
hence the LHS is irreducible over $\mathbb{Q}$ since it is the minimal polynomial of $\exp\left(\frac{2\pi i}{12}\right)$.
The irreducibility of cyclotomic polynomials is a well-known fact, proved here.
Comment: You were may be the fourth or fifth viewer to make the observation that this is $\Phi_{12}$. So without a proof this is IMO worth a comment only.
Comment: Yes, it is well known, but apparently not to the asker, so it is not useful to just bluntly state that this polynomial is irreducible. Not even a link. And the proof is not [as simple](https://paramanands.blogspot.fi/2009/12/gauss-and-regular-polygons-cyclotomic-polynomials.html) as you claim. Of course, by assuming that the Galois group is what it is, the proof does become trivial.
Comment: @JyrkiLahtonen: a proof of what? The irreducibility of cyclotomic polynomials should be well-known, and the equality between $\Phi_{12}$ and $x^4-x^2+1$ **is** proved through the shown decomposition, matching the decomposition given by the Moebius inversion formula.
Answer: Let $r(x)$ be the resolvent cubic of your polynomial. Then $r(x)=x^3-2x^2-3x$. The roots of $r(x)$ are $-1$, $0$, and $3$, none of which is the square of a non-zero rational number. Furthermore, your polynomial has no rational root and the coefficient of $x$ in $r(x)$ is not a perfect square in $\mathbb Q$. Therefore your polynomial is irreducible in $\mathbb{Q}[x]$.
Answer: You can use wonderful criterion of Murty's (see Theorem 1):

Let $f(x)=a_mx^m+a_{m-1}x^{m-1}+\dots+a_1x+a_0$ be a polynomial of degree $m$ in $\mathbb{Z}[x]$ and set $$H=\max_{0\leq i\leq m-1} |a_i/a_m|.$$
  If $f(n)$ is prime for some integer $n\geq H+2$, then $f(x)$ is irreducible in $\mathbb{Z}[x]$.

In this case it works because $f(3)=73$ is a prime.


WPF DataTrigger - Setting ListBoxItem IsSelected

Question: I have the following data trigger on the ListBoxItems in my Multi-selection ListBox
<DataTrigger Value="True">
    <DataTrigger.Binding>
        <MultiBinding Converter="{StaticResource DisableWorkItemConverter}">
            <Binding ElementName="MainForm" Path="PickedWorkItemID"/>
            <Binding Path="Id"/>
        </MultiBinding>
    </DataTrigger.Binding>
    <Setter Property="IsEnabled" Value="False"/>
    <Setter Property="IsSelected" Value="False"/>
</DataTrigger>

IsEnabled gets set fine, but IsSelected does not get set.  How can I fix that?
I tried taking out IsEnabled to see if it was conflicting with IsSelected, but the Item remained selected when it should not.
Just to reiterate, I can tell the bindings and the converter are working fine, because IsEnabled works correctly.  But for some reason IsSelected will not un-set.

Edit: It just occurred to me that I may not want this to work like IsEnabled.  Because when this trigger evaluates false, the item gets re-enabled.  I would not want a previously unselected row to get selected just because this trigger is no longer true.
Any ideas?  Basically I don't want any of the disabled rows to be selected.

Edit 2:
I tried adding a normal trigger hoping it would chain off the data trigger and that did not work either.

Comment: In reproducing your problem, I've found that if I set the ListBoxItem IsSelected=True in a trigger, then I can set it to False in a trigger as well.  Once the user selects the item, though, the trigger will no longer change IsSelected.
Comment: Hmmm, that is interesting.  Does not bode well for me finding a way to remove the selection.  Thanks for looking into it.
Answer: It seems that once the "IsSelected" property is set, whether by user or in code behind, the setter will no longer work.  I'm not sure if there is any way around that, but there is at least a hack that would work in your specific case.  You could register a handler for the "IsEnabledChanged" event on your ListBoxItem and then check your data condition and set IsSelected in the handler if the data calls for it.
Example:
private void ListBoxItem_EnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
{
    ListBoxItem senderItem = (ListBoxItem)sender;
    if (YourDataCondition == true)
    {
        senderItem.IsSelected = false;
    }
}

The only other solution I've been able to find would be to add some dependency property to your ListBoxItem, register a similar method to its "OnPropertyChanged" event, and change that property in your DataTrigger.
Here is someone else's attempt to do this that I haven't been able to verify yet.


vermelho/negativo e verde/positivo

Question: Tenho uma tabela que, hora o valor é negativo e, hora é positivo. Gostaria que esse valores ficassem verdes ou vermelhos. Mas, não consegui fazer isso. Atualmente meu select esta sendo apresentado dessa maneira:
(php, myadmin, pdo)

<?php
        $sql = $pdo->prepare("SELECT sum(premio) as premio from home
WHERE id_user = :id_user;");
        $sql->bindValue(":id_user", $id);
        $sql->execute();

        if ($sql->rowCount() > 0) {
            foreach ($sql->fetchAll() as $item) {
        ?>

        Ganho
         R$ <?php echo $item['premio'];?>

     <?php
        }
        }
        ?>

Comment: Bem-vindo Gabriel Alves ao Stack Overflow em Português. Cãso nã fazer um tour pelo sita em o tenha feito seria interessante https://pt.stackoverflow.com/tour
Answer: Use uma condicional para setar um estilo a td verificando o valor de $item['premio']
<?php
      $sql = $pdo->prepare("SELECT sum(premio) as premio from home WHERE id_user = :id_user;");
        $sql->bindValue(":id_user", $id);
        $sql->execute();

        if ($sql->rowCount() > 0) {
            foreach ($sql->fetchAll() as $item) {

            //valor
            $premio = $item['premio'];

                //condicional
                if ($premio<0){
                    $cor='red';
                }else{
                    $cor='green';
                }
?>

        Ganho
        <td style='color:<?php echo $cor;?>'> R$ <?php echo $premio;?>

<?php
   }
   }
?>

Comment: Leo muito obrigado, foi muito mais simples que imaginei e alcançou exatamente o objetivo. Ultima coisa, na minha tela rome terá muitos resultados , você acha uma ma pratica fazer isso dessa forma, (separadamente para cada resultado) MAS JA VLW MUITO OBRIGADO.
Comment: @GabrielAlves, não acho uma má pratica, não tem como não aplicar separadamente para cada resultado mesmo que seja com class css

vermelho/negativo e verde/positivo


Estimation of time for a specific value of a variable

Question: I have a data set:
require(xts)
days<-seq(as.Date("2016-05-01", format="%Y-%m-%d"), as.Date("2016-07-31", format="%Y-%m-%d" ), by= 1)
df.days<-xts(x = data.frame(Empty=rep(NA, length(days))), order.by=days)
df.norm <- rnorm(10000, 40, 5)
df.norm <- df.norm[df.norm > 30 & df.norm < 50]
SAMPLE <-sample(df.norm, length(df.days[.indexwday(df.days)==1]), replace=FALSE)
df.weeks<-xts(SAMPLE, order.by = index(df.days[.indexwday(df.days)==1]))
df.data<-merge.xts(df.weeks,df.days)
df.data<-df.data[,1]
colnames(df.data)[1]<-"variable1"

Now suppose we do not the true distribution of the variable1 but its underlying process tends to approach 40 over days.

I want to know at what date the variable1 will be equal to 40.

What is the best  method applicable to this case?
Some options I can think of are Spline, Expectation Maximization, and probably Kriging. Kindly help me do this in R.
Answer: Expectation-Maximisation is a method for optimizing parameters, rather than interpolation. As to whether to use kriging or spline interpolation, I would suggest that splines are perhaps conceptually simpler and a better first port of call.
The easiest option, in my opinion, is to use the loess() function from the core package, which is nicely documented (use: ?loess in RStudio to see the documentation). Loess has a width parameter which needs to be specified, which can be optimised through generalised cross validation. The documentation should contain enough example code to get you moving.
For some example code and a discussion of the limits of LOESS regression, maybe read: http://www.fromthebottomoftheheap.net/2012/07/24/whats-wrong-with-loess-for-palaeo-data/
Comment: In principle, yes, though you'd have to think about how to use it with your dataframe. If your aim is simply to find a smooth function underlying your data and using this to predict additional points, many regression methods will be suitable. These typically come with some governing assumptions, so make sure you are clear on what those are. For a very general introduction to krigingsee Rasmussen and Williams' textbook Gaussian Processes for Machine Learning, which is freely available online.
Comment: Thanks for help. Is it also possible to do kriging on my data?
Comment: Please see the question again. I have edited it.
Comment: Kindly See my edited question. The focus of this question is what You have just answered.
Comment: How do I apply the concept we just discussed to this data?


GTest: Handle Segmentation Fault

Question: I'm using GTest for unittesting my project.
One of the functions I want to test terminates with a Segmentation Fault, which is is not the correct behavior of this function.
I want gtest to report this error, like every other error, but it doesnt. It doesnt run other test cases and it doenst print a report at the end.
It there a way to get a correct report from gtest for this kind of behavior?
Answer: You didn't link any code example, so the best answer I can give you is very general.
Your problem is either:

Your function is incorrect and is segmentation faulting (edge cases or main body)
You wrote your test badly, and it (the test itself) is segmentation faulting

Seg Faulting happens when your program/test tries to do something it isn't allowed to do (i.e.. you try to dereference a null ptr, access memory that isn't yours, etc..). Google Test is not able to handle the signal SIGSEGV (nobody is), so your program will crash. Seg Faults are the operating systems way of telling you that you did something illegal and they instantly terminate your program. You need to fix the segmentation fault in order to get results. I would recommend doing the following things:

Learn how to use GDB, and run your program in GDB to figure out where it is segmentation faulting
Use print statements to figure out where your program is segmentation faulting.
Comment: Maybe my question was not clear enough. In this case I know where the error is, but my problem is, that one segfault prevents that I get an gtest result. I hope that gtest has a smart feature which allows to run alle other tests and report this one as failing with segfault.
Comment: A Seg Fault kills the executable, so Google Test is no longer running after it occurs (and can't do anything about it). I would recommend that you break your tests up into multiple executables, and have your CI job search the output for failures, and fail the pipeline if a seg fault occurs.  The only real way to have some of your tests still produce results is to split up your executable into multiple executables, and hope they don't all seg fault. If they all Seg Fault, you will never get GTest's normal end of run output.
Comment: Does that help?
Comment: Not really, my goal was to get full gtest results, and I don't understand why googletest can to death tests, but can't handle segfaults.

GTest: Handle Segmentation Fault


How do I prove $\tan1 < \frac{\pi}{2}$?

Question: Prove that the equation
$$\sin x \sin({\sin x}) = \frac{\pi}{2} \cos({\sin x})$$
has no real solutions.
Let $t=\sin x$, $-1\leq t\leq 1$. Then the expression above is equvalent to $t\sin t = \frac{\pi}{2} \cos t$. As the function $f(t)=t\sin t - \frac{\pi}{2} \cos t$ is even, and $t=0$ is not a solution, I have to prove that $f(t)$ has no positive roots ($t>0$).  So, for the left side $0<t\leq 1$ and $0<\sin t\leq \sin1$, then $t\sin t\leq \sin1$. For the right side $\cos t\geq \cos1$, so $\frac{\pi}{2} \cos t\geq \frac{\pi}{2} \cos1$. The objective is to prove that $\sin1<\frac{\pi}{2} \cos1$, or, equivalently, $\tan1 < \frac{\pi}{2}$.
I don't know how to approach this inequality. The arguments and the values are mixed up.
Comment: @CalumGilhooley I don't agree with close votes on a question like this.  It's a perfectly reasonable math question, and one that is likely to be well beyond the capabilities of a beginner, as your answer shows.  In fact, a beginner is likely to have no idea how to start.  (Also, I would never vote to close a question from new contributor, unless it was offensive in some way.)
Comment: Well, they're [close](https://www.wolframalpha.com/input/?i=pi%2F2-tan(1))
Comment: **Welcome** to the site !
Comment: @CalumGilhooley it's a new trend on MSE that some people in the CRUDE chatroom think it's OK to delete others' posts just because the question had been closed before. Do post the issue on meta, but don't raise your expectations high.
Answer: We can use the Taylor series and alternating series theorem to say
$$\sin 1 \lt 1-\frac 1{3!}+\frac 1{5!}=\frac {101}{120}\\
\cos 1 \gt 1-\frac 1{2!}+\frac 1{4!}-\frac 1{6!}=1-\frac 12+\frac 1{24}-\frac 1{720}=\frac{389}{720}\\
\tan 1=\frac {\sin 1}{\cos 1} \lt \frac {606}{389} \lt 1.56 \lt \frac {\pi}2$$
Answer: This is a Community Wiki repost of one of several deleted answers to a deleted question from last year: Compare $\arcsin (1)$ and $\tan (1)$.
[I have taken this opportunity to incorporate a simplification - but only a slight one - I made later in a comment.]
I would be pleased if we were allowed to revisit the other deleted answers, too.

One can write:
$$
\frac{1}{\sqrt{1 + \tan^21}} = \cos1 = 1 - 2\sin^2\frac{1}{2} >
\frac{17639}{32768} > \frac{17632}{32768} =
\frac{551}{1024},
$$
because
$$
\sin\frac{1}{2} <
\frac{1}{2} - \frac{1}{2^3\cdot3!} + \frac{1}{2^5\cdot5!} =
\frac{1920 - 80 + 1}{3840} < \frac{1845}{3840} = \frac{123}{256}.
$$
On the other hand, using Archimedes's lower bound,
$\pi > 3\tfrac{10}{71}$:
$$
\frac{1}{\sqrt{1 + \left(\sin^{-1}1\right)^2}} =
\frac{1}{\sqrt{1 + \left(\frac{\pi}{2}\right)^2}} <
\frac{1}{\sqrt{1 + \left(\frac{223}{142}\right)^2}} =
\frac{142}{\sqrt{69893}} <
\frac{142}{\sqrt{69696}} =
\frac{142}{264} = \frac{71}{132}.
$$
So, one can prove that $\tan1 < \sin^{-1}1$ by proving that:
$$
\frac{551}{1024} > \frac{71}{132},
$$
which simplifies to $33 \times 551 > 71 \times 256$, that is,
$18183 > 18176$ - which is true.
Comment: [Repost of most of a deleted comment.] Honestly, having seen Ross Millikan's exemplary simple answer to the present question, I've lost interest in trying to revive last year's question and answers. I admit to a mild, sneaky curiosity as to whether everybody else made as much unnecessary fuss in their answers as I did in mine [...]

How do I prove $\tan1 < \frac{\pi}{2}$?


Why sin and cos do not get the same result that as tan, in this case?

Question: Let $x=3$ and $y=3$. Then $\tan\theta = \frac{3}{3} = 1$.
However if we use pythagorean theorem to find the value of hypotenuse and $\sin$ or $\cos$ function we get very different value. Here it is:
$$\text{hypotenuse} = \sqrt{3^2 + 3^2} = \sqrt{18} = 3\sqrt{2}\\
\sin\theta = \frac{3}{3\sqrt{2}} = \frac{1}{\sqrt{2}} \text{ or:}\\
\cos\theta = \frac{3}{3\sqrt{2}} = \frac{1}{\sqrt{2}}
$$
What I am doing so horribly that getting such a wrong result? I think this is wrong because the value of $\theta$ should be equal regardless of trig function as long as the value of $x$, $y$ and $r$ are the same.
Comment: Everything is correct. What's the problem?
Comment: But you're not computing $\theta$, you're computing $\tan\theta$,$\sin\theta$ and $\cos\theta$...
Comment: The value of theta should not be different. Same x and y value should always give you the same angle.
Answer: Recall that $\tan(\theta)=\frac{\sin(\theta)}{\cos(\theta)}$, which is true for the values that you used, since $\frac{\frac{1}{\sqrt{2}}}{\frac{1}{\sqrt{2}}}=1$.
Answer: There is nothing wrong here, you have a triangle with sides $3,3,3\sqrt 2$. Its angle $\theta$ (the $45$ degree one) has $\tan(\theta)=1$ and $\cos(\theta)=\sin(\theta)=\frac{1}{\sqrt2}$
The value of theta is quite constant, in fact it is $45°$ in degrees or $\frac\pi4$ in radians. It is true, of course, that $\tan(\theta)\neq \sin(\theta)$, but that is nothing unusual.


Symmetric and homogeneous three variable inequality with radicals.

Question: While trying to solve a problem, I got the following inequality which appears correct, but I cannot prove.  For positive $x, y, z$,
$$\sum_{cyc} \frac{x}{y^2+z^2} \ge \sum_{cyc} \sqrt{\frac{y^2+z^2}{2(x^2+y^2)(z^2+x^2)}}$$
Equality is obviously when $x=y=z$.  Tried AM-GM (takes it in opposite directions), Cauchy Schwarz (not tight enough) etc. with no luck. Adding constraints doesn't seem to simplify either.  Any hints welcome.
Answer: By C-S $\left(\sum\limits_{cyc}\sqrt{\frac{y^2+z^2}{2(x^2+y^2)(x^2+z^2)}}\right)^2\leq\sum_(y^2+z^2)\sum\limits_{cyc}\frac{1}{2(x^2+y^2)(x^2+z^2)}=\frac{2(x^2+y^2+z^2)^2}{\prod\limits_{cyc}(x^2+y^2)}$.
Thus, it remains to prove that
$\left(\sum\limits_{cyc}(x^5+x^3y^2+x^3z^2+x^2y^2z)\right)^2\geq2(x^2+y^2+z^2)^2(x^2+y^2)(x^2+z^2)(y^2+z^2)$.
Let $x+y+z=3u$, $xy+xz+yz=3v^2$ and $xyz=w^3$.
Hence, we need to prove that $f(w^3)\geq0$, where
$f(w^3)=(81u^5-135u^3v^2+54uv^4+9u^2w^3-5v^2w^3)^2-$
$-2(3u^2-2v^2)^2(81u^2v^4-54v^6-54u^3w^3+36uv^2w^3-w^6)$.
We see that $f'(w^3)=2(81u^5-135u^3v^2+54uv^4+9u^2w^3-5v^2w^3)(9u^2-5v^2)+$
$+2(3u^2-2v^2)^2(54u^3-36uv^2+2w^3)\geq0$.
Id est, $f$ is an increasing function, which says that $f$ gets a minimal value for extremal value of $w^3$, which happens in two following cases only.

$y=1$ and $z\rightarrow0^+$, which gives $(x^2+1)^2(x^4+2x^3+x^2+2x+1)(x-1)^2$;
$y=z=1$, which gives $(x^2+1)^2(x^3+2x^2+x+8)x(x-1)^2\geq0$. Done!
Comment: Thanks. Wish there was a method with AM-GM etc though.


probability choosing letters

Question: Suppose we choose an n letter word at random (uniformly) from $\Sigma^n\;$where $\; \Sigma = \{a,b,c\}$. What is the probability that the letters of the word are in (increasing) alphabetical order?
So from sum of events / sum of all possible events:
I believe the answer is $\dfrac{n(n-1)(n-2)}{3!.3^n}$.
Is that correct?
Comment: Consider the factorial again.
Answer: You have got a mistake. (I did it too at first attempt). For $n=2$ your formula gives $0$. Which is obviously not correct!
The probability is (number of ordered words)/(number of words).
Number of words is $3^n$ - this is easy.
Difficult part is to calculate the number of ordered words.
Let's take an ordered word. Let's put a '|' character after all the 'a' letters. Then we put a '|' after all the 'b' letters. Positions of these two '|' characters in $n+2$-letter word define define the original ordered word: '|' characters split the range into 3 parts (some of them may be empty) and we fill the parts with 'a', 'b' and 'c'.
So we need to calculate the number of possibilities to put 2 '|' characters into $n+2$ positions. Which is ${n+2 \choose 2}$.
And the final answer would be ${n+2 \choose 2}/3^n$.
Comment: I get it now! Thank you very much!

probability choosing letters


No URLs in dashboard

Question: After installing Drupal I cannot use the dashboard menu because none of the URLs are found. I cannot google my way to find a solution to this so.
Comment: What is your actual question? Also, is this about Drupal 5?
Answer: Check that the .htaccess file exists in the Drupal root. Sometimes people unzip/untar or copy paste Drupal directories and this file is excluded by some operating systems and file transfer programs.
Drupal 7 .htaccess: http://cgit.drupalcode.org/drupal/tree/.htaccess?h=7.x
Drupal 8.2.x .htaccess: http://cgit.drupalcode.org/drupal/tree/.htaccess
This is usually the cause of what you report.
Otherwise, this could be an issue with how Apache or IIS is setup to serve your Drupal site. Since you can really get in the weeds with server configurations such as Apache, it is recommended you use something like Acquia Dev Desktop or DrupalVM to install and run a Drupal site locally, so you can sidestep issues and run a local site under generally accepted best practices for a LAMP stack tuned for Drupal.

No URLs in dashboard


How to get the form field label of a multi-value field

Question: In hook_form_user_form_alter I need to get the title of each field. When I dump a normal (single-value) field #title is an array value, like this:
array (size=13)
  '#title' => string 'Name' (length=13)
  '#title_display' => string 'before' (length=6)

but for fields that can contain more than one value, #title is an object that looks like this:
array (size=13)
  '#title' =>
    object(Drupal\Core\StringTranslation\TranslatableMarkup)[1544]
      protected 'translatedMarkup' => null
      protected 'options' =>
        array (size=0)
          empty
      protected 'stringTranslation' =>
        object(Drupal\Core\StringTranslation\TranslationManager)[285]
          protected 'translators' =>
            array (size=1)
              ...
          protected 'sortedTranslators' =>
            array (size=1)
              ...
          protected 'defaultLangcode' => string 'en' (length=2)
          public '_serviceId' => string 'string_translation' (length=18)
      protected 'string' => string '@title (value @number)' (length=22)
      protected 'arguments' =>
        array (size=2)
          '@title' => string 'Name' (length=19)
          '@number' => int 1
  '#title_display' => string 'invisible' (length=9)
  '#description' => string '' (length=0)
  '#field_parents' =>
    array (size=0)
      empty
  '#required' => boolean false
  '#delta' => int 0
  '#weight' => int 0
  '#type' => string 'textfield' (length=9)
  '#default_value' => string 'John Doe' (length=8)
  '#size' => int 60
  '#placeholder' => string '' (length=0)
  '#maxlength' => int 255
  '#attributes' =>
    array (size=1)
      'class' =>
        array (size=2)
          0 => string 'js-text-full' (length=12)
          1 => string 'text-full' (length=9)

If I just refer to #title, for the multi-value field I end up with:
Name (value 1)

What is the proper way of obtaining the title, and what causes the difference?
Answer:
What is the proper way of obtaining the title, and what causes the
  difference?

The cause is this code in the field widget:
  // For multiple fields, title and description are handled by the wrapping
  // table.
  if ($is_multiple) {
    $element = [
      '#title' => $this->t('@title (value @number)', ['@title' => $title, '@number' => $delta + 1]),
      '#title_display' => 'invisible',
      '#description' => '',
    ];

This t($string, array $args = [], array $options = []) function returns a TranslatableMarkup object.
You can cast the translatable markup as string to obtain the title, but normally you don't have to. See both answers here  How to get the string value from the function CountryManager::getStandardList()?
Comment: If you look at the @ string property, it is what I receive when I cast (string)$form['field_name']['widget'][0]['#title'] as suggested at that link. I see further down an @ arguments with a @title property that does not contain 'value @ number', but am unclear how to get to it.
Comment: The answer given is correct in terms of the cause. The way I found to get to just the label without the value suffix is: $form[field]['widget'][0]['#title']->getArguments()['@title']


map.find() returns seemingly randomly map.end()

Question: I am using a custom comparator in a C++ map. Unfortunately map.find() often doesn't find the desired entry in the map.
Code to reproduce this is very simple:
#include <array>
#include <iostream>
#include <map>

using namespace std;

typedef struct DATA_t {
  array<int, 4> data;
} DATA_t;

struct DATA_cmp {
  bool operator()(const DATA_t& a, const DATA_t& b) const {
    for (int i = 0; i < a.data.size(); ++i)
      if (a.data[i] < b.data[i]) return true;
    return false;
  }
};

int main(int argc, char** argv) {
  map<DATA_t, int, DATA_cmp> index;
  DATA_t data1 = {1, 2, 4, 8};
  DATA_t data2 = {1, 3, 5, 7};
  DATA_t data3 = {0, 6, 7, 8};
  DATA_t data4 = {0, 1, 1, 2};
  index[data1] = 1;
  index[data2] = 2;
  index[data3] = 3;
  index[data4] = 4;
  cout << "data1 " << (index.find(data1) == index.end() ? "not found" : "found") << endl;
  cout << "data2 " << (index.find(data2) == index.end() ? "not found" : "found") << endl;
  cout << "data3 " << (index.find(data3) == index.end() ? "not found" : "found") << endl;
  cout << "data4 " << (index.find(data4) == index.end() ? "not found" : "found") << endl;
  return 0;
}

Output should be for all lines "found", but I get:
data1 found
data2 not found
data3 found
data4 found

I suspect the problem is my comparison function, but I don't see my mistake.
Comment: BTW, in c++, `typedef struct S {} S;` --> `struct S {};`, as I showed in the demo in my answer.
Answer: Your comparison function is not correct. Consider what happens for the following keys:
{ 1, 2, 3, 4 }  // #1
{ 1, 3, 2, 4 }  // #2

Now comparing #1 with #2 will return true since the 2nd index is less (2 < 3). But, comparing #2 with #1 will also return true since the 3rd index is less (2 < 3).
This violates the requirements that the keys have a strict weak ordering, i.e. a < b and b < a can't both be true.
You can fix this by just using operator< on arrays like this:
struct DATA_cmp {
  bool operator()(const DATA_t& a, const DATA_t& b) const {
    return a.data < b.data;
  }
};

Here's a demo.


Convergence In probablility implies convergence in distribution?

Question: I'm currently working on the following exercise:

If $X_n$ is sequence of randon maps with values on a metric space $(S,d)$. Show tha convergence in probablity to a randon map $X$ implies $P\circ X_n^{-1}\Rightarrow P\circ X^{-1}$ as $n\to \infty$.

where $P$ is the a Borel probability on $S$.

Observation: Here convergence in probability means that given $\epsilon>0$ one has $P(d(X_n,X)>\epsilon)\to 0$ as $n\to \infty$.

I was trying to prove it without success when the following example came:
Example: Consider the probability space $([0,1].\mathscr{B}([0,1]),\lambda)$ onde $\lambda$ is the lebesgue measure. Also consider the sequence of randon maps $X_n=n\cdot 1_{[0,\frac{1}{n}]}$ and $X\equiv 0$. So $X_n\to X$ in probability. But on the other hand if $f=id$ in $[0,1]$
$$
1=\lim_{n\to \infty}\mathbb{E}f(X_n)\neq \mathbb{E}f(X)=0
$$
so $P\circ X_n^{-1}\not\Rightarrow P\circ X^{-1}$ as $n\to \infty$.
Question: Are my example correct?? If not  why, and how to prove?
Comment: "Observation: Here convergence in probability means that..." Certainly not (and the fact that X disappears from this formulation should worry you, shouldn't it?).
Comment: Yes are you right. Corrected.
Answer: The definition of weak convergence is
$X_n \implies X$ iff for all $f$ continuous and bounded you have $$\int_{\mathbb{R}} f(x) dF_n(x) \rightarrow \int_{\mathbb{R}} f(x) dF(x)$$
But, in your case $P \circ X_n^{-1}$ is a distribution in $\mathbb{R}$, so $f=id$ isn't bounded...
HINT: Given two random variables $X,Y$ then for all $a$ and $\epsilon$ you have
$$P(Y \le a) \le P(X\le a +\epsilon)+P(d(X,Y) > \epsilon)$$
then use that $X_n \implies X$ iff $F_n(x) \rightarrow F(x)$ for all $x$ where $F$ is continuous.
Comment: Thank you Rodrigo,I knew it was something minor that was missing in my view, but could not find.


Binomial logistic regression with multiple Likert-scale (ordinal) predictors

Question: My colleague wants to perform binomial logistic regression with data that include:

binomial (T/F) response variable
35 different Likert-scale (1-5) predictor variables to choose between.
N = 300

They are trying to do the analyses in R.
At first I considered suggesting glm as follows:
glm(Y ~ X1 + X2 ..., data = dataset.name, family = binomial)

However, I don't think it's appropriate to treat the likert-scale predictors as continuous or as categorical data using factor(). These predictors are truly ordinal data.
Although a number of R packages exist that can fit one or more types of ordinal regression models, the most comprehensive among these seems to be the VGAM package.
However, I'm not sure how to incorporate a binomial response in a VGAM model.
Perhaps this isn't possible? Perhaps another package would be better?
Question:
What would be the appropriate way to perform a binomial logistic regression in R incorporating ordinal-scale predictor variables?
Answer: Ordinal regression is for ordinal responses, so you do not need such models. You can use logistic regression, the question is how to represent the ordinal predictors. That depends also on information you did not give us, such as number of observations (logistic regression tends to be rather data-hungry, see Minimum number of observations for logistic regression?.)
In R you can represent the likert variables as ordered factors, that way they will be represented as orthogonal polynomials. But that will use four df for each variables, which is probably to much. As an alternative you can represent them as numeric variables, but use maybe quadratic polys to represent them. That way you get some indication of nonlinearity. Another viewpoint is here: Likert scaled covariates and binary logistic regression
Comment: Thanks for the answer. I'm still working through it. FYI, I've updated my original post to include sample size: 300. I'm not sure if that impacts your answer to any degree. Thanks!


How should a pop shield be set up?

Question: Following answers to a previous question Avoiding Plosives I have bought a simple pop shield.
I'm wondering what the optimal setup is for it, especially in terms of distance between the shield and the mic, and the shield and my mouth.
I'm using a SM58 and many singers seem to get really close, practically kissing the mic... both for technique and because the closer you are, the less bleed you get from other sources.
So do I want the shield practically brushing the mic and then sing as if the shield isn't there, or what?
Answer: Contrary to what Todd Wilcox said, a pop screen is actually more effective if placed further away from the mic.
The main trouble with plosives is that they are pretty directional (see here for a detailed study). That means, if you place the mic pointing straight at your mouth, the plosives will hit it really hard even if there's some distance. Placing the mic only slighly off-axis from your mouth would probably already solve your plosive problem, but this isn't a good idea because it also affects the vocal sound.
A good pop filter works mainly1 by dispersing this "vortex shock" which makes plosives so directional. Behind the screen, the shock spreads out in all directions, which means it decays much faster. However, it still needs some space to disperse: if you're pressing a small-diaphragm condenser mic right into a pop filter, it's pretty useless.
Now, most large-diaphragm mics and also the SM58 have a metal basket that limits the closeness to about an inch. This is often quite enough, but note that the SM58 actually also has a pop screen built right into that basket – and usually that's good enough, but in your case apparently not. So, placing another pop screen close to the mic will then probably also not be much use.
Instead, I recommend that you talk right into the pop screen, and place the mic about 2" away. Many voice artists do it this way; singers less often (I think they don't need to, because the voice has enough volume in the tones so the plosives aren't such a problem).

†That's how it should be, because then the pop screen won't affect other sounds.
Answer: You want the pop filter normally to be closer to the microphone than the mouth, maybe just about 1" away. Alternatively, you can use the pop filter as a way to keep a singer from getting too close to the mic by positioning it farther away.
You should be at least an inch or so from the pop filter, to reduce the amount of saliva that builds up on it at least. Mic technique for recording is typically very different from live mic technique. Usually I like to have the mic at least 6" - 8" from the singer's mouth when recording, which is way too far away for high volume live situations (it would work for bluegrass with no drums, though).
Mic position regardless of the pop filter isn't just a whole question, it's potentially a whole forum.
For most mics:
The closer you are, the more low end emphasis you get - even to the point of boosting the low end, which isn't always good. The more on-axis you are, the more even the response and the better the high end. The more pointed towards your nose or chest, the more of each of those parts of the sound you will get. Beyond about 12" - 16", the sound can thin out a lot, making the voice sound distant (which can be good for backing vocals), but also you get more of the sound of the room. More or less room can be good or bad depending on how good the room sounds and what kind of sound you're going for. Most rooms that are not build and treated for recording don't sound very good, although you can get special effects with some interesting rooms. Many artists have used bathrooms, stairwells, or long hallways to get different sounds.
Let's look at a few pros:

I notice they both use C12s or clones. Taylor sure has her pop filter close to that very expensive mic.

And Beyonce getting really up close:
Comment: This line "Mic position regardless of the pop filter isn't just a whole question, it's potentially a whole forum." cannot be more true. Totally agree with everything here and while I don't have anything to add, I just want to bring the points made here to your attention as much as possible.
Comment: Definitely agree as well. Regarding position for singer to mic during recording, I was always taught to use a hand-turkey's distance to get the 6-8 inches.

How should a pop shield be set up?


Proof that $\frac{\sin x}{x}, x\in (0,\infty)$ is improperly Riemann integrable.

Question: This is the beginning of the proof that $\frac{\sin x}{x}, x\in (0,\infty)$ is improperly Riemann integrable.
However, I don't understand how to attain the second identity below.
In the first inequality, I can see that $|\lim_{a\to \infty} \int_{N\pi}^a \frac{\sin x}{x}dx| \le \lim_{a\to \infty} \int_{N\pi}^{(N+1)\pi} |\frac{\sin x}{x}|dx$, but how do we get the same inequality for $N\to \infty$? What justifies this change in variables?
Also, similarly, how does this enable us to conclude the second identity?
To get the second identity, we would need $\lim_{a\to \infty} \int_0^{N(a)\pi} \frac{\sin x}{x}dx = \lim_{n\to \infty} \int_0^{n\pi} \frac{\sin x}{x}dx$, but how do we get this?
I mean, I don't understand how we are able to switch the limit from $a\to \infty$ to $N \to \infty$. I can see this intuitively but I would appreciate if anyone could explain how this works rigorously.
For $a>0$ we can find $N=N(a)\in \mathbb{N}$ such that $N\pi \le a <(N+1)\pi$. Thus
$$\int_0^\infty \frac{\sin x}{x}dx = \lim_{a\to \infty} \bigg( \int_0^{N\pi} \frac{\sin x}{x}dx + \int_{N\pi}^a \frac{\sin x}{x}dx\bigg)
=\lim_{N\to \infty} \sum_{i=0}^{N-1} \int_{i\pi}^{(i+1)\pi} \frac{\sin x}{x}dx,$$
where we use
$$\Bigg| \lim_{a\to \infty} \int_{N\pi}^a \frac{\sin x}{x}dx \Bigg| \le \lim_{N\to \infty} \int_{N\pi}^{(N+1)\pi} \Bigg| \frac{\sin x}{x}\Bigg| dx \le \lim_{N\to \infty} \frac{\pi}{N\pi}=0.$$
Comment: For those kind of oscillatory function, integrating by parts is always a good idea, as $ \int_1^\infty \frac{\cos x}{x^2}dx$ is easy to understand
Answer: A more correct chain of inequalities would be
$$\Bigg| \int_{N\pi}^a \frac{\sin x}{x}dx \Bigg| \le  \int_{N\pi}^{a} \Bigg| \frac{\sin x}{x}\Bigg| dx \le \int_{N\pi}^{(N+1)\pi} \Bigg| \frac{\sin x}{x}\Bigg| dx \le \frac{1}{N\pi}\int_{N\pi}^{(N+1)\pi} | \sin x| dx\\= \frac{2}{N\pi}=
\frac{2(N+1)}{N}\frac{1}{(N+1)\pi}\le \frac{4}{a},$$
where $1/(N+1)\pi <1/a \le 1/N\pi$. And now you send $a\to\infty$ to get $0$.
Comment: Thanks that resolves the inequality problem. But how do we get $\lim_{a\to \infty} \int_0^{N\pi} \frac{\sin x}{x}dx = \lim_{N\to \infty} \sum_{i=0}^{N-1} \int_{i\pi}^{(i+1)\pi} \frac{\sin x}{x}dx$? In fact, to split the limit of the sum of the first two integrals into the sum of the limit of the two integrals and use the above identity, don't we need the integrability of $\lim_0^\infty \frac{\sin x}{x} dx$, which is what we want to prove in the first place?
Answer: Perhaps it would be more clear if you maintained the explicit dependence of $N$ on $a$ throughout.  Adding a couple extra steps for clarity, we have that $N(a)\pi\le a\lt(N(a)+1)\pi$ implies
$$\left|\int_{N(a)\pi}^a{\sin x\over x}dx\right|\le\int_{N(a)\pi}^a\left|\sin x\over x\right|dx\le\int_{N(a)\pi}^a\left|\sin x\over x\right|dx+\int_a^{(N(a)+1)\pi}\left|\sin x\over x\right|dx\\=\int_{N(a)\pi}^{(N(a)+1)\pi}\left|\sin x\over x\right|dx\le\int_{N(a)\pi}^{(N(a)+1)\pi}\left|1\over N(a)\pi\right|dx={\pi\over N(a)\pi}$$
Finally, it's clear that $N(a)\to\infty$ as $a\to\infty$ (and vice versa).
Comment: @takecare, as $a$ runs through all (large) real values, $N(a)$ runs through all (large) integer values.  If you like, think of it as $$\lim_{a\to\infty}\int_0^{N(a)\pi}f=\lim_{N(a)\to\infty}\int_0^{N(a)\pi}f=\lim_{n\to\infty}\int_0^{n\pi}f$$
Comment: Yes this is much clearer. But from this, how do we get $\lim_{a\to \infty} \int_0^{N\pi} \frac{\sin x}{x}dx = \lim_{N\to \infty} \sum_{i=0}^{N-1} \int_{i\pi}^{(i+1)\pi} \frac{\sin x}{x}dx$? Also, to split the limit of the sum of the first two integrals into the sum of the limit of the two integrals and use the above identity, don't we need the integrability of $\int_0^\infty \frac{\sin x}{x} dx$, which is what we want to prove in the first place?
Comment: @takecare, writing $$\int_0^{N\pi}f(x)dx=\sum_{i=0}^{(N-1)}\int_{i\pi}^{(i+1)\pi}f(x)dx$$ is a general property for definite integrals.  Keep in mind, this is only the *beginning* of the proof that the improper integral converges.  Presumably what comes next is an inequality of some sort that bounds the sum on the right hand side with a convergent infinite series.
Comment: Right I knew that. I was thinking why $\lim_{a\to \infty} \int_0^{N(a)\pi} f = \lim_{n \to \infty} \int_0^{n\pi} f$. Because the $N$ on the left hand side depends on $a$ but the right hand side doesn't.
Answer: HINT:
You should estimate the integral on a given interval $[a,b]$ and see what happens when that interval moves to infinity. For this, use integration by parts:
$$\int_a^b \frac{\sin x}{x} d x = \int_ a^b (-\cos x)' \frac{1}{x} d x = = - \cos x \cdot \frac{1}{x} \mid_a^b - \int_a^b (-\cos x)(- \frac{1}{x^2})dx= \\=\frac{\cos a}{a} - \frac{\cos b}{b} - \int_a^b \frac{\cos x}{x^2} dx $$
We conclude that
$$\left |\int_a^b \frac{\sin x}{x} d x \right |\le \frac{1}{a} + \frac{1}{b} + \frac{1}{a}- \frac{1}{b} = \frac{2}{a}$$


guitar - open strings in just intonation

Question: has anyone of you tried to tune your guitar to just intonation?
As far as I understand it, it's possible to tune the open strings to just intonation. Consequently, you couldn't fret notes but only use the open strings and harmonics.
I have a Peterson tuner which has a Just Intonation setting. It can be set to keys, however, it still doesn't seem to work. Theoretically, if I tune the guitar to open D, I'd have to set the key to D. Or do I have to use A 440 as reference and tune the strings use A as the key?
There are some guitarists like Stephen O'Malley and Duane Pitre who are using just intonation on normal guitars. However, I cannot find any information on how they do it.
Thanks!
Comment: It's dead easy to tune with just intonation. Simply tune using the harmonics of the strings. And you sure can fret notes but they might not sound as well tuned as you might like. Is your question actually "has anyone done this?" Because yes, I did it for years.
Comment: You say that using the tuner "doesn't seem to work". Please elaborate on that.
Comment: With respect to @ToddWilcox comment, if we calculate the theoretical frequencies for a guitar in standard tuning with accurate 4:3 fourths and an accurate 4:1 fifteenth between the two E strings, and accurate equal-tempered frets, a lot of the fretted notes will be perfectly acceptable.  For example, the fifth fret of the B string (247.5 Hz open frequency) will be 330.3729 Hz instead of 330 Hz, which is close enough to being in tune for virtually every purpose.  The third fret D will be 294.3288 Hz instead of 293.3333 Hz, also close enough for most purposes.
Comment: @Aaron "tuner doesn't seem to work": see my answer explaining why there's no key for which the most commonly specified just intonation scales have a 4:3 ratio for all of the fourths B-E-A-D-G.
Answer: To tune in just intonation, stop tuning your guitar to a tuner!  Tune one string by ear to a pitch reference and then tune the other strings by ear to each other.  To tune two strings to a just fourth, play the seventh-fret harmonic of the higher string against the open lower string (or its twelfth- or fifth-fret harmonic).  For example, once you've tuned your A string to a tuning fork, find your E by playing the seventh-fret harmonic of the A string.  This will put the E string's frequency at ¾ of the A string's frequency, a just perfect fourth.
If you're tuning strings a fifth apart, for example if you're tuning the lowest string to D, reverse the procedure: play the seventh-fret harmonic of the lower string against the open higher string (or its twelfth- or fifth-fret harmonic).
The interval between G and B, of course, is a major third, and a just major third is a 5:4 ratio.  But if you use 5:4 for the major third and 4:3 for the fourths, you will find that your highest string is not 2 octaves above the lowest, a factor of 4:1, but rather (4:3)⁴ × 5:4, which is 320:81 or about 3.95:1.  If you tune the high E string to the low one, or to the seventh-fret harmonic of the A string, and then tune the B string to the E string, then the major third will have a ratio of 81:64 instead of 5:4.

I have a Peterson tuner which has a Just Intonation setting. It can be set to keys, however, it still doesn't seem to work. Theoretically, if I tune the guitar to open D, I'd have to set the key to D. Or do I have to use A 440 as reference and tune the strings use A as the key?

This is probably not working because the tuner is giving you the most common just diatonic scale for the key you're selecting.  This scale has the ratios 1:1, 9:8, 5:4, 4:3, 3:2, 5:3, 15:8, 2:1.  Note that the perfect fifth between 9:8 and 5:3 -- the second and sixth degrees of the scale -- is 40:27 instead of 3:2.  If you invert that, you get a perfect fourth of 27:20 instead of 4:3.
In the key of D, that "unjust" interval is between E and B.  In A, it's between B and F♯.  It looks like choosing D is therefore probably better for open D tuning and A for standard tuning.
But there's another issue, that of the minor seventh.  In other words, in the key of A, where does the tuner put G?  There are three possibilities for the minor seventh: 16:9 (two 4:3 fourths), 9:5 (a 3:2 fifth and a 6:5 minor third) and 7:4 (the acoustically pure seventh from the harmonic series).  In the first case, the ratio between D and G will be 4:3, as expected, but the other two ratios are the more commonly used, so choosing A for standard tuning is more likely to give you an out-of-tune interval there.  In the case of 9:5, it will be 9:5 ÷ 4:3 or 27:20, whereas for 7:4 the ratio will be 7:4 ÷ 4:3 or 21:16.
In conclusion, the most common arrangements of the just diatonic scale have three consecutive 3:2 fifths (in circle-of-fifths order).  Using D major as our example, they are G-D-A-E.  Other perfect fifths are out of tune so the scale can contain some 5:4 major thirds.  The pitches used in standard guitar tuning span four consecutive spots on the circle of fifths, G-D-A-E-B, so it's not possible to pick a key in which the most common just-intonation scales will have all of the fourths at a 4:3 ratio.

As a postscript, there are two related issues that are somewhat beyond the scope of this answer, which is long enough, but that deserve to be mentioned.
The first is the question of the absolute pitch you're tuning to.  If you set your tuner to just intonation in D, does it keep A at 440 Hz, giving D a frequency of 293 ⅓ Hz, it does it build the scale on the equal-tempered frequency of 440 ÷ 2(7⁄12) or approximately 293.6648 Hz?  It probably doesn't matter much, certainly not if you're playing by yourself.
The second question is that of the 81:64 major third between the G and B strings.  This will be out of tune with the fourth-fret harmonic of the G string.  (If your A is 110 Hz, G will be 195 5⁄9 Hz and open B will be 247.5 Hz, so the fourth-fret harmonic of G will be 977 7⁄9 Hz while the fifth-fret harmonic of B will be 990 Hz.)  If this is a problem for you then you will need to decide which compromises you can make depending on your needs.  If you want to explore that, it's probably better to ask a new question.
Comment: Thanks a lot for your comprehensive and helpful answer! That makes it a lot clearer! I'm going to try your describe approach.
Comment: @Tom I'm happy to help.  I'm not a guitarist though, and in particular I have no experience to shed light on the use of open strings vs 12th- or 5th-fret harmonics for tuning, so you may want to unaccept my answer for now to avoid discouraging anyone who might have more practical advice from posting it.
Comment: @Tom - as phoog said, you need to decide what your priorities for just intervals are, and that's not a simple question.  You might also be interested in the work of Tolgahan Çoğulu, a guitarist who has developed a guitar with moveable frets to explore a wide range of tunings.  This is a good place to start, as it is expressly devoted to the problem phoog mentions: https://www.youtube.com/watch?v=XT4oOYj4SwQ
Comment: @phoog I see! I'll try your approach and let you know then. Anyway, thanks a lot
Comment: @Scott Thanks! I'll check out Tolgahan Çoğulu. I know that some people build guitars with moveable frets. I'm curious to see if it also just with the open strings in just intonation. So basically, being limited to the open strings, since freting wouldn't be possible or sound out of tune in most places


How to use $-1$ in some form instead of $e^i$ to represent a $1$ radian rotation

Question: The first fact:
A complex number whose modulo equals 1 lies on the unit circle, and finding the square root is equivalent to halving its angle on the unit circle. The angle of -1 is 180 degrees, the square root of -1 means that the angle of $i$ is 90 degrees, the angle of the square root of $i$ is 45 degrees, and the angle of the square root of $i$ is 22.5 degrees ... which is described as the following picture

The second fact
$(1+i/n)^n=e^i   \ when \ n \to \infty $ which means a rotation of one radian,
To a summary, $i$ multiplying a real number means a $\pi/2$ rotation,  $i$ at the power of $e$ means a 1 radian rotation.
I have a strange idea, could use -1 of the form in the fist fact to represent 1 radian rotation.
i.e. how to use $\sqrt{-1}  \ \sqrt{\sqrt{-1}} \ \sqrt{\sqrt{\sqrt{-1}}} \ ...$ to represent an arbitray radian rotation by combination or some what you could think
Comment: Maybe write $(-1)^{1/2}, (-1)^{1/4}, \dots (-1)^{1/2^k},\dots$ (looks mmore professional).   Choose some of them (based on binary expansion of $a$) to get $(-1)^a$, defined as $(-1)^a = e^{i\pi a}$.  In particular, to get $e^i$ use the binary expansion of $1/\pi$.
Comment: It is not clear what your idea is or what you are asking for. Please clarify.
Comment: A better view, I aim to understand it from different and vivid view.
Answer: A $\pi$-radian rotation from $1$ gives $-1$; that is, $$-1=e^{\pi i}$$  Taking $\pi$-th roots, $$(-1)^{\frac{1}{\pi}}=e^i$$
(If you liked this, give GEdgar's comment an upvote.)


TextToSpeech - Unable to start activity: findViewById(R.id.srcText) must not be null in Kotlin Android

Question: Been working on a real-time Translation project combined with TTS, but I'm a total beginner in Android development. The OCR and translate functions are working properly since I referred to the codelab.
However, after I have added TTS to MainActivity with srcText(TextView) in main_fragment.xml the error showed up. Have read a number of posts regarding this problem, but can't seem to find a suitable solution since the structure of the project files from the codelab is quite complicated(activity, fragment, ViewModel...) .
MainActivity.kt
import android.os.Bundle
import android.speech.tts.TextToSpeech
import android.util.Log
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.mlkit.codelab.translate.main.MainFragment
import java.util.*

class MainActivity : AppCompatActivity(), TextToSpeech.OnInitListener {

    private var tts: TextToSpeech? = null //ADDED from TextToSpeech

    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)
        //setContentView(R.layout.main_fragment)
        setContentView(R.layout.main_activity) //Changed

        if (savedInstanceState == null) {
            supportFragmentManager.beginTransaction()
                .replace(R.id.container, MainFragment.newInstance())
                .commitNow()
        }

        //TextToSpeech starts here...
        //(Copied code) Button and etEnteredText need to be removed and modified respectively
        tts = TextToSpeech(this, this)
        //val btnSpeak: Button =findViewById(R.id.btnSpeak)
        //val etEnteredText: EditText =findViewById(R.id.etEnteredText)

        Log.i("123","Initialization Completed")

        val srcText: TextView = findViewById(R.id.srcText)
        val translatedText: TextView= findViewById(R.id.translatedText)
        //btnSpeak.setOnClickListener{ view ->

            if(srcText.text.isEmpty()){
                Toast.makeText(this@MainActivity,
                    "Enter a text to use TTS.", Toast.LENGTH_SHORT)
                    .show()
            }else{
                speakOut(srcText.text.toString())
            }

            //Do the same for ...

            if(translatedText.text.isEmpty()){
                Toast.makeText(this@MainActivity,
                    "Enter a text to use TTS.", Toast.LENGTH_SHORT)
                    .show()
            }else{
                speakOut(translatedText.text.toString())
            }

        //}
    }

    override fun onInit(status: Int) {

        if (status == TextToSpeech.SUCCESS) {
            // set US English as language for tts
            val result = tts!!.setLanguage(Locale.US)

            if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                Log.e("TTS","The Language specified is not supported!")
            }

        } else {
            Log.e("TTS", "Initialization Failed!")
        }

    }

    private fun speakOut(text: String){
        tts!!.speak(text, TextToSpeech.QUEUE_FLUSH, null, "")
    }

    public override fun onDestroy() {

        if (tts != null) {
            tts!!.stop()
            tts!!.shutdown()
        }
        super.onDestroy()
    }

}

main_activity.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" />

main_fragment.xml
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.google.mlkit.showcase.translate.main.MainFragment">

    <androidx.camera.view.PreviewView
        android:id="@+id/viewfinder"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintBottom_toTopOf="@id/middle"
        app:layout_constraintTop_toTopOf="parent" />
    <SurfaceView
        android:id="@+id/overlay"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintStart_toStartOf="@id/viewfinder"
        app:layout_constraintEnd_toEndOf="@id/viewfinder"
        app:layout_constraintBottom_toBottomOf="@id/viewfinder"
        app:layout_constraintTop_toTopOf="@id/viewfinder" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/middle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent=".5" />

    <TextView
        android:id="@+id/srcLang"
        style="@style/SrcLangText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="20dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="20dp"
        android:layout_marginBottom="4dp"
        app:layout_constraintBottom_toTopOf="@+id/srcTextScrollView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/middle"
        tools:text="source lang" />

    <ScrollView
        android:id="@+id/srcTextScrollView"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_marginBottom="4dp"
        android:fillViewport="true"
        android:scrollbars="vertical"
        app:layout_constraintBottom_toTopOf="@+id/divider"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/srcLang">

        <TextView
            android:id="@+id/srcText"
            style="@style/SrcText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="20dp"
            android:layout_marginEnd="20dp"
            tools:text="source text" />
    </ScrollView>

    <View
        android:id="@+id/divider"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginStart="20dp"
        android:layout_marginEnd="20dp"
        android:background="?android:attr/listDivider"
        app:layout_constraintBottom_toTopOf="@+id/targetLangSelector"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/srcTextScrollView" />

    <Spinner
        android:id="@+id/targetLangSelector"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="20dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/divider" />

    <ScrollView
        android:id="@+id/translatedTextScrollView"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_marginBottom="4dp"
        android:fillViewport="true"
        android:scrollbars="vertical"
        app:layout_constraintBottom_toTopOf="@+id/divider2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/targetLangSelector">

        <TextView
            android:id="@+id/translatedText"
            style="@style/TranslatedText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="20dp"
            android:layout_marginEnd="20dp"
            android:layout_marginBottom="4dp"
            tools:text="translated text" />
    </ScrollView>

    <View
        android:id="@+id/divider2"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginStart="20dp"
        android:layout_marginTop="4dp"
        android:layout_marginEnd="20dp"
        android:layout_marginBottom="4dp"
        android:background="?android:attr/listDivider"
        app:layout_constraintBottom_toTopOf="@id/imageView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/translatedTextScrollView" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="18dp"
        android:layout_marginStart="4dp"
        android:layout_marginTop="4dp"
        android:layout_marginEnd="4dp"
        android:layout_marginBottom="4dp"
        android:contentDescription="@string/content_description_google_translate_attribution"
        android:scaleType="fitCenter"
        android:src="@drawable/greyscale_regular_3x"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/divider2" />

    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyle"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:visibility="invisible"
        app:layout_constraintStart_toEndOf="@+id/targetLangSelector"
        app:layout_constraintTop_toTopOf="@id/targetLangSelector"
        app:layout_constraintBottom_toBottomOf="@id/targetLangSelector" />

    <TextView
        android:id="@+id/progressText"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="@string/downloading_model_files"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/progressBar"
        app:layout_constraintBottom_toBottomOf="@id/progressBar"
        android:gravity="center_vertical"
        app:layout_constraintTop_toTopOf="@id/progressBar" />

</androidx.constraintlayout.widget.ConstraintLayout>

Logcat Error Message
2022-05-12 02:49:48.730 18411-18411/com.google.mlkit.codelab.translate E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.google.mlkit.codelab.translate, PID: 18411
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.google.mlkit.codelab.translate/com.google.mlkit.codelab.translate.MainActivity}: java.lang.IllegalStateException: findViewById(R.id.srcText) must not be null
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
     Caused by: java.lang.IllegalStateException: findViewById(R.id.srcText) must not be null
        at com.google.mlkit.codelab.translate.MainActivity.onCreate(MainActivity.kt:61)
        at android.app.Activity.performCreate(Activity.java:7994)
        at android.app.Activity.performCreate(Activity.java:7978)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)

Need a helping hand from my fellow developers and hopefully without making a whole lot of changes to the original structure. Thanks in advance :)
Answer: Do like this it might be Work :
private var srcText : TextView ? = null //Add this variable above onCreate

Find view by ID. Within on Create
srcText = findViewById(R.id.srcText)

So Your onCreate Code is like this :
override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)
        //setContentView(R.layout.main_fragment)
        setContentView(R.layout.main_activity) //Changed

        if (savedInstanceState == null) {
            supportFragmentManager.beginTransaction()
                .replace(R.id.container, MainFragment.newInstance())
                .commitNow()
        }

        //TextToSpeech starts here...
        //(Copied code) Button and etEnteredText need to be removed and modified respectively
        tts = TextToSpeech(this, this)
        //val btnSpeak: Button =findViewById(R.id.btnSpeak)
        //val etEnteredText: EditText =findViewById(R.id.etEnteredText)

        Log.i("123","Initialization Completed")

        srcText = findViewById(R.id.srcText)  // Find View By ID of srcText Here

        val translatedText: TextView= findViewById(R.id.translatedText)
        //btnSpeak.setOnClickListener{ view ->

            if(srcText.text.isEmpty()){
                Toast.makeText(this@MainActivity,
                    "Enter a text to use TTS.", Toast.LENGTH_SHORT)
                    .show()
            }else{
                speakOut(srcText.text.toString())
            }

            //Do the same for ...

            if(translatedText.text.isEmpty()){
                Toast.makeText(this@MainActivity,
                    "Enter a text to use TTS.", Toast.LENGTH_SHORT)
                    .show()
            }else{
                speakOut(translatedText.text.toString())
            }

        //}
    }

Hope this Will work.


Bash: Check if remote directory exists using FTP

Question: I'm writing a bash script to send files from a linux server to a remote Windows FTP server.
I would like to check using FTP if the folder where the file will be stored exists before attempting to create it.
Please note that I cannot use SSH nor SCP and I cannot install new scripts on the linux server. Also, for performance issues, I would prefer if checking and creating the folders is done using only one FTP connection.
Here's the function to send the file:
sendFile() {
    ftp -n $FTP_HOST <<! >> ${LOCAL_LOG}
        quote USER ${FTP_USER}
        quote PASS ${FTP_PASS}
        binary
        $(ftp_mkdir_loop "$FTP_PATH")
        put ${FILE_PATH} ${FTP_PATH}/${FILENAME}
        bye
!
}

And here's what ftp_mkdir_loop looks like:
ftp_mkdir_loop() {
    local r
    local a
    r="$@"
    while [[ "$r" != "$a" ]]; do
      a=${r%%/*}
      echo "mkdir $a"
      echo "cd $a"
      r=${r#*/}
    done
}

The ftp_mkdir_loop function helps in creating all the folders in $FTP_PATH (Since I cannot do mkdir -p $FTP_PATH through FTP).
Overall my script works but is not "clean"; this is what I'm getting in my log file after the execution of the script (yes, $FTP_PATH is composed of 5 existing directories):
(directory-name) Cannot create a file when that file already exists.
Cannot create a file when that file already exists.
Cannot create a file when that file already exists.
Cannot create a file when that file already exists.
Cannot create a file when that file already exists.

Answer:     #!/bin/bash

    FTP_HOST=prep.ai.mit.edu
    FTP_USER=anonymous
    firstname.lastname@example.com
    DIRECTORY=/foo                   # /foo does not exist, /pub exists
    LOCAL_LOG=/tmp/foo.log
    ERROR="Failed to change directory"

    ftp -n $FTP_HOST << EOF | tee -a ${LOCAL_LOG} | grep -q "${ERROR}"
    quote USER ${FTP_USER}
    quote pass ${FTP_PASS}
    cd ${DIRECTORY}
    EOF

    if [[ "${PIPESTATUS[2]}" -eq 1 ]]; then
      echo ${DIRECTORY} exists
    else
      echo ${DIRECTORY} does not exist
    fi

Output:

/foo does not exist

If you want to suppress only the messages in ${LOCAL_LOG}:
ftp -n $FTP_HOST <<! | grep -v "Cannot create a file" >> ${LOCAL_LOG}

Comment: Creative answer using `$PIPESTATUS` to check errors in FTP. But following @EtanReisner comment, it seems that there will be too many FTP connections. Also I'd ultimately like to check the folders' existence and create them with only one FTP connection.
Comment: Is the suggestion here that he should be performing one ftp connection per directory component to test with `cd` and then one per non-existent component to use `mkdir` and then one more to transfer the file?
Comment: I'll award you the bounty at the end of the period if there's no better answer because I've just learned about `$PIPESTATUS` and your secondary answer where we only suppress the messages is satisfactory although not exactly answering my question.
Comment: @grim Unfortunately, I don't know that there is any way to test for a directory via ftp without triggering an error (from either `mkdir` or `cd`) and I don't know of any way to test for/catch that error within an ftp session either so the selective silencing might be the best you can get when used with your original code.
Answer: To solve this, do as follows:

To ensure that you only use one FTP connection, you create the input (FTP commands) as an output of a shell script
E.g.
$ cat a.sh
cd /home/test1
mkdir /home/test1/test2

$ ./a.sh | ftp $Your_login_and_server > /your/log 2>&1

To allow the FTP to test if a directory exists, you use the fact that "DIR" command has an option to write to file
 # ...continuing a.sh
 # In a loop, $CURRENT_DIR is the next subdirectory to check-or-create
 echo "DIR $CURRENT_DIR $local_output_file"
 sleep 5 # to leave time for the file to be created
 if (! -s $local_output_file)
 then
    echo "mkdir $CURRENT_DIR"
 endif

Please note that "-s" test is not necessarily correct - I don't have acccess to ftp now and don't know what the exact output of running DIR on non-existing directory will be - cold be empty file, could be a specific error. If error, you can grep the error text in  $local_output_file
Now, wrap the step #2 into a loop over your individual subdirectories in a.sh
Comment: Ironically, sftp doesn't support writing to local file, so this solution ONLY works for pure ftp
Comment: I wasn't able to implement this solution. Could you please elaborate? I'm still not very versatile with bash scripting.
Comment: I'm getting `?Invalid command` when doing `DIR $CURRENT_DIR $local_output_file`
What exactly is $local_output_file?
Comment: @grim - it's a variable I made up to hold the name of your desired file where you stash the output from DIR.
Comment: By the way, the output of running `DIR` on non-existing directory does't create/update the local output file.
Comment: Perfect then use "-f" test
Comment: After implementing the solution: the command is connecting to the FTP server but I'm getting `Segmentation fault: 11` as soon as the first command is echoed and piped from the script.
I tried to only echo `DIR` and I still get the same error.
Comment: Can you clarify something for me please? Isn't `a.sh` completely run before redirecting its output to the `ftp` command? If so, the local output file test will never evaluate to false, right?
Comment: @grim - that's why there's `sleep` in there. Ideally, you'd have a 2-sided pipe and some sort of communication, but you need Perl for that instead of bash
Comment: @DVK I have used the code , directly
    ftp -n $HOST << EOF
    user $USER $PASS
     lcd  $src_directory
     echo "DIR $detinationDir $local_output_file"
      sleep 5
       if (! -s $local_output_file)
         then
        mkdir $detinationDir
         fi
        put *
       bye
        EOF

But I am getting invalid command for the lines from echo  to fi
Can  you please help


Probability density of $Y = bX+c$ is $f_Y(x) = \frac{1}{b}f_X(\frac{x-c}{b})$ for $b>0$

Question: We know that if $Y = bX+c$ where $b>0$, its density function with respect to $f_X$ (density of $X$) is: $f_Y(x) = \frac{1}{b}f_X(\frac{x-c}{b})$. Now how can I get the density of $Y$ when $b<0$?
Following the same approach as for case $b>0$, I got ($F_Y$ is the cumulative distribution function of $Y$):
$$F_Y(x) = P(Y\leq x) = P(bX+c\leq x) = (\text{since $b<0$}) =\\
 P(X \geq \frac{x-c}{b}) = 1 - P(X< \frac{x-c}{b})=1 - P(X\leq \frac{x-c}{b})=\\
1 - \int_{-\infty}^{\frac{x-c}{b}}f_X(\xi)d\xi=1 - \int_{-\infty}^{x}\frac{1}{b}f_X(\frac{t-c}{b})dt$$
If only I could write the last expression as the integral of something, then I could get $f_Y$.
Update:
As pointed out in the comments, the last part should be $1-\int_{\infty}^x \frac{1}{b}f_X(\frac{t-c}{b})dt$.
Solution: I think I got it. We have $$P(X\geq \frac{x-c}{b}) = \int_{\frac{x-c}{b}}^\infty f_X(\xi)d\xi = \text{(using $\xi = (t-c)/b$ and reversing the limits)}=\int_{-\infty}^x -\frac{1}{b} f_X(\frac{t-c}{b})dt$$
So $f_Y(x) = -\frac{1}{b} f_X(\frac{x-c}{b})$. Note: the expression is positive since $b<0$.
Comment: The last = sign is wrong since the change of variable $\xi=(t-c)/b$ transforms the integral on $\xi<(x-c)/b$ into an integral on $t>x$, not $t<x$.
Comment: You're right. I will fix it.
Answer: $$P(X\geq \frac{x-c}{b}) = \int_{\frac{x-c}{b}}^\infty f_X(\xi)d\xi = \text{(using $\xi = (t-c)/b$ and reversing the limits)}=\int_{-\infty}^x -\frac{1}{b} f_X(\frac{t-c}{b})dt$$
So $f_Y(x) = -\frac{1}{b} f_X(\frac{x-c}{b})$.
Note: the expression is positive since $b<0$.


Meaning of dots in Lattice / Galois Connection

Question: Wondering what the dots mean (and what the whole element it's a part of means) in the slide below (above pos and neg). I have seen them in another similar presentation on data-flow lattices and Galois connections.
Comment: The context appears to be https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-820-fundamentals-of-program-analysis-fall-2015/lecture-notes/MIT6_820F15_L18.pdf
Answer: The context is not clear, but maybe pos means greater than zero, and dotted pos means great than or equal to zero? That would be logical, as dotted pos is the unification of pos and 0, for example.


skaffold unable to pull image

Question: I have a Skaffold config file
apiVersion: skaffold/v2beta26
kind: Config
metadata:
  name: libero
build:
  local:
    useBuildkit: true
  artifacts:
    - image: registry.a.com:5000/b/c/d
      custom:
        buildCommand: make docker
deploy:
  kubectl:
    manifests:
      - k8s/canary-a/deployment.yaml

The make docker build command corresponds to
DOCKER_BUILDKIT=1 $(DOCKER) build --secret id=ci-job-token,src=token .

I have no idea why, but when I run Skaffold dev,
#12 exporting layers done
#12 writing image sha256:95d59d2289205522ca22543767eef3852042959006af15d4f41d43306ec4640b done
#12 DONE 0.0s
getting image: GET https://registry.a.com:5000/v2/b/c/d/manifests/4.5.5-264-g248b268-dirty: MANIFEST_UNKNOWN: manifest unknown; map[Tag:4.5.5-264-g248b268-dirty]

Notice the /v2 in the URL, where did that come from? Am I missing something here?
I think it's also worth mentioning that i've already ran skaffold dev with multiple different configurations (for example different tag policies), so that might have to do something with it.
Answer: That GET https://registry.a.com:5000/v2/... is showing the underlying REST API for accessing an image registry.  That API is called the OCI Distribution Spec.
The MANIFEST_UNKNOWN: manifest unknown error is happening as your make docker is creating an anonymous untagged image, and is not fulfilling the Skaffold Custom Builder contract which requires the command to build the image named $IMAGE, which includes the destination repository and image tag to be used, and push the image if $PUSH_IMAGE is true.
Your make docker should do something like:
DOCKER_BUILDKIT=1 $(DOCKER) build --tag $(IMAGE) --secret id=ci-job-token,src=token .
if [[ "$PUSH_IMAGE" == true ]]; then $(DOCKER) push $(IMAGE); fi

(My make knowledge is rusty, so you will likely need to adjust this!)

skaffold unable to pull image


SQLiteOpenHelper onUpgrade() Confusion Android

Question: I am doing my first app with a database and I am having a little trouble understanding the onUpgrade function.  My database has a table with an items and a favorite column so that the user can favorite an item.  Most implementations I see simply drop the table and reconstruct it but I don't want to do this. I want to be able to add more items to the table.
When the app is upgraded through the android marketplace does the database know its version number?  So could I increment the version number in the code and then export it to the marketplace and when the user boots up the upgraded version for the first time then onUpgrade will be called?
If this is the case my onUpgrade would simply pull from a file and add the database items in.  Is this a standard way of doing things or is there a better way of handling this in Android.  I am trying to stay as standard as possible.
Thanks
Comment: You know Mike, it has been a year.  You really should accept one of the answers
Comment: years are going, but Mike don't call `onUpgrade()`
Comment: Last seen: Sep 7 '10 at 17:35
Comment: One more year and here we are, no acceptance of the Answer! may be he just forgot his password!
Comment: 4 years were not enough for Mike to get the answer worthy of his acceptance...
Comment: 5 years and waiting...
Comment: It's 2016 nothing new \o/
Answer: Ok, before you run into bigger problems you should know that SQLite is limited on the ALTER TABLE command, it allows add and rename only no remove/drop which is done with recreation of the table.
You should always have the new table creation query at hand, and use that for upgrade and transfer any existing data. Note: that the onUpgrade methods runs one for your sqlite helper object and you need to handle all the tables in it.
So what is recommended onUpgrade:

beginTransaction
run a table creation with if not exists (we are doing an upgrade, so the table might not exists yet, it will fail alter and drop)
put in a list the existing columns List<String> columns = DBUtils.GetColumns(db, TableName);
backup table (ALTER table " + TableName + " RENAME TO 'temp_"                    + TableName)
create new table (the newest table creation schema)
get the intersection with the new columns, this time columns taken from the upgraded table (columns.retainAll(DBUtils.GetColumns(db, TableName));)
restore data (String cols = StringUtils.join(columns, ",");
            db.execSQL(String.format(
                    "INSERT INTO %s (%s) SELECT %s from temp_%s",
                    TableName, cols, cols, TableName));
)
remove backup table (DROP table 'temp_" + TableName)
setTransactionSuccessful

(This doesn't handle table downgrade, if you rename a column, you don't get the existing data transfered as the column names do not match).
.
public static List<String> GetColumns(SQLiteDatabase db, String tableName) {
    List<String> ar = null;
    Cursor c = null;
    try {
        c = db.rawQuery("select * from " + tableName + " limit 1", null);
        if (c != null) {
            ar = new ArrayList<String>(Arrays.asList(c.getColumnNames()));
        }
    } catch (Exception e) {
        Log.v(tableName, e.getMessage(), e);
        e.printStackTrace();
    } finally {
        if (c != null)
            c.close();
    }
    return ar;
}

public static String join(List<String> list, String delim) {
    StringBuilder buf = new StringBuilder();
    int num = list.size();
    for (int i = 0; i < num; i++) {
        if (i != 0)
            buf.append(delim);
        buf.append((String) list.get(i));
    }
    return buf.toString();
}

Comment: Hello, and thanks for your answer.
Quick question: is it really necessary to call `beginTransaction()` and `setTransactionSuccessful()` inside of `onUpgrade()`?
As the call to `onUpgrade()` in `SQLiteOpenHelper` is already surrounded by those two.
Comment: it's there in the code it's the retainAll method on the list, so `oldColumns.retainAll(newColumns)` at that time `DBUtils.GetColumns(db, TableName)` will return new columns, as the new tables has just been created, and the `columns` variable holds the reference to the columns before renaming the table, so old columns.
Comment: `StringUtils.join` is unnecessary. Android has a TextUtils class which has a join method, see [TextUtils.join](http://developer.android.com/reference/android/text/TextUtils.html). Otherwise a great answer.
Comment: I read this answer many times. it gives feel so good at all time because of detail explanation.
Comment: Hi Pentium, excellent answer, I was wondering could you clarify how I "get the intersection with the new columns, this time columns taken from the upgraded table" though?
Comment: Thanks Pentuim, I got confused by the extra brackets you had around the code, I thought you were using an additonal variable or something outside the brackets, Excellent answer and thanks again.
Comment: @Pentium10 But where does db version come into play in all of this?
Comment: @IgorGanapolsky DB version fires the event to start this process for you.
Answer: Next to Pentium10's excellent answer, here are some good examples from living code:

Android AOSP: com.android.providers.calendar.CalendarDatabaseHelper.java
Android AOSP: com.android.browser.BrowserProvider.java
OpenIntents Notepad: org.openintents.notepad.NotePadProvider.java
Comment: just edited the answer with non-dead links... thanks for the great answer!
Comment: Sadly Google Code Search has shut down now so these examples can't be viewed.
Answer: Thank you for clarifying that onUpgrade() will not support Remove/Drop statements @Pentium 10
For those of you who would like to know the exact moment when onUpgrade() gets called, it is during a call to either getReadableDatabase() or getWriteableDatabase().
To those who are not clear how it ensure it gets triggered...the answer is: It is triggered when the database version provided to the constructor of SqLiteOpenHelper is updated. Here is a example
public class dbSchemaHelper extends SQLiteOpenHelper {

private String sql;
private final String D_TAG = "FundExpense";
//update this to get onUpgrade() method of sqliteopenhelper class called
static final int DB_VERSION = 2;
static final String DB_NAME = "fundExpenseManager";

public dbSchemaHelper(Context context) {
    super(context, DB_NAME, null, DB_VERSION);
    // TODO Auto-generated constructor stub
}

now to...onUpgrade()
@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
    sql = "ALTER TABLE " + fundExpenseSchema.Expense.TABLE_NAME + " ADD COLUMN " + fundExpenseSchema.Expense.FUNDID + " INTEGER";
    arg0.execSQL(sql);
}

Comment: What is a use-case for upgrading the DB_VERSION number?
Comment: Please don't sign your posts.  Put your website in your profile.
Answer: I've been using the solution proposed by @Pentium10 for a long time but today i had a problem, after doing alter table, getColumns from the original table still returns the same columns (in the new version of the db the table suffer mayor structure changes, some columns added some others), really i don't know why select statement does not reflect the structure changes, more over before creating my table again, select statement still returns the columns! When the table is not re-created yet!
So i manage solving this issue updating getColumns method using pragma table_info, like this:
    /**
 * Get a list of column base_dictionary for the selected table
 *
 * @param db
 *  Database that contains the table
 * @param tableName
 *  Table name to be used
 * @return A List of column name
 */
public static List<String> getColumns(SQLiteDatabase db, String tableName) {
    List<String> ar = null;
    Cursor c = null;
    try {
        c = db.rawQuery("pragma table_info(" + tableName + ")", null);

        ar = new ArrayList<String>();
        if (c != null && c.moveToFirst()) {
            do {
                ar.add(c.getString(c.getColumnIndexOrThrow("name")));
            } while (c.moveToNext());
            c.close();
        }

    } catch (Exception e) {
        Log.v(tableName, e.getMessage(), e);
        e.printStackTrace();
    } finally {
        if (c != null) c.close();
    }
    return ar;
}


How to set Apache to return 403 on images used as CSS backgrounds

Question:
Possible Duplicate:
How to prevent hot linking ("image theft" / "bandwidth theft") of ressources on my site?

I'd like to configure my Apache server similar to a working configuration I noticed on the Farming Simulator website. They use CSS background images for their main navigation bar but if you try to view an image with a direct link (example) it returns a 403 Forbidden error. I know how to allow/deny indexes for directories, but not how to deny access to files within those directories.
Does anyone know how I'd go about configuring .htaccess to work like this?
I found a similar question but it doesn't really answer mine.
Answer: First I want to tell you that this is a very futile act. As soon as you see the image in your browser, it has been downloaded to your computer.
When I followed your link directly I had a 403. Then I visited the page and I could even see the image in the link because it was in the cache.
I believe this effect is produced by examining the referer of the request. A sample for blocking by referer can be found here
I still recomend you not to do it. Not many people try to hotlink a background image. And if they really want to, it's still easy to overcome this measure by simply changing the header.


Como utilizar a imagem gerada no html em outra página

Question: Estou convertendo uma string para imagem para ser utilizada em um boleto bancário. Tendo em vista esta necessidade, tenho como exemplo a seguinte varável:
$string = 10499.10657 01500.110045 00002.710038 9 79320000000000

Obs.: estes da variável estão em string UTF-8
Código:
$font  = 5;
$width  = imagefontwidth($font) * strlen($string);
$height = imagefontheight($font);

$image = imagecreate($width, $height);

$bg = imagecolorallocate($image, 255, 255, 255);
$textcolor = imagecolorallocate($image, 65, 65, 65);
imagestring($image, 5, 0, 0, $string, $textcolor);
header("Content-type: image/png");
imagepng($image);

E me retorna uma imagem na aba com o valor:

Em outro arquivo, tenho um template html que necessito inserir, mas como faço para realizar esta passagem via variável na tag <img src="<?php ?>">  para apenas mostrar onde eu quero, não executando nesta aba como está ocorrendo?
Li em alguns tópicos em inglês que se faz necessário converter para a base64 segundo meu entendimento, de fato se faz necessário?
Referência: link
Answer: você pode fazer o seguinte

ou ainda pode transformar sua imagem em um base64
$font  = 5;
$width  = imagefontwidth($font) * strlen($string);
$height = imagefontheight($font);

$image = imagecreate($width, $height);

$bg = imagecolorallocate($image, 255, 255, 255);
$textcolor = imagecolorallocate($image, 65, 65, 65);
imagestring($image, 5, 0, 0, $string, $textcolor);
ob_start();
imagepng($image);
$imagedata = ob_get_clean();

e na pagina mais em baixo em php vc printaria assim
<?php echo '';

--- Para modificar a fonte ----
seria algo assim
$font = imageloadfont('./fonte.ttf');
imagestring($image, 5, 0, 0, $string, $textcolor);

da uma lida na doc. https://www.php.net/manual/pt_BR/function.imagestring.php
Comment: Funcionou certinho, obrigado.


Undesired output in Racket

Question: I'm working on a homework assignment and am a little bit confused as to what produced this output. Here is the code:
<code>#lang racket
(define (my_calc calcType radius); define the function and set up the parameters
  (define PI 3.1416); define PI
  (cond ((and (= calcType 1) (positive? radius))); check to see whether the calc function is one and the radius is positive
        ((* 2 PI radius radius)); return the area of a circle
        ((and (= calcType 2) (positive? radius))); check to see whether the calc function is 2 and the radius is positive
        ((* (/ 4 3) PI radius radius radius)); return the volume of a sphere
        (else #f); if calc function is not 1 or 2 or the radius is not positive, return false
  )
)
(my_calc 1 10)
(my_calc 2 10)
(my_calc 0 1)
(my_calc 1 0)
</code>
and here is the output:
<code>#t
628.32
6.2832
0
</code>
I have no idea why the first one would return true, it should return the area of a circle. There isn't even a return statement that would allow that. The second one seems to work just fine. The third one should produce false, but it produces the second answer divided by a hundred for some reason. And the 0 at the bottom is beyond me. Can anyone help me? Thank you.
Answer: Your first procedure in a cond case has to be the test expression followed by the result. See the documentation, https://docs.racket-lang.org/reference/if.html.
For example:
<code>(cond
   [; test expression
    (and (= calcType 2) (positive? radius))
    ; following result
    ((* (/ 4 3) PI radius radius radius))]

   [else whatever]
)
</code>
I would recommend using square brackets for each cond case for legibility.
In your case,
<code>[(and (= calcType 1) (positive? radius))]
</code>
The test expression is <code>(and (= calcType 1) (positive? radius))</code> but there is no following procedure.
You have the same problem for all of your cond cases. Good luck.
Comment: I tried that and got this error message:
application: not a procedure;
 expected a procedure that can be applied to arguments
  given: 628.32
  arguments...: [none]
Comment: @Mike12670 I'm not sure what you tried... That error you received means you don't have enough brackets. Make sure you have procedueres only where needed.
Comment: I found out that I had too many parentheses. Thanks for your help! I'll mark your question as the answer.

Undesired output in Racket


proving a tricky limit is zero

Question: Let $$S=\{x+{\sqrt{2}}:0\leq x\leq 1\}$$ and $$A_{n}=\{0,1/n,2/n,...\}$$
Let $C_{n}=|S{\cap}A_{n}|$. Prove that the $$\lim_{n\to\infty}\frac{C_{n}}{n}=0$$.
My attempt: $x+{\sqrt{2}}=\frac{k}{n}$ implies $x=\frac{k-{\sqrt{2}}n}{n}$. We need $x$ to be between 0 and 1 so the cardinality is the number of integers $k$ satisfying $n{\sqrt{2}}{\leq}k{\leq}n(1+{\sqrt{2}})$.
But this means the cardinality is $n$ which won't make the limit zero. Thanks for any help
Comment: The limit is $1$, not $0$.
Comment: @TonyK look at page 7 here http://terrytao.files.wordpress.com/2011/01/measure-book1.pdf.
Comment: Your formulation of the problem is different: in the link, $S = \{ x + \sqrt{2} : x \in [0,1] \cap \mathbb{Q} \}$. This is a rather different object from $\{ x + \sqrt{2} : x \in [0,1] \}$. In the latter case you will get $1$.
Comment: @Ian Thanks; can you show me how to get 1?
Comment: Your OP is one step away from getting the limit to be 1....
Comment: @Ian sorry I meant 0
Comment: @Ian the first formulation is what I wanted
Comment: @GregMartin sorry I mean the first formulation and get the limit to be zero
Comment: @Ian So the cardinality is the no. of integers k satisfying 0<(k/n)+sqrt(2)<1. But where do I go from here?
Comment: @Ian I think I get it now. The intersection is the empty set since a rational + irrational is an irrational. Correct?
Comment: You're asking all these questions about more or less the same thing, but none of them quite makes sense. What do you _really_ want to know?
Answer: The set $S=[\sqrt{2}, 1+\sqrt{2}]$ as OP points out we need the number of $k$ such that
$$n{\sqrt{2}}{\leq}k{\leq}n(1+{\sqrt{2}})
$$ and this is either $n$ or $n-1$. Since both $\frac{n}{n}$ and $\frac{n-1}{n}$ limit to $1$ we have that the correct limit is $1$.
Comment: sorry I mistated the question. I have answered it in the comments. I have another question: Can you think of a set $S$ where the limit does not exist? Thanks

proving a tricky limit is zero


Issue when trying to use the IN operator in a JPQL query

Question: the following query :
SELECT P FROM Project P WHERE :currentUser IN(P.assignedUsers)

throws the following error :

org.h2.jdbc.JdbcSQLException: Syntax error in SQL statement: "....";
  expected "NOT, EXISTS, INTERSECTS, SELECT, FROM";

Am i using the IN operator wrong, or am i supposed to do it differently.
Project.assignedUsers : is a list containing users (a OneToMany Relationship).
and the currentUser parameter is a valid user.
Answer: You cannot use implicit joins for this purpose; you probably want to utilize the member of operator:
SELECT P FROM Project P WHERE :currentUser MEMBER OF P.assignedUsers