Why is $x^2-2ux+1$, where $u = \cos(\frac{2\pi}{n})$, irreducible in $\mathbb Q(u)$?

Question: My textbook states that $x^2-2ux+1$, where $u = \cos(\frac{2\pi}{n})$ for some $n \in \mathbb N$ is clearly irreducible in $\mathbb Q(u)$.
Is this obvious?
I tried to write it as a product of linear factors, but I found this difficult because I do not know what an element in $\mathbb Q(u)$ looks like.
Any insights?
Comment: this is false for $n=6$
Comment: For $n=3$ it's reducible over $\Bbb Q$. It'd be pretty easy to explain why if it were $x^2-2\cos(\frac{2\pi}{n})x+1$ instead (the discriminant would be imaginary).
Comment: Yes, it is. I hadn't even thought about doubting the textbook. I'll check if I have overlooked something.
Comment: Perhaps it is actually $\;u=\cos\frac{2\pi}n\;$ and **not** $\;u=\color{red}2\cos\frac{2\pi}n\;$ ? That would automatically render that quadratic irreducible over the reals...
Comment: @DonAntonio That is exactly the case. Sorry for your trouble. The answer is clear now.
Comment: @Improve, edit your question's title, too.
Comment: @DonAntonio Can't I just delete the question? It is based on me reading the text incorrectly. I do not know what the general feeling about such things are.
Comment: Well @improve: first, many people already read the question and some even commented, not to mention that there'salready an answer. What's the point of deleting ?
Comment: @DonAntonio Well, no other reason than that the question was originally based on a false assumption.
Answer: If we in fact have $\;u=\cos\frac{2\pi}n\;$ , then the quadratic's discriminant is
$$\Delta:=b^2-4ac=\cos^2\frac{2\pi}n-4<0$$
and we're done...
Comment: Um, $b=-2u{}{}$.
Comment: Read the comments below the question, @seaturtles
Comment: I did, and even commented before you, but I'm telling you: while $u$ was corrected from $2\cos$ to just $\cos$, the polynomial is still $x^2-2ux+1$.
Comment: I see what you mean, @seaturtles...yet I think the intention is for $\;x^2-ux+1\;$ ...at least that's what I understood and meant before. Let's see if the OP addresses this, though it doesn't matter much I think, as $$\cos^2\frac{2\pi}n-1<0\;\;\forall\,1<n\in\Bbb N$$
Comment: Of course, you get $\Delta=-4\sin^2$, which is much more elegant than $\cos^2-4$. Also, the quadratic $x^2-2\cos()x+1$ appears in nature as $(x-\cos)^2+\sin^2$. Plus, OP already checked back with the problem and changed $u=2\cos$ to $u=\cos$ but did not change the polynomial. All these facts considered, I overwhelmingly believe $x^2-2ux+1$ was exactly as intended.


Numerical differentiation

Question: Using Taylor series, establish the error term for the formula $f′′(x)≃ \frac{f(x+h)−2f(x)+f(x−h)}{h^2}$. Assume f(x) and all its derivatives have similar magnitudes, determine the value of $h=1/(2^m)$ that gives the most accurate approximation of f''(x).
I understand that by using Taylor series, the error term is O( $\frac{h^4f''''(x)}{24}$ ). But how to get h?
Comment: This sure reads like a homework problem. What have you done so far?
Comment: I got the error term for f''(x) based on the formula above: $\frac{h^4f''''(x)}{4!}+\frac{h^6f^{xi}(x)}{6!}$+...
Answer: The Taylor polynomial of degree $3$ with Lagrange form for remainder reads
$$\begin{align}f(x-h)&=f(x)-hf^{\prime}(x)+\frac12h^2f^{\prime\prime}(x)-\frac16h^3f^{\prime\prime\prime}(x)+\frac1{24}h^4f^{(4)}(\xi_1)\\
f(x+h)&=f(x)+hf^{\prime}(x)+\frac12h^2f^{\prime\prime}(x)+\frac16h^3f^{\prime\prime\prime}(x)+\frac1{24}h^4f^{(4)}(\xi_2)\end{align}$$
With $x-h<\xi_1<x<\xi_2<x+h$. Adding, then subtracting $2f(x)$ we have
$$\begin{align}f(x-h)-2f(x)+f(x+h)&=h^2f^{\prime\prime}(x)+\frac{h^4}{24}\left(f^{(4)}(\xi_1)+f^{(4)}(\xi_2)\right)\\
&=h^2f^{\prime\prime}(x)+\frac{h^4}{12}f^{(4)}(\xi)\end{align}$$
Where the intermediate value theorem has assured us that there must be a $\xi$ such that $x-h<\xi_1<\xi<\xi_2<x+h$ and $f^{(4)}(\xi)=\frac12\left(f^{(4)}(\xi_1)+f^{(4)}(\xi_2)\right)$, assuming a continuous $f^{(4)}(x)$. That means that
$$\frac{f(x-h)-2f(x)+f(x+h)}{h^2}=f^{\prime\prime}(x)+\frac{h^2}{12}f^{(4)}(\xi)$$
Assuming IEEE-754 single precision arithmetic with $24$ bits of precision, the error in $f(x-h)-2f(x)+f(x+h)=h^2f^{\prime\prime}(x)$ is about $2^{-24}f(x)$ in magnitude so the roundoff error in $f^{\prime\prime}(x)$ is about $\frac{2^{-24}}{h^2}f(x)$. The truncation error is about $\frac{h^2}{12}f(x)$ and these $2$ errors have the same magnitude when $h^4=12\times2^{-24}$; $h\approx0.029\approx2^{-5}$. For double precision arithmetic with $53$ bits of precision, $h^4=12\times2^{-53}$; $h\approx1.9\times10^{-4}\approx2^{-12}$.
Comment: Sorry, but how can I say that the error is about $2^{-24} f(x)$ in magnitude (single precision case)?

Numerical differentiation


Multilinear Model with fixed intercept

Question: I would like to fit the following model Y (t) = m (t) + b * t + g * C (t) + N (t) with m (t) to be the long term mean monthly values (remove seasonal component), b the trend coefficient, C to be the matrix of explanatory variables, and N (t) the error term being AR (1).
I would like to ask you if this model is the same as the following:
Y (t) - m (t) = b * t + g * C (t) + N (t). Forced to have 0 intercept term, or I should also substract the mean from my regressors also.
Moreover, I would like to know if you can propose how this could be implemented, preferably in Matlab, or secondly in R.
I am not familiar with this kind of models yet, so thanks in advance, all help is very much appreciated.
Answer: In R this can be done using the arima function as follows:
y_no_m<-y-m  # removing m from y per your example
C_trend<-cbind(C,t=seq_along(y)) # add time trend variable to matrix of explanatory variables
arima(y_no_m, order=c(1,0,0), xreg=C , include.mean=FALSE)

The code below demonstrates this by way of simulation -- setting up the model you describe above (with arbitrary, random X's and coefficients) and then recovering the coefficients via arima.
t<-500
coefs<-list(ar=0.5,time=0.01,x=c(1.5,2,-1))
errors<-arima.sim(list(ar=coefs$ar),n=t)
    time<-seq_along(errors)
    trend<-time*coefs$time
X<-data.frame(X1=rnorm(t),X2=rnorm(t),X3=rnorm(t))
y_demean<-with(X,trend+coefs$x[1]*X1+coefs$x[2]*X2+coefs$x[3]*X3+errors)
X_t<-cbind(X,time=time)
model<-arima(y_demean,order=c(1,0,0),xreg=X_t,include.mean=FALSE)
>Call:
>arima(x = y_demean, order = c(1, 0, 0), xreg = X_t, include.mean = FALSE)

>Coefficients:
>     ar1      X1      X2       X3    time
>  0.4119  1.5283  1.9665  -0.9665  0.0095
>s.e. 0.0408  0.0407  0.0393   0.0380  0.0002

>sigma^2 estimated as 0.8659:  log likelihood = -673.58,  aic = 1359.15

Comment: Thank you very much for your reply and the code you provide me. Excuse my ignorance, but if i understood correctly your reply, substracting the mean is like to have a fixed intercept term with fixed value in my model? That means that if the other regressions didn't affect my measurements, then, the value would be equal to the seasonal mean?
Thank you very much again for your attention.
PS: sorry, I don't have the credits yet to vote for you.
Comment: You are correct -- if the transformation $y'_t=y_t - m_t$ means that the mean of $y'_t=0$ then you won't need the intercept term (as above).  If you include the intercept anyway (ie `include.mean=TRUE`) you'll likely find it is estimated as insignificant ... but you reduce the uncertainty of estimation by leaving it out.
Comment: Thank you very much for explaining this, it is of great help. Thank you.

Multilinear Model with fixed intercept


c synchronise write to stdout and stderr

Question: I am implementing ls program. Everything is working properly, besides synchronisation of error messages and normal output.
I store information in big buffers (200kb).
As you can see subfolder2 has no rights to be opened.
My program works recursively and opens folder tests, then reads all of it's content, than writes it to stdout. Then it opens folder, displays all content. Same with subfolder1. When it meets subfolder 2, it gets errno and writes explanation in stderr. It works in debugger and doesn't work in reality, because it places output where it wants, not at the end.
And it  works perfectly it when  uses stdout, like on the example in the bottom.
/Users/qhetting/ft_ls/tests
total 0
drwxr-xr-x  3 qhetting 2018 102 Mar 30 14:08 .
drwxr-xr-x 19 qhetting 2018 646 Mar 30 15:04 ..
drwxr-xr-x  4 qhetting 2018 136 Mar 30 14:10 folder

/Users/qhetting/ft_ls/tests/folder
total 0
drwxr-xr-x 4 qhetting 2018 136 Mar 30 14:10 .
drwxr-xr-x 3 qhetting 2018 102 Mar 30 14:08 ..
drwxrwxrwx 2 qhetting 2018  68 Mar 30 14:09 subfolder1
d--------- 2 qhetting 2018  68 Mar 30 14:10 subfolder2

/Users/qhetting/ft_ls/tests/folder/subfolder1
total 0
drwxrwxrwx 2 qhetting 2018  68 Mar 30 14:09 .
drwxr-xr-x 4 qhetting 2018 136 Mar 30 14:10 ..

ft_ls: subfolder2: Permission denied

Code:
 if (!(dir = opendir(fld_name)))
            {
                if (errno)
                    print_error(fld_name, errno, NULL); //gets file name, concatenates it with error message and prints it with write like
write(2, error, strlen(error));
                return;
            }
            errno = 0;
            while ((dirp = readdir(dir)))
            {
                if (!(g_flag & A && dirp->d_name[0] != '.') || g_flag & A)
                {
                    attrib = ft_relink(attrib, dirp->d_name,
                                       get_full_path(fld_name, dirp->d_name));
                    if (first_asign)
                    {
                        holder = attrib;
                        first_asign = false;
                    }
                }
                if (errno)
                {
                    print_error(fld_name, errno, attrib);
                    errno = 0;
                    continue;
                }
            }
            attrib = holder;
            ft_merge_sort(&attrib, comparator_lex);
            print_level(attrib, g_flag); //here all read content is printed in stdout with big buffer.
            if (g_flag & R_BIG)
            {
                while (attrib)
                {
                    if (IS_OK && is_dir(attrib->full_path) && !attrib->error_message)
                        ft_open_folder(attrib->full_path);
                    attrib = attrib->next;
                }
            }
            closedir(dir);

Answer: You can use fflush(stdout) and fflush(stderr) to flush the output buffers. Doing so will print whatever is left in the buffer immediately.

Synopsis
int fflush(FILE *stream);
Description
If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.

https://port70.net/~nsz/c/c11/n1570.html#220.127.116.11
Comment: What to do if it doesn't help?


cpp iterator inheritance

Question: My requirements are same to the question asked Using Iterators to hide internal container and achieve generic operation over a base container[1] at stackoverflow. I have a generic pure virtual base container class, which needs to provide an iterator which should be STL complaint so I can use them with cpp algorithm's #include <algorithm>. My implementation uses only an single class instead of two classes as in [1] solution.
Base pure virtual class
class BaseItr
{
  public:
    class iterator : public std::iterator<std::input_iterator_tag, int>
    {
      public:
        iterator() : _in(NULL) {}
        inline iterator(const iterator& org) : _in(org._in) {}
        inline iterator& operator=(const iterator& other) { _in = other._in; return *this; }
        virtual inline int operator * () { return _in->operator*(); }
        virtual inline iterator& operator++() { (*_in)++; return *this; }
        virtual inline iterator& operator++(int unused) { (*_in)++; return *this; }
        virtual inline bool operator==(const iterator& other)
        {
          return *(*_in) == *(*(other._in));
        }
        virtual inline bool operator!=(const iterator& other)
        {
          return *(*_in) != *(*(other._in));
        }
        // would use shared pointer insted of this
        //~iterator() { if(_in) { delete _in; } }
        static inline iterator New(iterator *in) { return iterator(in); }
      private:
        iterator(iterator *in) : _in(in) {}
        iterator *_in;
    };

    virtual iterator begin() = 0;
    virtual iterator end() = 0;
};

Implementation
class Itr : public BaseItr
{
  private:
    class iterator : public BaseItr::iterator
    {
      public:
        iterator(int val) : _val(val), BaseItr::iterator() {}
        int operator * () { return _val; }
        inline iterator& operator++() { ++_val; return *this; }
        inline iterator& operator++(int unused) { _val++; return *this; }
      private:
        int _val;
    };
    BaseItr::iterator _begin;
    BaseItr::iterator _end;
  public:
    inline Itr(int start, int end)
    {
      _begin = BaseItr::iterator::New(new iterator(start));
      _end = BaseItr::iterator::New(new iterator(end));
    }

    BaseItr::iterator begin() { return _begin; }
    BaseItr::iterator end() { return _end; }
};

My implementation works was need, I want to know are there any drawbacks with this implementation, Please help me decide with my design to use the appropriate implementation. I have add my full working example code in github:gist https://gist.github.com/3847688
Ref:

Iterator for custom container with derived classes
Using Iterators to hide internal container and achieve generic operation over a base container
Fast and flexible iterator for abstract class
C++ : Using different iterator types in subclasses without breaking the inheritance mechanism
Answer: The most glaring issue: your iterator does not have value semantics.
The STL algorithms are free to copy an iterator if they wish. For example suppose:
template <typename It>
It find(It b, It e, typename std::iterator_traits<It>::const_reference t) {
    for (; b != e; ++b) {
        if (*b == t) { return b; }
    }
    return e;
}

The problem is that if you invoke this algorithm with BaseItr&, then the result is of type BaseItr, and you are thus exposed to Object Slicing, which is undefined behavior.
In order to give value semantics to you iterator, you need to create a wrapper class around an abstract implementation and have the wrapper correctly manage the copy through a virtual clone method. If your iterator ends up with virtual methods, you are doing it wrong.
Comment: "*If your iterator ends up with virtual methods, you are doing it wrong.*" I'd +1 this more than once if I could.
Comment: @Kam: `std::unique_ptr` deals with ownership, `clone` deals with copying. You can use both in conjunction.
Comment: If the iterator is a wrapper for the abstract implementation don't we still face the _Object Splicing_?. As we can initialize the wrapper without an instance of the abstract class in it, if so how to prevent it. Can we use `std::unique_ptr` instead of a virtual `clone`.

cpp iterator inheritance


Print the WHOLE menu?

Question: Is there a way to print out an array of the entirety of a menu in Drupal 7?
For example, I have access controls in place so that a user gets a role after they take a quiz, which then allows them to see the next quiz. So until they pass quiz #1, their menu will not show them any evidence of quiz #2's existence.
What I want to do is print out the titles of ALL menu items, regardless of whether the user has access to the associated nodes or not. I plan to rewrite the menu to make the permitted items links, while the others appear greyed out until the user gains access to them.
I have not been able to find any modules, and simply doing this:
<code>print_r(menu_navigation_links('menu-program-menu'));
</code>
only shows the items that the user has permission to view.
Is there a module already that does this, that I just haven't been able to find? Does a query have to be made directly to the database or is there a way to do this with more finesse?
Answer: What you can do is to select corresponding titles from the database directly:
<code>$sql = "SELECT l.link_title FROM {menu_links} l WHERE l.menu_name = :menu_name ";
$result = db_query($sql, array(':menu_name' => 'menu-program-menu'));
foreach($result as $object) {
    print $object->link_title;
}
</code>
Comment: That does indeed work! Though I think there must be an API or something somewhere that give you access to this. Is this the only way to do it? Anyway thank you! Did you consult documentation for this, and if so, might I have a link?
Comment: No I didn't consult any documentation for this. I just opened phpmyadmin and had a quick look to recall how menu links are stored in the db and then wrote this piece of code. But you might find useful http://drupal.org/developing/api/database
it explains how to query the database :)
Answer: Besides writing custom database queries you might be able to use functions listed on the Menu API page. For example menu_load_links() loads all the links of the specified menu. menu_link_load() can be used to get additional (including access) information besides the general link data (thanks, beth, for pointing this out!). You could also use the code of the listed functions to create your own similar functions without the access controls.
Comment: Thank you, this is what I have been digging for! Only one thing, in looking at the output of that function, I don't see information about user permissions for each link. Am I missing something? Or should I use [menu_link_load()](http://api.drupal.org/api/drupal/includes!menu.inc/function/menu_link_load/7) for each mlid that is returned by menu_load_links()?
Comment: You're right, menu_load_links() does not retrieve any access information. Like you already figured out using the mlid's and menu_link_load() should cover your needs though.

Print the WHOLE menu?


Prove (by definition) that $\lim _{z\to 1+i}\left(\frac{1}{z^2+1}\right)=\frac{1}{2i+1}$

Question: How can I take this expression $$\left(\frac{1}{z^2+1}\right)-\frac{1}{2i+1}$$ to the form $z-(1+i)$?
I must use the definition of limit to prove this result. That is, use $\delta$ and $\epsilon$.
What I have done so far is to raise the definition: $$\lim _{z\to 1+i}\left(\frac{1}{z^2+1}\right)=\frac{1}{2i+1}\Leftrightarrow[\forall\epsilon>0,\exists\delta>0/\forall z\in\mathbb{C}:(0<|z-(1+i)|<\delta\Rightarrow|\left(\frac{1}{z^2+1}\right)-\frac{1}{2i+1}|<\epsilon)]$$
I must prove:
$$\left|\left(\frac{1}{z^2+1}\right)-\frac{1}{2i+1}\right|<\epsilon$$ as long as $0<|z-(1+i)|<\delta$
We start from
\begin{align}
\left|\left(\frac{1}{z^2+1}\right)-\frac{1}{2i+1}\right|&=\left|\frac{1+2i-(z^2+1)}{(z^2+1)(2i+1)}\right|\\
&=\left|\frac{2i-z^2}{(z^2+1)(2i+1)}\right|\\
&=\left|\frac{(2i-z^2)(1-2i)}{(z^2+1)(2i+1)(1-2i)}\right|\\
&=\left|\frac{2i+4+i(2z^2+2)}{5(z^2+1)}\right|.
\end{align}
But I still don't get the expression I need.
Comment: @Erika: Thank you for improving your question. I upvoted your question for that. However, note that user2661923's request to re-open your question in its original form is contrary to site guidelines (which Kavi Rama Murthy linked you to), so please do not post that kind of question again. Thank you.
Answer: The following response would be significantly shorter if you were allowed to use the Complex Analysis Theorem that
if $~\lim_{z \to z_0} a(z) = L \neq 0$
then $\lim_{z \to z_0} \frac{1}{a(z)} = \frac{1}{L}.$
I am assuming that the above theorem is out of bounds.  Further, attempting to simply derive the above theorem (from scratch), would first require that some Real Analysis theorems be derived.
So, I will go for Kludginess.

This problem requires a backward and offbeat approach.  A straightforward conversion of $z$ to $x + iy$ will be very messy.  Fortunately, there is a middle ground.
Preliminary Concepts
(1)
Given $~r \in \Bbb{R}, ~s \in \Bbb{R^+},$
the constraint that $|r| < s$
is equivalent to the constraint that
$-s < r < s.$
(2)
Suppose that $u,v \in \Bbb{C}$
and that you want to establish that
$|u - v| < \epsilon$.
This may be established by showing that
$|\text{Re}(u - v)| < \frac{\epsilon}{2}~~~$ and
$~~~|\text{Im}(u - v)| < \frac{\epsilon}{2}.$
This is based on the idea that
$|\sqrt{\left[\frac{1}{2}\right]^2 + \left[\frac{1}{2}\right]^2} < 1.$
(3)
Suppose that $u,v \in \Bbb{C}$
and you are given that $0 < |u - v| < \delta.$
This implies that
$|\text{Re}(u - v)| < \delta~~~$ and
$~~~|\text{Im}(u - v)| < \delta.$
The justification for this is very similar to that applied in (2) above.
(4)
In this problem, rather than identifying a relationship between $\delta$ and $\epsilon$ such that $\delta = g(\epsilon)$, I will make things easy on myself by also requiring that $\delta \leq \frac{1}{10}$.
Thus, the relationship will look like $\delta = \min\left[\frac{1}{10}, g(\epsilon)\right].$
(5)
As suggested at the start of my answer, I am going to start with the requirement that
$\displaystyle \left| ~\frac{1}{z^2 + 1} - \frac{1}{2i + 1} ~\right| < \epsilon.$
Then, I will see where this leads in terms of the necessary constraint on $\delta$, which will always be required to be $\leq \frac{1}{10}.$

Assume that $z = (x + iy)$.
Let $w = (z^2 + 1)$ and let $\overline{w}$ represent the complex conjugate of $w$.
Let $f(z) = \displaystyle \left( ~\frac{\overline{w}}{|w|^2} - \frac{1 - 2i}{5} ~\right).$
It is desired that $|f(z)| < \epsilon.$
Based on (2) above, I will achieve this, by requiring that
$| ~\text{Re}[f(z)] ~| < \frac{\epsilon}{2}~~~$ and
$~~~| ~\text{Im}[f(z)] ~| < \frac{\epsilon}{2}.$
Using (1) above, this will be done by requiring that
$$-\frac{\epsilon}{2} < \text{Re}[f(z)] < \frac{\epsilon}{2} ~~~\text{and} ~~~ -\frac{\epsilon}{2} < \text{Im}[f(z)] < \frac{\epsilon}{2}. \tag{A} $$

The challenge is to specify $\delta$ so that
$$ 0 < \left| ~(x + iy) - (1 + i) ~\right| < \delta \leq \frac{1}{10} \tag{B} $$
implies that the constraints in (A) above are satisfied.

$w = (z^2 + 1) = (x^2 - y^2 + 1) + i(2xy).$
This implies that
$\overline{w} = (x^2 - y^2 + 1) - i(2xy)~~~$
and $~~~|w|^2 = (x^2 - y^2 + 1)^2 + (4x^2y^2).$
Using (1) and (3) above, (B) above implies that
$$1 - \delta < x < 1 + \delta ~~~\text{and}
~~~ 1 - \delta < y < 1 + \delta. \tag{C} $$
Since $~\delta \leq \frac{1}{10},~$ you have that
$(1 - \delta) > 0~~~$ and $~~~\delta^2 < \delta.$
Therefore,
$$ 1 - 2\delta < x^2 < 1 + 3\delta ~~~\text{and}
~~~ 1 - 2\delta < y^2 < 1 + 3\delta. \tag{D} $$
Consequently lower and upper bounds for $(x^2 - y^2 + 1)$ are
$$(1 - 5\delta) = (1 - 2\delta) - (1 + 3\delta) + 1  \leq (x^2 - y^2 + 1) \\ \leq [\text{similarly}] ~(1 + 5\delta).  \tag{E} $$
Similarly, lower and upper bounds for $(-2xy)$ are
$$(-2 - 6\delta) < (-2)(1 + \delta)^2 < (-2xy) \\ <
(-2)(1 - \delta)^2 < (-2 + 4\delta). \tag{F} $$
Using (E) and (F), you have that
$$(1 - 5\delta) < \text{Re}(\overline{w}) < (1 + 5\delta) ~~~\text{and} \\ (-2 - 6\delta) < \text{Im}(\overline{w}) < (-2 + 4\delta). \tag{G}$$
Using (G) above, lower and upper bounds for $|w|^2$ are
$$(5 - 26\delta) < (1 - 5\delta)^2 + (-2 + 4\delta)^2 \leq |w|^2 \\ \leq (1 + 5\delta)^2 + (-2 - 6\delta)^2 < (5 + 95\delta). \tag{H}$$

Now, using (G), (H) above, lower and upper bounds for $~$ Re$\left(\frac{\overline{w}}{|w|^2}\right)~$
and $~$ Im$\left(\frac{\overline{w}}{|w|^2}\right)~$
may be identified.
A lower bound for $~$ Re$\left(\frac{\overline{w}}{|w|^2}\right)~$ is
$$\frac{1 - 5\delta}{5 + 95\delta} = \frac{1 + 19\delta}{5 + 95\delta} - \frac{24\delta}{5 + 95\delta} > \frac{1}{5} - \frac{24}{5}\delta > \frac{1}{5} - 5\delta.\tag{I} $$
An upper bound for $~$ Re$\left(\frac{\overline{w}}{|w|^2}\right)~$ is
$$\frac{1 + 5\delta}{5 - 26\delta} = \frac{1  - \frac{26}{5}\delta}{5 - 26\delta} + \frac{\frac{51}{5}\delta}{5 - 26\delta} < \frac{1}{5} +  \frac{51}{10}\delta < \frac{1}{5} + 6\delta.\tag{J} $$
A lower bound for $~$ Im$\left(\frac{\overline{w}}{|w|^2}\right)~$ is
$$\frac{-2 - 6\delta}{5 - 26\delta} = \frac{-2 + \frac{52}{5}\delta}{5 - 26\delta} - \frac{\frac{82}{5}\delta}{5 - 26\delta} > -\frac{2}{5} - \frac{82}{10}\delta > -\frac{2}{5} - 9\delta.\tag{K} $$
An upper bound for $~$ Im$\left(\frac{\overline{w}}{|w|^2}\right)~$ is
$$\frac{-2 + 4\delta}{5 + 95\delta} = \frac{-2 - 38\delta}{5 + 95\delta} + \frac{42\delta}{5 + 95\delta} < -\frac{2}{5} +  \frac{42}{5}\delta < -\frac{2}{5} + 9\delta.\tag{L} $$

Using (I) and (J)
$$-5\delta = \frac{1}{5} - 5\delta - \frac{1}{5} < \text{Re}[f(z)] < \frac{1}{5} + 6\delta - \frac{1}{5} = 6\delta.$$
Using (K) and (L)
$$-9\delta = -\frac{2}{5} - 9\delta + \frac{2}{5} < \text{Im}[f(z)] < -\frac{2}{5} + 9\delta + \frac{2}{5} = 9\delta.$$
$\delta$ must be chosen so that
$$-\frac{\epsilon}{2} < -5\delta, ~6\delta < \frac{\epsilon}{2}, ~-\frac{\epsilon}{2} < -9\delta, ~9\delta < \frac{\epsilon}{2}.$$
Coupled with the constraint that $\delta \leq \frac{1}{10}$
a workable final specification is
$$\delta = \min\left(\frac{1}{10}, \frac{\epsilon}{20}\right).$$
Answer: It is unfortunate that most textbooks and teachers do not teach how to use asymptotic analysis. This is an intuitive and powerful technique that can be used even if you want to obtain an ε-δ proof.
$
\def\lfrac#1#2{{\large\frac{#1}{#2}}}
\def\abs#1{\left|#1\right|}
$
First let's use the technique:
  As $t\overset{∈ℂ}→0$:
    $\lfrac1{(1+i+t)^2+1} = \lfrac1{2i+2·(1+i)·t+t^2+1}$.
    $⊆ \lfrac1{2i+1+O(t)} ⊆ \lfrac1{2i+1}·\lfrac1{1+O(t)} ⊆ \lfrac1{2i+1}·(1+O(t)) → \lfrac1{2i+1}$.
That's it!
Now how to convert it into an ε-δ proof? Easy. Simply use concrete bounds in place of the asymptotic bounds:
  Let $r = \abs{t}$.
  Then $\lfrac1{(1+i+t)^2+1} = \lfrac1{2i+1}·\lfrac1{1+u}$   where $u = 2·\lfrac{1+i}{2i+1}·t+\lfrac1{2i+1}·t^2$.
  And $\abs{u} ≤ 2·r+r^2 ≤ 3r$   if $r ≤ 1$.
  And $\abs{\lfrac1{1+u}-1} = \lfrac{\abs{u}}{\abs{1+u}} ≤ \lfrac{\abs{u}}{1-\lfrac12} ≤ 6r$   if $r ≤ 1$ and $\abs{u}≤\lfrac12$.
  Thus $\abs{ \lfrac1{2i+1}·(\lfrac1{1+u}-1) } ≤ \lfrac12·6r = 3r$   if $r ≤ 1$ and $3r ≤ \lfrac12$.
  Thus $\abs{ \lfrac1{(1+i+t)^2+1} - \lfrac1{2i+1} } ≤ 3r$   if $r ≤ \lfrac16$.
It is now trivial to turn this into an ε-δ proof.
Comment: Ignore the downvoter, who has been unable to justify the downvote. It is not only easy to produce an ε-δ proof from what I wrote, it is far simpler and shorter than the one in the other answer, and furthermore the technique to obtain the proof is much more general.


How to find sum of factorial of 1,2,.....up to n(input no. )

Question: I tried to solve this question many time but i am confused with the loop operation ..
#include<stdio.h>
#include<conio.h>
void main()
{
   int n,i,j, fact =1, sum =0;
   printf("Enter the limit of the factorial series");
   scanf("%d", &n);
   for(i=1;i<=n;i++)
   {
       for(j=1;j<=n;j++)
       {
          fact = fact * j;
       }
       sum = sum + fact;
       fact = 1;
   }
   printf("The sum of the factorial series of % d terms is: %d",n,sum);
   getch();
}

Please give me a hint to solve the problem.
Comment: Do not try to write multi-language source files. Stick with one of C or C++ or Java.
Comment: What does this have to do with Java?
Comment: variable overflow may be.., looks like an XY problem
Comment: Offtopic, but `void main` is wrong. Moreover avoid `conio.h` and `getch` as these are not standard.
Comment: you want to do this is java or c++? Here you have pasted c++ code.
Comment: factorial of 13 is `6227020800` (needs 33 bits). It probably does not fit an `int` on your system.
Answer: You are always calcultacing fact(n) in your second loop. Your second loop should probably be like this :
for(j=1;j<=i;j++)
{
    fact = fact * j;
}

Comment: You got him right :)
Answer: Your inner loop always compute factorial(n).
Create sub function may help:
int fact(int n)
{
    int res = 1;
    for (int i = 1; i <= n; ++i) {
        res *= i;
    }
    return res;
}

so your main loop becomes:
int main()
{
   int n,sum = 0;
   printf("Enter the limit of the factorial series\n");
   scanf("%d", &n);
   for(int i = 1; i <= n; i++) {
       sum = sum + fact(i); // And now it is evident that it is fact(i) and not fact(n).
   }
   printf("The sum of the factorial series of % d terms is: %d\n", n, sum);
}

or if you want to do all in one loop
int main()
{
   int n;
   printf("Enter the limit of the factorial series\n");
   scanf("%d", &n);
   int sum = 0;
   int fact = 1;
   for(int i = 1; i <= n; i++) {
       fact *= i; // update fact, as Fact(n+1) = Fact(n) * (n+1)
       sum += fact;
   }
   printf("The sum of the factorial series of % d terms is: %d\n", n, sum);
}


Running roundcube alongside passenger on nginx

Question: I have recently tried to install passenger on nginx. The installation works and everything is good. However I would like to run roundcube webmail on my server as well.
Basically my problem is that nginx has the root directive set to the passenger app:
root /home/me/www/hello/public

and roundcube is created as a symlink on the server as:
/home/me/www/webmail

My question how do I get the url www.my-server.com to refer to the normal root but www.my-server.com/webmail to refer to the roundcube folder?
I have tried variations on the following in my nginx.conf with no luck:
location /webmail/ {
    #root /home/me/www;
    alias /home/me/www;
    try_files $uri /index.php;
    passenger_enabled off;
}

The above configuration results in 403 forbidden when using www.my-server.com/webmail and File not found when using the URI: www.my-server.com/webmail/index.php.
Any ideas?
Answer: That was a bit tricky but I found the solution in the nginx documentation about location.
As there is a location directive matching .php files this will take precedence over the /webmail/ location and since this does not declare a root location the global root will be used which still points to the passenger folder.
The solution was to add a root directive to the php matching location and limit php execution to the webmail path, like so:
index index.html index.htm index.php

location /webmail/ {
    root /home/me/www;
}

location ~ /webmail/.*\.php$ {
    root /home/me/www;
    ...
}

Now everything works.


Equivalence of definitions for topology generated by a basis.

Question: Let $X$ be a set and let $\mathcal{B}$ be a basis for a topology on $X$. This means that $\mathcal{B}$ is a collection of subsets of $X$ such that for all $x \in X$ there is a basis element $B \in \mathcal{B}$ such that $x \in B$ and whenever $x$ is in the intersection of two basis elements $B_1$ and $B_2$, there is a third basis element $B_3$ such that $x \in B_3$ and $B_3 \subseteq B_1 \cap B_2$ (Munkres definition).
Here are what I understand to be two equivalent definitions of topologies generated by a basis. That is, one can generate a topology for $X$ from $\mathcal{B}$ as
\begin{equation}
\mathcal{T}_{\mathcal{B}} = \{\bigcup C \mid C \subseteq \mathcal{B}\}.
\end{equation}
Or, alternatively and equivalently, one can build the same topology by building the set
\begin{equation}
\mathcal{T}_{\mathcal{B}}' = \{U \subseteq X \mid (\forall x \in U)(\exists B \in \mathcal{B})( x \in B \wedge B \subseteq U)\}.
\end{equation}
Question 1) Is this the correct way to understand the material? That is, there is a definition of basis and two equivalent ways to build a topology from it?
Question 2) As far as I understand, the two sets should be equivalent. Online I have only found proofs of this equivalence by first proving that one of the two actually constitutes a topology (Munkres does this as well) and then showing the rest. Is this a necessary step? is it done out of convenience? is it sufficient to show that $\mathcal{T}_\mathcal{B} = \mathcal{T}_\mathcal{B}'$ as follows for instance?
Proof:
Let $V \in \mathcal{T}_\mathcal{B}$. Then, $V$ is the union of some basis elements. Since all basis elements are subsets of $X$, their union is a subset of $X$; i.e,. $V \subseteq X$. Let now $x \in V$. Then, $x$ belongs to some basis element $B \in \mathcal{B}$ and that basis element must be fully contained in $V$. Thus, $V \in \mathcal{T}_\mathcal{B}'$. Let now $V \in \mathcal{T}_\mathcal{B}'$. I will show that this is the union of some basis elements. Consider some $x \in V$. By definition there is a $B_x \in \mathcal{B}$ such that $x \in B_x$ and $B_x \subseteq V$. Thus, $x \in \bigcup_{x\in V}B_x$. Suppose now $x \in \bigcup_{x \in V}B_x$. Then, $x \in B_x$ for some $x \in V$. Since all $B_x$ are subsets of $V$, then $x \in V$. Thus, $V = \bigcup_{x\in V}B_x$ and $V \in \mathcal{T}_\mathcal{B}$.
Comment: Q1: Yes. Q2: Your proof of $\mathcal{T}_\mathcal{B} = \mathcal{T}_\mathcal{B}'$ is ok and usual. However, you could avoid the implicit (though frequent) use of the axiom of choice in the second part, by showing instead: $V$ is the union of all the elements of $\mathcal B$ which are contained in $V.$
Answer: Everything is correct. In the first definition you need the convention that if $C = \emptyset$, then $\bigcup C = \emptyset$.
In your proof of $\mathcal{T}'_{\mathcal{B}} \subset \mathcal{T}_{\mathcal{B}}$ it would be better (see Anne Bauval's  comment) to define
$$C(V) = \{ B \in \mathcal B \mid B \subset V \} .$$
Then $V = \bigcup C(V)$. In fact, $\bigcup C(V) \subset V$ is trivial. To show $V \subset \bigcup C(V)$, consider $x \in X$. There exists $B_x \in \mathcal B$ such that $x \in B_x \subset V$. Thus $B_x \in C(V)$ and $x \in \bigcup C(V)$.


Supplying a predefined list of options for an exposed item in a view in Drupal?

Question: I've got a view that filters by year. The year is a normal text CCK field on the content type. I've exposed this field in the view, so that the user can type in a value for it. E.g. 2010. It will then show all the content types with the field set to 2010. My problem is, I don't want the user to type in the value. I want to change that text field to a dropdown with several years.
My options are:

Hack it with JQuery --> VERY BAD
Edit the exposed value using some hook or something BEFORE it's outputted on the page
Any other options?

My question is, how do I do option 2, or worst case, option 3?
Answer: When you edit the CCK field in Manage fields, you can set the allowed values for that field. If you do, when you go back into the View, you'll have a new filter, Field - allows values which will give you a select menu of the allowed values when you expose it.
If you don't want to limit the values during creation, you're going to have to alter the exposed form in a custom module:
<code>function mymodule_form_alter(&$form, $form_state, $form_id) {
  if ($form_id === 'views_exposed_form') {
    // Change field_test_value to the name of your field
    $form['field_test_value']['#type'] = 'select';
    $form['field_test_value']['#options'] = array(
      '' => '',
      '2010' => '2010',
      '2009' => '2009');
  }
}
</code>
See the Form API reference to see what else you can do.


Plotting the Digraph with graphviz in python from DOT file

Question: This is the API reference for graphviz. I could not find any method that generates a directed graph from an existing dot source file. Methods like render and view save in a new file.
How can I display a graph from existing dot code?
Answer: I was able to solve it using Source class.
from graphviz import Source
temp = """
digraph G{
edge [dir=forward]
node [shape=plaintext]

0 [label="0 (None)"]
0 -> 5 [label="root"]
1 [label="1 (Hello)"]
2 [label="2 (how)"]
2 -> 1 [label="advmod"]
3 [label="3 (are)"]
4 [label="4 (you)"]
5 [label="5 (doing)"]
5 -> 3 [label="aux"]
5 -> 2 [label="advmod"]
5 -> 4 [label="nsubj"]
}
"""
s = Source(temp, filename="test.gv", format="png")
s.view()

The output will be in same folder, and format can be altered.
PS - To install graphviz on Ubuntu. First install using
sudo apt install graphviz and then sudo pip install graphviz, else it won't work.
Comment: @johnktejik I similarly got `AttributeError: 'Dot' object has no attribute 'splitlines'`. Solved it by running `dot.to_string()` before passing to `Source()`
Comment: I get a strange error `AttributeError: 'function' object has no attribute 'splitlines'`
Answer: You can use the Source.from_file('/path/to/dot_file') function as defined in the API.
Thus the code will be:
from graphviz import Source
path = '/path/to/dot_file'
s = Source.from_file(path)
s.view()

Comment: python3.7 /tmp/graphviz.py
Traceback (most recent call last):
  File "/tmp/graphviz.py", line 3, in
    from graphviz import Source
  File "/tmp/graphviz.py", line 3, in
    from graphviz import Source
ImportError: cannot import name 'Source' from 'graphviz' (/tmp/graphviz.py)
Comment: it flashed on my screen for a millisecond then disappeared.  How do I get it to stay?
Answer: I put a very short code for displaying graph using a dot file in Python.
The code is like this:
from graphviz import Source

path = 'abcd.dot'
s = Source.from_file(path)
print(s.source)

s.render('abcd.gv', format='jpg',view=True)


Train / Validate / Test sets in Caret

Question: I want to use caret to compare two different classification algorithms. For example SVM and Elastic net.
I want to put aside some samples for test set and then use the rest of the samples for training the model, which involves tuning some parameters (like alpha and lambda for elastic net) for which I use cross validation as well. But once I fixed the model, I want to calculate it's performance on the test set (that was not used for parameter tuning).
I want to do 10 fold cross validation to calculate performance of each method (SVM vs Enet).  Note that this cross validation should be in an outer loop than the cross validation used for parameter tuning for each method.
I was wondering if I can use Caret to do that.
In the pseudo code given by Caret (http://caret.r-forge.r-project.org/training.html) the first loop (line 2) is for each parameter set, and the next loop (line 3) is for each resampling iteration. Is it possible to add another outer loop such as (Line 0:  for each resampling iteration) to this schema ?

EDIT: @topepo: yes we have a limited data, so we want to have multiple test sets. Use 90% data for training (including parameter tuning) and then calculate the performance on the 10% remaining data. then repeat this 10 times with different partitionings of the data.
Comment: Do you want multiple test sets? Otherwise, I don't see what the outer loop does. Pseudo-code would help.
Answer: Give this a try (modify the details as needed)
<code>library(caret)

library(mlbench)
data(Sonar)

set.seed(1)
splits <- createFolds(Sonar$Class, returnTrain = TRUE)
    results <- lapply(splits,
                      function(x, dat) {
                        holdout <- (1:nrow(dat))[-unique(x)]
                        data.frame(index = holdout,
                                   obs = dat$Class[holdout])
                  },
                  dat = Sonar)
mods <- vector(mode = "list", length = length(splits))

## foreach or lapply would do this faster
for(i in seq(along = splits)) {
  in_train <- unique(splits[[i]])
  set.seed(2)
  mod <- train(Class ~ ., data = Sonar[in_train, ],
               method = "svmRadial",
               preProc = c("center", "scale"),
               tuneLength = 8)
  results[[i]]$pred <- predict(mod, Sonar[-in_train, ])
  mods[[i]] <- mod
}

lapply(results, defaultSummary)
</code>
Comment: Sorry to ask what is probably a very simple question but why is it required to pass x and splits[[i]] to the method unique() in your example? Why not simply use x or splits[[i]] on its own? As far as I understand unique returns the same vector but without duplicates. Also, I thought that each of the ten folds in splits is a list of row position integers for the training data (given returnTrain = TRUE) which would not contain duplicates? Sorry again if I am not understanding. My knowledge of R is not great. Thanks again for your Caret package!

Train / Validate / Test sets in Caret


Adding ASCII characters to HTML links in Drupal

Question: I've written the decimal HTML entry of the "Logical or" ASCII note in a menu-link and yet I don't see the character. What I do see is the decimal HTML entry... Why is that? Is this problem solvable without any modules? Thanks,
Answer: You can use the Menu HTML module for that.
It uses a bunch of alter hooks, which means you could theoretically reproduce the same functionality in a theme if you really want to. So yes, it's possible to solve without using a module per se.
Modules are the proper way to add such functionality, though, hacking this into a theme is bad application design in my opinion. Drupal is, intentionally, a modular system; don't be scared of installing modules to add functionality, that's what you're supposed to do :)
Comment: Yep that's a good way to look at it
Comment: Thanks for the fast answer --- Indeed, Drupal is modular but I'm sure we would agree that it's best to avoid installing modules if (!) there is an swift & easy non-modular solution, which is not the case here, So I guess a module-lover as myself will go and install Menu HTML. Thanks again.


Nginx/proxy not working properly

Question: I recently uninstalled apache2 for Nginx
I'm trying to listen on 88, 808 and 888 for my sites and redirect different subdomains for each (and another domain to another server).
the problem is that Nginx is giving bad gateway for all proxied requests and timeout for the direct ip access.
proxy conf :  --> otherdomain.fr = eror 502 bad gateway
# HTTP
server {
    # Listen on ipv4
    listen 80;
    #listen [::]:80;

    server_name  ~.*.otherdomain.fr;

    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass "http://192.168.1.17";
    }
}

server{
    listen 80;
    server_name nextcloud.domain.me;
    location / {
        proxy_set_header Host $host;
        proxy_pass "http://127.0.0.1:888";
        proxy_redirect off;
    }
}

server{
    listen 80;
    server_name domain.me;
    location / {
        proxy_set_header Host $host;
        proxy_pass "http://127.0.0.1:808";
        proxy_redirect off;
    }
}

ex for port 88: --> ip:88 = timeout
(obviously, it is enabled and the nginx user have access to the files)
server {
    # Listen on ipv4
    listen 88;

    location / {
        root /var/www/html/tests;
    }

}

I'm obviously doing something wrong but I cant find out what, if you could give me a hand it would be incredible.
Thank you in advance!
EDIT :
netstat -tulpen | grep -E '8.?8'

tcp        0      0 127.0.0.1:10028         0.0.0.0:*
LISTEN      0          28186      1929/master tcp        0      0
0.0.0.0:80              0.0.0.0:*               LISTEN      0          91603      8801/nginx: master tcp        0      0 127.0.0.1:12340
0.0.0.0:*               LISTEN      0          25868      734/dovecot tcp        0      0 127.0.0.1:631           0.0.0.0:*
LISTEN      0          19881      497/cupsd tcp        0      0
0.0.0.0:88              0.0.0.0:*               LISTEN      0          75033      8801/nginx: master tcp        0      0 0.0.0.0:888
0.0.0.0:*               LISTEN      0          75032      8801/nginx: master tcp        0      0 0.0.0.0:443             0.0.0.0:*
LISTEN      0          75030      8801/nginx: master tcp        0
0 127.0.0.1:10025         0.0.0.0:*               LISTEN      0
28182      1929/master udp6       0      0 :::32885
:::*                                113        21172
482/avahi-daemon: r"""
Comment: What's the reason to differentiate the ports and then proxying them? What's the output of `netstat -tulpen | grep -E '8.?8?'`` ? Do you have `listen` directives for all of these ports?
Comment: 1./ I'm proxying and differentiate the ports because I use a different server for each one (808 is a cherrypy serv actually not running, otherdomain.fr is another machine (apache2), 888 is nextcloud with this instance of nginx (and php8.0) and I only use 88 for testing purposes so I don't use a subdomain for it)

2./ see EDIT

3./ yes I do
Comment: EDIT : I could remove the port for nextcloud and maybe port 88
Comment: nginx requires either a location, an server name or an ip in the servername. else it will imho not serve the contents as it does not know whatever to do with it., moreover for what reason do you uae `~.*.` in servername?
Comment: What is the content of nginx `error.log`?
Comment: @djdomi the regex is made to redirect every subdomain of otherdomain.fr to this ip
Comment: @TeroKilkanen
For 3 requests :
otherdomain.fr
domain.me:88
nextcloud.domain.me

I get :
`2021/11/05 10:05:52 [error] 22452#22452: *1 connect() failed (113: No route to host) while connecting to upstream, client: 220.127.116.11, server: ~.*.otherdomain.fr, request: "GET / HTTP/1.1", upstream$
2021/11/05 10:05:55 [error] 22452#22452: *3 connect() failed (113: No route to host) while connecting to upstream, client: 18.104.22.168, server: ~.*.otherdomain.fr, request: "GET /favicon.ico HTTP/1.$`
Answer: You don't need quotes around the destination URL of proxy_pass.
Main problem is the server_name ~.*.otherdomain.fr and the fact that you are using proxy_set_header Host $host.
In this case it seems your regular expression for server_name is invalid and it is taken as a string. That string appears then in $host variable.
You should try
server_name *.otherdomain.fr;

instead. If that doesn't work, use
proxy_set_header Host $http_host;

Which passes the HTTP Host header onward instead of contents of $host variable.
Comment: i was guessing correctly that regrx works but is conflict with the rest ;) thabks fir the clarification of my thoughts

Nginx/proxy not working properly


Biased coin probability example: Bayes' rule and the law of total probability

Question: My textbook gives the following example:

You have one fair coin, and one biased coin which lands Heads with probability $3/4$. You pick one of the coins at random and flip it three times. It lands Heads all three times. Given this information, what is the probability that the coin you picked is the fair one?
Solution:
Let $A$ be the event that the chosen coin lands Heads three times and $F$ be the event that we picked the fair coin. We are interested in $P(F \mid A)$, but it is easier to find $P(A \mid F)$ and $P(A \mid F^c)$ since it helps to know which coin we have; this suggests using Bayes' rule and the law of total probability. Doing so, we have
$$\begin{align} P(F \mid A) &= \dfrac{P(A \mid F)P(F)}{P(A)} \\ &= \dfrac{P(A \mid F) P(F)}{P(A \mid F) P(F) + P(A \mid F^c) P(F^c)} \\ &= \dfrac{(1/2)^3 \cdot 1/2}{(1/2)^3 \cdot 1/2 + (3/4)^3 \cdot 1/2} \\ &\approx 0.23 \end{align}$$

Bayes' rule is as follows:
$$P(A \mid B) = \dfrac{P(B \mid A) P(A)}{P(B)}$$
And the law of total probability is as follows:
Let $A_1, \dots, A_n$ be a partition of the sample space $S$, with $P(A_i) > 0$ for all $i$. Then
$$P(B) = \sum_{i}^n P(B \mid A_i) P(A_i)$$
What I don't see is how the authors got $P(A) = P(A \mid F) P(F) + P(A \mid F^c) P(F^c)$?
I would appreciate it if people could please take he time to clarify this.
Comment: What do you mean?  For any event $F$ the two events $F, F^c$ are mutually exclusive and exhaustive, hence the law of total probability can be applied.
Comment: That's just [the Law of Total Probability](https://en.wikipedia.org/wiki/Law_of_total_probability).
Comment: @lulu hmm, how?
Comment: Well, $P(A\,|\,\,B)\times P(B)=P(A\cap B)$ and $F,F^c$ are mutually exclusive and exhaustive so...
Comment: @lulu But I don't see where the complements are coming from?
Comment: @lulu Oh, I see.
Answer: lulu is right: In your formula for the law of total probability take $A_1 = F$ and $A_2 = F^c$. Then $A_1,A_2$ is a partition of the sample space and
$$
P(A) = \sum_{i=1}^2 P(A \mid A_i) P(A_i) = P(A \mid F) P(F) + P(A \mid F^c) P(F^c)
$$
is exactly that formula with the sum written out.


Help understanding a proof about cardinal numbers

Question: I was reading a proof about cardinal numbers, but I do not understand one step. The proof goes as follows:
"Let $\beta$ be any ordinal, and for each ordinal $\alpha \lt \beta$, let $\kappa_{\alpha}, \lambda_{\alpha}$ be cardinals, where $\kappa_{\alpha} \lt \lambda_{\alpha}$. Then, alpha
$$\sum_{\alpha\lt\beta}\kappa_{} \lt \prod_{\alpha \lt \beta}\lambda_{\alpha}$$
The basic idea of the proof is to prove there is an injection from the cardinal sum to the cardinal product, to show that the cardinal sum is less than or equal to the cardinal product. Then, the author assumes that they are equal to each other and finds a contradiction. I do not understand the injection he creates
"Proof:
Define
$$f\colon \bigcup_{\alpha \lt \beta}(\kappa_{\alpha} \times \langle \alpha\rangle) \rightarrow \prod_{\alpha \lt \beta}\lambda_\alpha$$
by taking $f(\xi, \gamma)$ to be that element of $\prod_{\alpha \lt \beta}\lambda_{\alpha}$ that takes the value $\xi \in \lambda_\gamma$, in the $\gamma$'th place and the value $0$ elsewhere. That is,
$f(\xi,\gamma)(\nu) = \xi$ (if $\nu = \gamma$) and
$0$ otherwise."
I do not understand this function, or what it does. I do not understand what "that element of $\prod_{\alpha \lt \beta}\lambda_\alpha$ that takes the value $\xi \in \lambda_{\gamma}$ in the $\gamma$'th" place means. I also don't understand the notation $f(\xi, \gamma)(\nu)$ means as well. Could someone help me?
Answer: An element of the product is given by specifyig for each index an element of the corresponding factor. In other words, it is a function $\phi$ from the index set (here $\beta$) to $\bigcup \lambda_\alpha$ such that for each $\alpha\in \beta$ we have $\phi(\alpha)\in\lambda_\alpha$.
Now the map $\phi=f(\xi,\gamma)$ that $f$ yields for a given $(\xi,\gamma)$ (with $\xi\in\kappa_\gamma$!) is chosen such that $\phi(\gamma)=\xi$ (which is allowed because $\xi\in\kappa_\gamma\subseteq \lambda_\gamma$); since we cannot safely guess anything else, we also let $\phi(\nu)=0\in\lambda_\nu$ for any $\nu\ne\gamma$. In short (and replacing $\phi$ by $f(\xi,\gamma)$ again)
$$f(\xi,\gamma)(\nu)=\begin{cases}\xi&\text{if $\nu=\gamma$}\\0&\text{else}\end{cases} $$


Azure Event Hub Python SDK - exceptions

Question: If I have 1 throughput unit (which allows 1000 msg/sec or 1Mb/sec) for an Event Hub and try to send more than 1000 msg/sec does the Azure Python SDK throw an exception or have some sort of return code that would notify me that I've exceeded my quota?
Answer: There are quotas and limits for Event Hubs(Service Bus).
The number of concurrent connections on a namespace for Event Hubs is 1,000 for NetMessing protocol or 5,000 for AMQP, see below:

For the message or event size, the entity name limits 50 charaters, and the maximum size of event is 256KB, see below:

About more details, you can refer to https://azure.microsoft.com/en-us/documentation/articles/service-bus-quotas/ to know it.
If you are developing IoT application and the throughput of data exceeds the quota of Event Hubs, I recommend to use the Azure IoT Hub. You can refer to https://azure.microsoft.com/en-us/documentation/articles/iot-hub-compare-event-hubs/ to know their differences.
Defect is that Azure IoT Hub has SDK for C, .Net, Java, NodeJS currently, but no SDK for Python. You can refer to https://azure.microsoft.com/en-us/documentation/articles/iot-hub-sdks-summary/ to know IoT SDK, or refer to https://azure.microsoft.com/en-us/documentation/articles/iot-hub-sdks-summary/ to use the IoT Hub REST APIs.

Azure Event Hub Python SDK - exceptions


Angular4 - cant implement password match validator

Question: From Angular docs:
const form = new FormGroup({
  password: new FormControl('', Validators.minLength(2)),
  passwordConfirm: new FormControl('', Validators.minLength(2)),
}, passwordMatchValidator);

function passwordMatchValidator(g: FormGroup) {
   return g.get('password').value === g.get('passwordConfirm').value
      ? null : {'mismatch': true};
}

I don't know how to call that passwordMatchValidator function. Tried something like:

But without any success...
Comment: @AJT_82 - Jeez... Thanks! If you provide the answer i could accept it, otherwise will delete it soon
Comment: Done! Glad to hear it was such a quick fix! :)
Comment: You don't need to call it. It is called everytime changes happens in form. Or what do you mean with **calling** it?
Comment: @AJT_82 but how do i show the error for this validation? I want to show the div element with some text that says "passwords do not match"
Comment: `` :)
Answer: To show the div with the error message if passwords don't match, you just do:


Why does this R ggplot2 code bring up a blank display device?

Question: While SO is not usually used for help with bugs, this one shows particularly simple and particularly annoying behavior. If you are a ggplot2 user, you can reproduce it in 10 seconds or less.
As this GitHub issue: ggplot_gtable creates blank display says, the following code
library(ggplot2)
stat = qplot(Sepal.Length, Petal.Length, data = iris, color = Species)
ggplot_gtable(ggplot_build(stat))

will produce a blank device. Note that since ggplot2 is a graphics library, some commands can bring up a graphics device to show the relevant plot. Specifically, just running ggplot_build(stat) will bring up a plot. But that doesn't explain this behaviour.
I'm not sure how to debug this (print statements don't really seem appropriate or useful), and the ggplot2 development community seems to be on vacation or something, so if any experienced R user can offer suggestions on how to debug this effectively, I would appreciate it. This is a trivial but incredibly annoying bug. Every time I run code which looks like the snippet, it brings up a blank device which the display switches focus to, and so I have to click it away before I can continue.
It is possible that I'm doing something horribly wrong and am the only person who can reproduce this bug. It is also possible, for some reason I can't imagine, that this is normal behavior. If you think either of these things are true, please let me know.
I'm using ggplot2 0.9.3.1 (latest release) on Debian squeeze.
Comment: what do you want to do with `ggplot_gtable(ggplot_build())`? (btw there's `ggplotGrob()`. My guess is that during the gtable creation, an open device is needed to resolve some kinds of grid units.
Comment: Does not happen on OSX: 10.7.5 /R: 3.0.1/ggplot2_0.9.3.1 when called from the GUI 1.60 (6475), but it does happen when called within an R session started in Terminal.app
Comment: @baptiste: The definition of `ggplotGrob` is `ggplot_gtable(ggplot_build())`. I'm using to get my hands on the grob table.
Comment: @DWin Thanks. That's useful information. So it is OS specific.
Comment: Added info in the 5 minute window. Interface specific as it turns out.
Comment: @DWin Ok, I'll update the issue with this information. Thanks.
Comment: Hmmm... I'm on OSX 10.8.3, R 3.0.1, R.gui 1.61 (6492) and ggplot2 0.9.3.1 and the blank page appears for me in both R.app and command line R.  The venn diagram of everyone's observations must point to the answer somehow.  Thanks Faheem for pursuing these issues.
Comment: another observation: `stat2 = stat + guides(colour="none")` doesn't open a window. Something about grid units in the guides
Comment: ... and indeed, `ggplot2:::guides_build` calls `widthDetails/heightDetails` which can require an open device: try this for instance, `library(grid); widthDetails(textGrob("hi"))`.
Comment: @baptiste I see. The chain looks like `ggplot_gtable` -> `build_guides` ->`guides_build`. This does look like what is going on. I don't understand why it is necessary to open a device, though. Can you add an answer? The page for `widthDetails` and `heightDetails` don't say anything about opening a device.
Answer: Some grid grobs have units that can only be resolved at drawing time, that is to say once a device window is open. This is the case of text grobs, for instance, as their size can depend (in the most general case) of the cex and fontsize arguments of the parent(s) viewports (which can be nested, etc.)
library(grid)
widthDetails(textGrob("hi"))

The current version of ggplot2 appears to use widthDetails in the code to build the legend grobs (guides_build function). It is conceivable that this could be replaced by grobWidth,  unless the grob size is too convoluted.
Comment: Thanks. What would the advantage of `grobWidth` be?
Comment: it doesn't open a window, apparently. But I never fully understood the difference between the two to be honest, probably only few others than Paul Murrell could tell for sure.
Comment: `grobWidth` works fine in place of `widthDetails`, but `ggplot_gtable` eventually calls `height_cm` --> `grid::convertWidth` --> `grid::convertUnit`, the last of which requires an open device.
Answer: I wonder if it is related to this thread from 3 years ago on R-Help with this workaround from @G.Grothendieck (copied material follows)
https://stat.ethz.ch/pipermail/r-help/2010-December/263754.html
library(lattice)
library(zoo)

df <- data.frame(y = matrix(rnorm(24), nrow = 6), x = 1:6)
xyplot(zoo(df[1:4], df$x), type = "p")

plot.object <- xyplot(zoo(df[1:4], df$x), type = "p")
# problem: a Quartz device is opened (on Mac OS X 10.6)

Grothendieck wrote in response:

This also opens up a window on Windows.   It occurs within lattice
  when lattice issues a trellis.par.get .  A workaround would be to open
  a device directed to null.  On Windows this would work.  I assume if
  you use "/dev/null" it would work on your machine.

png("NUL")
plot.object <- ...
dev.off()

Comment: it doesn't feel very elegant, but I guess in some cases it's the only way to work around grid's idiosyncrasies. The preferred null device, I believe, is `pdf(file = NULL)`.
Comment: That's interesting. I wonder if such a thing would be an option here. @baptiste? Maybe add a link to the r-help thread? Gmane is what I usually link to. I reformatted your answer a bit - could you approve? Thanks.
Comment: Replaced original text with link to the (real) R-help Archive at `stat.ethz.ch`. I use MarkMail for search.
Answer: I am still having this issue with R 3.6.1 in 2019.
My lack of reputation doesn't allow me to comment. So I am writing yet another answer:
Things become a bit tricky if your plot uses non-standard fonts, say
library (ggplot2)
stat = qplot(Sepal.Length, Petal.Length, data = iris, color = Species) +
  theme(text = element_text (family="DejaVu Sans"))

As was explained in the answer by baptiste, the output device is needed in order to determine some text dimensions. With the non-standard font, however, you need the appropriate output device. If you just use a pdf(file=NULL) as baptiste said, you get the dimensions wrong (and a warning that 'DejaVu Sans' was substituted by another font which is responsible for the false dimensions). In order to resolve this, I had to open an output device that is able to render the non-standard font (with a temporary file, say):
cairo_pdf (tempfile (fileext=".pdf"))
grob = ggplot_gtable (ggplot_build (stat))
dummy = dev.off ()

Hope this information is useful.
Answer: Problem seems to be caused by "color = Species".
If replaced by "group = Species", then no more blank display device.
Comment: Welcome. This isn't really an answer -- it is a comment. If you read the other (complete) answers, you will understand **why** `group = Species` does not cause a problem when `colour = Species` does.
Comment: @mnel Agreed. user2640757, please change this to a comment. Thanks.


What is the right usage in Fisher test in R

Question: So I have data in form (in real data I have more rows, of course so this is just a sample)
>df <- structure(list(cake.eated = c(1, 0, 0, 1, 1, 1), is.it.weekend = c(1, 1, 1, 0, 1, 0)),
+ .Names = c("is.cake.eated","is.it.weekend"), row.names = c(NA, -6L), class = "data.frame")
>df

 is.cake.eated is.it.weekend
         1             1
         0             1
         0             1
         1             0
         1             1
         1             0

and I woulf like to perfotm Fisher's test to it. In contigency-table form my data looks like
>c = matrix(c(2205,2605,1442,1042), ncol=2)
>rownames(c) <- c("cake.eated", "cake.not.eated")
>colnames(c) <- c("not.weekend", "weekend")
>c

                  not.weekend  weekend
 cake.eated            2205    1442
 cake.not.eated        2605    1042

So my question is, which one of these is the right way to use Fisher's test in R;
> fisher.test(c)

      Fisher's Exact Test for Count Data

data:  c
p-value < 2.2e-16
alternative hypothesis: true odds ratio is not equal to 1
95 percent confidence interval:
0.5539554 0.6753183
sample estimates:
odds ratio
0.6117068

OR
>fisher.test(df$is.cake.eated, df$is.it.weekend)
      Fisher's Exact Test for Count Data

data:  df$is.cake.eated and df$is.it.weekend
p-value = 1
alternative hypothesis: true odds ratio is not equal to 1
95 percent confidence interval:
0.8607512 1.1611740
sample estimates:
odds ratio
     1

Is Fisher test even okay to use in this case an this kind of data or is some else like chi-squared better? Why are the results from fisher tests so different and what am I doing wrong?
> chisq.test(df$is.cake.eated, df$is.it.weekend)

    Pearson's Chi-squared test with Yates' continuity correction

data:  df$is.cake.eated and df$is.it.weekend
X-squared = 1.781e-06, df = 1, p-value = 0.9989

Also, by Barnard test my results look like
> barnard.test(2205, 1442, 2605, 1042, dp=0.01)

       Barnard's Unconditional Test

       Treatment I Treatment II
Outcome I         2205         1442
Outcome II        2605         1042

Null hypothesis: Treatments have no effect on the outcomes
Score statistic = 9.88313
Nuisance parameter = 0.03 (One sided), 0.97 (Two sided)
P-value = 7.65658e-22 (One sided), 7.65658e-22 (Two sided)

Comment: Where does the `rain.zeros` data come from (where you run `fisher.test(df$is.cake.eated, df$is.it.weekend)` the output data does not match the input.)
Comment: sorry, I copied wrong stuff from my console. Should be okay now
Comment: Thanks. Will try to replicate it and update my answer. Is that the output you get from running it on your real data?
Comment: Yes these were the results from my real data. I will also check this now again couple of times if I haven't noticed something relevant
Comment: And is the table c the real data? An odds ratio of 1 means the outcome is the same in the two groups so I suspect something has gone wrong with the data.
Comment: I found the problem.. I had the contigency table totally wrong.. heh, this is kind of embarrassing =/. But yeh, the real one looks like `contig = matrix(c(412,1033,630,1575), ncol=2)´  But thanks anyway, you made me to question myself and that solved the problem =)
Answer: fisher.test
With fisher.test you can run it either on a table, as in your example fisher.test(c) or you can run it on two vectors, as in your second example. It looks like the output you have provided from fisher.test(df$is.cake.eated, df$is.it.weekend) does not match the input. They should correspond if the correct data are used:
df <- structure(list(cake.eated = c(1, 0, 0, 1, 1, 1), is.it.weekend = c(1, 1, 1, 0, 1, 0)),
                .Names = c("is.cake.eated","is.it.weekend"), row.names = c(NA, -6L), class = "data.frame")

fisher.test(df$is.cake.eated, df$is.it.weekend)

Gives
    Fisher's Exact Test for Count Data

data:  table(df)
p-value = 0.4667
alternative hypothesis: true odds ratio is not equal to 1
95 percent confidence interval:
  0.00000 11.81149
sample estimates:
odds ratio
         0

And fisher.test(table(df)) gives
    Fisher's Exact Test for Count Data

data:  table(df)
p-value = 0.4667
alternative hypothesis: true odds ratio is not equal to 1
95 percent confidence interval:
  0.00000 11.81149
sample estimates:
odds ratio
         0

Chi-squared test
The chi-squared test and Fisher's exact test are used to do similar things: test the association between two categorical variable. However, they go about it in different ways. You can find details in standard statistics text books, but basically the chi-squared test approximates the p value (it is said to be 'asymptotic') whereas the exact test gives an exact p value. For this reason I tend to always use Fisher's exact but you could use chi-squared here.
The rule of thumb about using chi-squared is that no cell in the table should have an expected cell count of less than 1, and no more than 20% of the cells should have an expected count of less than 5. You can access the expected cell counts in R:
chisq.test(c)$exp
In your example, this is satisfied and the chi-squared approximation is valid:
chisq.test(c)$exp
               not.weekend weekend
cake.eated            2405    1242
cake.not.eated        2405    1242

chisq.test(c)

    Pearson's Chi-squared test with Yates' continuity correction

data:  c
X-squared = 97.189, df = 1, p-value < 2.2e-16


Java banking system problems

Question: I'm making a banking system based on an UML that I got recently. I'm having problems finishing some methods, whereas I tried several things to complete it myself.
It's the following. My method "addInterest()" isn't adding any sort of interest to the balance that one account has. May it be checking account or savings account. it just doesn't add it.
And one more question, in the requirements it's being said that after every new customer has been made, 2 accounts are being made. I hope i've done it correctly, and some correction would be highly appreciated! I know that the code isn't 100% complete yet, but i'm doing it bit by bit.
Account.java
package com.company;

public class Account {
    public static Double interest = 0.042;
    private static Long number = 0L;
    private Double balance = 0.0;

    public Account(Double interest, Long number, Double balance) {

        number = Account.number;
        balance = this.balance;
    }

    public void deposit(Integer amount) {

        balance = balance + amount;

    }

    public double addInterest() {
        return balance += balance * interest;
    }

    public double getBalance() {

        return balance;

    }

    public static void main(String[] args) {
        Account checkingaccount = new Account(interest, 1L, 0.0);
        Account savingsaccount = new Account(interest, 1L, 0.0);

        Customer customer = new Customer(1L, "John Doe", savingsaccount, checkingaccount);

        checkingaccount.deposit(500);
        savingsaccount.deposit(100);

        checkingaccount.addInterest();
        savingsaccount.addInterest();

        System.out.println("Has a balance of " + checkingaccount.getBalance());

        System.out.println("Has a balance of " + savingsaccount.getBalance());

        System.out.println("Total balance is " + customer.totalBalance());

    }
}

Customer.java
class Customer {
    private static Long lastNumber;
    private String name;
    private Account savingsAccount;
    private Account checkingAccount;

public Customer(Long lastNumber, String name, Account savingsAccount, Account checkingAccount){
    //add lastnumber
    this.name = name;
    this.savingsAccount = savingsAccount;
    this.checkingAccount = checkingAccount;
}

public String getName(){
    return this.name;
}

public Account getCheckingaccount(Account checkingaccount){
    return checkingaccount;
}

//public Long getUniqueNumber(){
//
//}

public Account getSavingsaccount(Account savingsaccount){
    // return savingsAccount info
    return savingsaccount;
}

public double totalBalance(){
    // return totalbalance
    return savingsAccount.getBalance() + checkingAccount.getBalance();
}

}

Comment: FYI floating-point types (i.e. `double`) aren't precise and will lead to errors when you need absolute precision, such as when handling money. [This question](https://stackoverflow.com/q/3730019/113632) goes into more detail. For practice or a homework assignment it's totally fine, but it's worth knowing that floating-point really isn't safe for this sort of task.
Comment: Be sure to initialize your balance. Right now you just declare the variable without actually putting it at 0.0 upon creation.
Comment: @dimo414 it's for homework specifically
Comment: @TimHunter i finished the Account constructor and added the initial balance for both accounts.
Comment: @Programmingboi123 yep, just sharing some knowledge :)
Comment: @Programmingboi123 Ah, you didn't put that in your posted code so I didn't see that. Another note for your `addInterest()` method, you can shorten the added interest and return it in the same line with something like `return balance += balance * interest;`.
Answer: You don't appear to be calling addInterest() in your main() method or elsewhere. You might want to call it inside .deposit() or after both .deposit() calls in main(). It depends on how you want the Account to behave (e.g. most banks add interest on a given timeline, such as once a month).

Java banking system problems


Elegant proof of $\int_{-\infty}^{\infty} \frac{dx}{x^4 + a x^2 + b ^2} =\frac {\pi} {b \sqrt{2b+a}}$?

Question: Let $a, b > 0$ satisfy $a^2-4b^2 \geq 0$. Then:
$$\int_{-\infty}^{\infty} \frac{dx}{x^4 + a x^2 + b ^2} =\frac {\pi} {b \sqrt{2b+a}}$$
One way to calculate this is by computing the residues at the poles in the upper half-plane and integrating around the standard semicircle. However, the sum of the two residues becomes a complicated expression involving nested square roots, which magically simplifies to the concise expression above.
Sometimes such 'magical' cancellations indicate that there is a faster, more elegant method to reach the same result.
Is there a faster or more insightful way to compute the above integral?
Comment: For what it's worth: using partial fractions also leads to a sum of two arctan integrals, where one has to simplify the result of the integration "by hand" afterwards to get the nice final form.
Answer: Ok, I finally found a nice method.
We have $$ \begin{align} \int_0^{\infty} \frac{dx}{x^4+ax^2+b^2} &= \int_0^{\infty} \frac{dx}{x^2}\frac{1}{(x-b/x)^2+2b+a} \\&=  \frac{1}{b}\int_0^{\infty} \frac{dx}{(x-b/x)^2+2b+a} \\&= \frac{1}{b}\int_0^{\infty} \frac{dx}{x^2+2b+a}  \\&=  \frac{
\pi}{2b\sqrt{2b+a}}   \end{align}$$
and the desired integral follows by symmetry.
Here the nontrivial step made use of the Cauchy-Schlömilch transformation (see e.g. here): if the integrals exist and $b > 0$, then $$\int_0^{\infty} f\left((x-b/x)^2\right)\, dx = \int_0^{\infty} f(x^2) \, dx$$
It is quite interesting that the above proof doesn't make use of the assumption that $a^2-4b^2 \geq 0$.
Comment: Indeed, you omitted several steps as compared to the [cited link](http://arxiv.org/pdf/1004.2445v1.pdf).
Comment: Very nice. I like this trick a lot.
Answer: It's time to return the favor from here Ruben. (>‿◠)✌
First, we will prove
$$\int_{-\infty}^\infty \frac{dx}{\beta^4x^4+2\beta^2\cosh(2\alpha)\,x^2+1}=\frac{\pi}{2\beta\cosh\alpha}$$
Note that
$$\frac{1}{\beta^4x^4+2\beta^2\cosh(2\alpha)\,x^2+1}=\frac{1}{e^{2\alpha}-e^{-2\alpha}}\left[\frac{1}{\beta^2 x^2+e^{-2\alpha}}-\frac{1}{\beta^2 x^2+e^{2\alpha}}\right]$$
Hence
\begin{align}
\int_{-\infty}^\infty \frac{dx}{\beta^4x^4+2\beta^2\cosh(2\alpha)\,x^2+1}&=\frac{1}{e^{2\alpha}-e^{-2\alpha}}\left[\int_0^\infty\frac{dx}{\beta^2 x^2+e^{-2\alpha}}-\int_0^\infty\frac{dx}{\beta^2 x^2+e^{2\alpha}}\right]\\
&=\frac{1}{e^{2\alpha}-e^{-2\alpha}}\left[\frac{e^{\alpha}}{\beta}\arctan\left(e^{\alpha}x\right)-\frac{e^{-\alpha}}{\beta}\arctan\left(e^{-\alpha}x\right)\right]_{x=-\infty}^\infty\\
&=\frac{\pi}{\beta}\left[\frac{e^{\alpha}-e^{-\alpha}}{\left(e^{\alpha}-e^{-\alpha}\right)\left(e^{\alpha}+e^{-\alpha}\right)}\right]\\
&=\frac{\pi}{2\beta\cosh\alpha}\qquad\qquad\square
\end{align}
Now
$$\int_{-\infty}^\infty \frac{dx}{x^4+\frac{2\cosh(2\alpha)}{\beta^2}\,x^2+\frac{1}{\beta^4}}=\frac{\beta^3\pi}{2\cosh\alpha}$$
Setting $a=\frac{2\cosh(2\alpha)}{\beta^2}$ and $b^2=\frac{1}{\beta^4}$, then using $\cosh\alpha=\sqrt{\frac{\cosh(2\alpha)+1}{2}}$ will give
$$\int_{-\infty}^{\infty} \frac{dx}{x^4 + a x^2 + b ^2} =\frac {\pi} {b \sqrt{2b+a}}\qquad\qquad\square$$
Comment: +1 Very nice! I hope you have these results compiled somewhere.
Answer: $\newcommand{\angles}[1]{\left\langle\, #1 \,\right\rangle}
 \newcommand{\braces}[1]{\left\lbrace\, #1 \,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\, #1 \,\right\rbrack}
 \newcommand{\ceil}[1]{\,\left\lceil\, #1 \,\right\rceil\,}
 \newcommand{\dd}{{\rm d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}
 \newcommand{\fermi}{\,{\rm f}}
 \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}
 \newcommand{\half}{{1 \over 2}}
 \newcommand{\ic}{{\rm i}}
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}
 \newcommand{\Li}[1]{\,{\rm Li}_{#1}}
 \newcommand{\pars}[1]{\left(\, #1 \,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\pp}{{\cal P}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\vphantom{\large A}\,#2\,}\,}
 \newcommand{\sech}{\,{\rm sech}}
 \newcommand{\sgn}{\,{\rm sgn}}
 \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}
 \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}$
$\ds{\int_{-\infty}^{\infty}{\dd x \over x^{4} + ax^{2} + b^{2}}
    ={\pi \over b\root{2b + a}}:\ {\large ?}.\qquad a, b\ >\ 0\,,\quad
    a^{2} - 4b^{2}\ \geq\ 0}$.

Indeed, this is essentially the @user111187 proof with the addition of some omitted details:

\begin{align}{\cal I}&\equiv\color{#66f}{\large
\int_{-\infty}^{\infty}{\dd x \over x^{4} + ax^{2} + b^{2}}}
=2\int_{0}^{\infty}{1 \over x^{2}}\,{\dd x \over x^{2} + a + b^{2}/x^{2}}
\\[5mm]&\imp\quad \half\,{\cal I}=\int_{0}^{\infty}{1 \over x^{2}}\,
{\dd x \over \pars{x - b/x}^{2} + 2b + a}\tag{1}
\end{align}

With $\ds{{b \over x}\equiv t\ \imp\ x = {b \over t}}$ we'll have:

\begin{align}\half\,{\cal I}&
=\int_{\infty}^{0}{t^{2} \over b^{2}}\,
{-b\,\dd t/t^{2} \over \pars{b/t - t}^{2} + 2b + a}
={1 \over b}\int_{0}^{\infty}{\dd t \over \pars{b/t - t}^{2} + 2b + a}\tag{2}
\end{align}

With $\pars{1}$ and $\pars{2}$:

\begin{align}
\half\,b{\cal I}&=\int_{0}^{\infty}{b \over x^{2}}\,
{\dd x \over \pars{x - b/x}^{2} + 2b + a}
\\[5mm]\half\,b{\cal I}&
=\int_{0}^{\infty}{\dd x \over \pars{x - b/x}^{2} + 2b + a}
\\[5mm]\mbox{and}\
b{\cal I}&=\half\,b{\cal I} + \half\,b{\cal I}
=\int_{0}^{\infty}{\pars{b/x^{2} + 1}\,\dd x \over \pars{x - b/x}^{2} + 2b + a}
\end{align}

With $\ds{u \equiv x - {b \over x}\ \imp\ \dd u = \pars{1 + {b \over x^{2}}}
\,\dd x}$ we'll get

\begin{align}
b{\cal I}&
=\int_{-\infty}^{\infty}{\dd u \over u^{2} + 2b + a}
={2 \over \root{2b + a}}\
\overbrace{\int_{0}^{\infty}{\dd u \over u^{2} + 1}}
^{\ds{\color{#c00000}{\pi \over 2}}}\ =\
{\pi \over \root{2b + a}}
\\[5mm]\imp{\cal I}&\equiv\color{#66f}{\large
\int_{-\infty}^{\infty}{\dd x \over x^{4} + ax^{2} + b^{2}}
={\pi \over b\root{2b + a}}}
\end{align}
Answer: Let $b=\frac{a}{2}\sin2\theta$ ($0<\theta<\frac{\pi}{2}$), then
\begin{eqnarray}
\int_{-\infty}^{\infty} \frac{dx}{x^4 + a x^2 + \frac14a^2\sin^22\theta}&=&\int_{-\infty}^{\infty}\frac{dx}{(x^2+a\sin^2\theta)(x^2+a\cos^2\theta)}\\
&=&\frac{1}{a(\cos^2\theta-\sin^2\theta)}\int_{-\infty}^{\infty}\left(\frac{1}{x^2+a\sin^2\theta}-\frac{1}{x^2+a\cos^2\theta}\right)dx\\
&=&\frac{1}{a(\cos^2\theta-\sin^2\theta)}\left(\frac{1}{\sqrt{a}\sin\theta}\arctan\frac{1}{\sqrt{a}\sin\theta}x\right.\\
&&-\left.\frac{1}{\sqrt{a}\cos\theta}\arctan\frac{1}{\sqrt{a}\cos\theta}x\right)\bigg|_{-\infty}^\infty\\
&=&\frac{1}{a(\cos^2\theta-\sin^2\theta)}\left(\frac{1}{\sqrt{a}\sin\theta}-\frac{1}{\sqrt{a}\cos\theta}\right)\pi\\
&=&\frac{\pi}{a\sqrt{a}(\cos\theta+\sin\theta)\sin\theta\cos\theta}\\
&=&\frac{\pi}{b\sqrt{2b+a}}.
\end{eqnarray}
Answer: Note
\begin{align}  \int_{-\infty}^{\infty} \frac{dx}{x^4 + a x^2 + b ^2}
 &= 2\int_{0}^{\infty} \frac{dx}{x^4 + a x^2 + b ^2} \overset{x\to\frac b x}=
 2\int_{0}^{\infty} \frac{\frac{x^2}b\ dx}{x^4 + a x^2 + b ^2}\\
&= \int_{0}^{\infty} \frac{1+ \frac{x^2}b}{x^4 + a x^2 + b ^2}dx=\frac1b \int_{0}^{\infty} \frac{d(x-\frac b x)}{(x-\frac b x)^2 +a+2b}\\
&= \frac1{b\sqrt{a+2b}}\tan^{-1}\frac{x-\frac b x}{\sqrt{a+2b}}\bigg|_0^\infty= \frac{\pi}{b\sqrt{a+2b}}
\end{align}


C++: converting Unix time to non-local timezone

Question: I am trying to convert a time held in a variable of time_t to a struct tm* in some time zone which is not the local time zone.
Building on this post, which discusses the inverse operation going from struct tm* to time_t, I have written the following function:
struct tm* localtime_tz(time_t* t, std::string timezone) {

  struct tm* ret;
  char* tz;

  tz = std::getenv("TZ"); // Store currently set time zone

  // Set time zone
  setenv("TZ", timezone.c_str(), 1);
  tzset();

  std::cout << "Time zone set to " << std::getenv("TZ") << std::endl;

  ret = std::localtime(t); // Convert given Unix time to local time in time zone
  std::cout << "Local time is: " << std::asctime(ret);
  std::cout << "UTC time is: " << std::asctime(std::gmtime(t));

  // Reset time zone to stored value
  if (tz)
    setenv("TZ", tz, 1);
  else
    unsetenv("TZ");
  tzset();

  return ret;

}

However, the conversion fails, and I get
Time zone set to CEST
Local time is: Wed Aug  9 16:39:38 2017
UTC time is: Wed Aug  9 16:39:38 2017

i.e. local time is set to UTC time, instead of UTC+2 for CEST.
Answer: The time zone abbreviations shown by date and other tools are not the names of time zones.  The IANA time zone database uses a major city within the relevant region instead.  The reason for that is that the abbreviations are not unique, and they do not convey sufficient information to convert past dates because places switch time zones.
In addition, POSIX specifies that the TZ variable has to be parsed in a specific way, and it pretty much suggests to treat a bare time zone abbreviation like UTC (but with a different abbreviation).
Instead, you have to use the actual time zone name, such as Europe/Berlin, or a POSIX time zone specifier such as CET-1CEST.
Answer: I'm providing an additional answer in case someone wants to do this in a way that is thread safe (without setting a global such as an environment variable).  This answer requires C++11 (or better) and Howard Hinnant's free, open-source timezone library, which has been ported to linux, macOS and Windows.
This library builds on <chrono>, extending it to calendars and timezones.  One can interface with the C timing API such as struct tm with this library, but such facilities aren't built in to the library.  This library makes the C API unnecessary, unless you have to interface with other code that uses the C API.
For example there is a type called date::zoned_seconds that couples a system_clock::time_point (except with seconds precision) with a date::time_zone to create local time in an arbitrary time zone.  As described in more detail here, here is how you can convert a zoned_seconds into a std::tm:
std::tm
to_tm(date::zoned_seconds tp)
{
    using namespace date;
    using namespace std;
    using namespace std::chrono;
    auto lt = tp.get_local_time();
    auto ld = floor<days>(lt);
    time_of_day<seconds> tod{lt - ld};  // <seconds> can be omitted in C++17
    year_month_day ymd{ld};
    tm t{};
    t.tm_sec  = tod.seconds().count();
    t.tm_min  = tod.minutes().count();
    t.tm_hour = tod.hours().count();
    t.tm_mday = unsigned{ymd.day()};
    t.tm_mon  = unsigned{ymd.month()} - 1;
    t.tm_year = int{ymd.year()} - 1900;
    t.tm_wday = unsigned{weekday{ld}};
    t.tm_yday = (ld - local_days{ymd.year()/jan/1}).count();
    t.tm_isdst = tp.get_info().save != minutes{0};
    return t;
}

Using this building block, it becomes almost trivial to convert a time_t to a tm in an arbitrary time zone (without setting a global):
std::tm
localtime_tz(time_t t, const std::string& timezone)
{
    using namespace date;
    using namespace std::chrono;
    return to_tm({timezone, floor<seconds>(system_clock::from_time_t(t))});
}

If you're using C++17, you can remove using namespace date as floor<seconds> will be completely provided within namespace std::chrono.
The above code creates a zoned_seconds from the string timezone and a system_clock::time_point derived from the time_t t.  The zoned_seconds is conceptually a pair<time_zone, system_clock::time_point> but of arbitrary precision.  And it can also be thought of as a pair<time_zone, local_time> since the time_zone knows how to map between UTC and local time.  So most of the user-written code above is just in extracting the local time from the zoned_seconds and placing that into a struct tm.
The above code can be exercised like this:
auto tm = localtime_tz(time(nullptr), "America/Anchorage");

If you don't need the result in a tm but can instead stay within the <chrono> system, there exists very nice features in the timezone library for parsing and formatting the zoned_seconds, for example:
cout << zoned_seconds{"America/Anchorage", floor<seconds>(system_clock::now())} << '\n';

Sample output:
2017-08-10 16:50:28 AKDT


Drupal 7 & OpenLayers - Can see sample map under OpenLayers Admin: Preview but NOT under Views: Preview

Question: I'm stumped and seeking some direction.
I'm seeking to create a dynamic map using OpenLayers, Drupal 7, Views and Custom Content Type. I've read all the documentation I can find and so far I've been able to:

successfully create a content type (using "Geolocation Field" to
store geodata instead of GeoField),
create an OpenLayers Overlay in Views, and
create a custom map (clone of Google Map example) in OpenLayers Admin.

In OpenLayers Admin I can view the sample map ('MySample Map") under OpenLayers Admin: Maps: Edit Map: Preview.  This map successfully shows data points from content in the database.
However when I create a new View of format OpenLayer with style = MySample Map nothing shows - no datapoints and no map, only the title.
Any recommendations for debugging/resolving this problem?  Thanks in advance.
Answer: Openlayers is generated via JavaScript so wont display in the views admin. Save your view and check the page/block.
If it is still not working check the width of the map. Sometimes, when set to auto the map will collapse showing nothing. Set a fixed with and check again. If it works then some simple css will fix the rest.
Good luck :)


Why doesn't a marching band have strings?

Question: In a regular orchestra the violin takes an important role. Why is it that in marching bands there are no strings usually? To give some context I'm working on a march composition and I like strings because they add a nice cinematic effect but I'm a bit iffy since a regular marching band doesn't have it. Maybe in compositions there are no rules though?
Comment: Not to rain on your parade, but ... trombones are a bt more water resistant than violins.
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/95262/discussion-on-question-by-foreyez-why-doesnt-a-marching-band-have-strings).
Answer: Marching bands are about volume, projection, and power. A violin can't possibly match the projection of a brass instrument, and thus why they aren't included.
That said, some bands have employed amplified string instruments, like electric bass, particularly for jazz and rock pieces.
Comment: @Barmar: Sitting/marching next to flutes, I tend to disagree with you...
Comment: In an orchestra, you normally have dozens of violins to 1 or 2 trumpets.  Those violins are not going to be heard at all in a field.
Comment: It was not oncommon in the early 20th century for marching bands to have banjos, one of the few string instruments loud enough.
Comment: Marching bands usually have woodwinds. Flutes aren't particularly loud.
Comment: This makes me wonder if electric violins *could* be practical in a marching band, and it's just a chicken-and-egg problem of no one bothering to write a decent piece including them since no one uses them.
Comment: @arc_lupus I think they're closer in volume to violins than brass instruments. However, they may seem louder up close because they're also more piercing tones (piccolos even more so).
Comment: One flute might not be particularly loud, for certain values of "particularly", but I think it can be seen that flutes belong to a section, which is amplification by multiplication. How loud do you expect 30 flutes to be?
Comment: Flutes are also in a higher register and have a more piercing sound. Piccolo flutes in particular pierce above the band in such a way that only a few are ever needed. The instrument commonly included in marching bands but least likely to be heard is the clarinet, which is why  it is not uncommon for clarinetists to play saxophone instead in a marching band. (I just played clarinet, but I would fake play sometimes during a particularly difficult marching move.) Saxophones were designed  to combine the sound production of a woodwind with the amplification properties of a brasswind.
Answer: Actual marching bands don't have strings - I'm sure you could extend this list of reasons:

Where would string players put sheet music?
String instruments are expensive and fragile. Whilst you can buy a professional trumpet for a couple of grand, that doesn't buy you a professional quality violin. And although you can repair a dented trumpet, a snapped neck or crushed cello body is much more serious.
Volume - you'd need lots of strings to match the volume of the wind instruments.
The bumps and so on of marching would put the strings out of tune.
Brass instruments are waterproof. Violins aren't.

...and so on.
So although you could write for Marching Band and strings you're unlikely ever to get it performed by actual people.
Instead I'd suggest writing an orchestral march, to be performed by a seated orchestra in a concert hall. There are lots of marches or march-influenced pieces in the orchestral repertoire that you could plunder for orchestration colours.
Comment: **Real marching bands** don't carry sheet music - it's all memorized. (Yeah, I know,... few and far between)
Comment: @CarlWitthoft Maybe it doesn't count as "real", but when I was in my high school marching band (playing trombone) we used sheet music. There were little music holders that clamped onto the instruments, and tiny versions of the sheet music that fit into it.
Comment: @Barmar  I marched 3 years iin high school & 4 in college, so I know about all those music holders.  My point, which was supposed to be sarcastic, is that some top-level bands do in fact memorized there charts and don't need the clip/clamp/screw-on music holders.
Comment: Where to put the charts? On the end of the instruments, like most others! Probably wouldn't use a Strad out marching, but any old fiddle would do! Can't see how bumps would untune a violin. Wouldn't really want a clarinet out in the rain - they may/may not be waterproof. Wouldn't want to do the test! True, violins probably are not waterproof... What's the so ons?
Comment: @JimCullen Chillax, bro.  My comment was merely intended as a humorous parody of all the  "real $GROUP don't ..."  cliches out there.
Comment: @Tim In all seriousness, when possible clarinetists will use a plastic or even metal clarinet for outside use.  Similarly,  many string players keep a "beater" instrument for all outside performances, even when in a "shed" ampitheatre, simply because of the risk of extreme heat or solarization.
Comment: @CarlWitthoft: Amen.  The only time we were allowed to use lyres was during parades - for a halftime shows and competitions, everything had to be memorized.  And we were definitely *not* a "top band".  Lyres and sheet music just add weight, anyway.  Marching with a French horn was tiring enough to where those few extra ounces mattered.
Comment: This anwer is largely specific to wooden string instruments. For marching, you should opt for carbon fibre or Stroh violins.
Comment: @CarlWitthoft that's a No True Scottsman. Nothing about being a marching band requires not using sheet music.
Comment: @JimCullen - except maybe marching over uneven terrain where you need to keep an eye on the ground?
Comment: @PeterCordes irrelevant. There are a number of reasons it may or may not be a *good idea*. Doesn't change the fact that saying you're not a "real marching band" if you use sheet music is a classic No True Scotsman fallacy.
Comment: 1) Marching band music is memorized (most of the time), as Carl pointed out. 2) Brass instruments cost thousands of dollars but I agree they're the more fragile and it's true that there's more chances of irreversible damage on a stringed instrument. 5) That doesn't mean they're _absolutely_ impervious or invulnerable to moisture. So this statement is half true. Wind instruments (but not all of them) more susceptible to water, however.
Answer: As Brian Thomas pointed out,  there's a huge difference between a marching band and a musical composition called a "march."
Marching bands are called that because, well, they march. Or in the case of Yale Univ.,  gyrate madly around the field.  You won't find string instruments (mostly), double-reeds, and a few other oddball instruments in a fielded band.
A composition that's a "march" may well feature percussion, keep a strict binary beat (i.e. no 3/4 or 5/4 unless you have mutants with extra legs), and generally evoke pageantry.
Comment: OP is aware that there are no strings in marching bands - wants to know *why*.
Answer: Because stringed instruments are fragile and not very loud.  And, traditionally, just because they don't.  In the same way that brass bands don't have woodwinds and string quartets don't have trombones.
If marching bands wanted strings, they'd find a way.  Either some harness contrivance, or they'd put them in the 'pit' with the heavy percussion.
And there's nothing to stop you writing for a non-marching concert band plus strings.
But you're right, if you're writing for a particular MARCHING band, it would be sensible to omit strings.
(Anyway, there are, sometimes)
https://www.connollymusic.com/stringovation/what-to-do-with-your-string-players-in-a-marching-band
Comment: Heavy percussion goes on the rolling cart with the keyboards and the amp for the cello, said cello being worn by the cellist in a modified percussion harness. Music folder for the cello is clipped into a harmonica holder worn around the neck.
Comment: @leftaroundabout My comment was based on experience. I'd link to a picture, but I can't find any at the moment. Also, I forgot to mention the Posture Pegs.
Comment: @shoover - [Here's an image](https://web.archive.org/web/20150910134409im_/http://mob.rice.edu/sections/strings/cello_harnesses.jpg) from the Internet Archive
Comment: @shoover about music clipped in a harmonica holder I'd object! However, you could always use some augmented-reality glasses.


Can't redirect STDERR or STDOUT to file

Question: I have application written in Go language and it runs in screen
(I do not think problem relates to Go language. I believe it uses STDOUT and STDERR)
screen -S log_server -d -m go run log_server.go 2 > err3.txt 1 > std3.txt

When it crashes I get error written in screen not in err3.txt or std3.txt
screen does not scroll and does not allow me to read full error.
std3.txt works properly
err3.txt has size 0 and error is printed in screen (I can see last 20 or 30 lines)
App crashes once per 3 or 5 days.
Answer: Not all spaces are permissible.  Try instead
screen -S log_server -d -m go run log_server.go 2> err3.txt 1> std3.txt

Comment: Nope.  But `> std3.txt` is a lawful form of `1> std3.txt`, so redirecting STDOUT was working, and the rest of the stuff was just creating errors or being ignored as extra arguments to the main command.  By the way, and forgive me for saying this, but feel free to ACCEPT the answer if you're happy with it.
Comment: Thank You. I ran command as you advised. `std3.txt` worked for me. So I thought these spaces are Ok.
Comment: I  planned to mark answer accepted once process will crash and I will get error in file. But it is not a problem. Thank You for you response. I am happy with your answer. It is accepted.

Can't redirect STDERR or STDOUT to file


Using Bootstrap to create holy grail style layout

Question: Sorry if this question has already been answered, I couldn't find anything that was exactly what I want.
I'm trying to create a responsive layout which is something similar to the Holy Grail Layout on A List Apart
There will be a fixed width column on the left, a variable width column in the middle and then a fixed width column on the right. The right column will only be visible in windows that are over a certain width and the whole thing will only expand up to a certain size.
I've created a jsFiddle which does exactly what I want here.
My basic HTML looks like this:

Window Width:

Two

Width:

One

Width:

Three

Width:

My question is, would it be possible to do this in something like Bootstrap. I think if it is possible then it could save me some time as I need to make it work on mobile devices, however I'm not sure how to combine some fixed and non fixed columns in a single Bootstrap layout.
Comment: Did you ever get this working reliably in Bootstrap 3?
Comment: No, I just ended up doing it without Bootstrap.
Answer: I recently had need of a Bootstrap holy grail layout (3 responsive columns, with the center column first in the source ordering, where any column can have the longest content).
Original markup:

       ...
       center column content
       ...

       ...
       left column content
       ...

       ...
       right column content
       ...

By adding a set of -inset- (margin-right) mixins/classes to complement the Bootstrap -offset- (margin-left) mixins/classes, I could achieve the layout by using these with an extra wrapping div around the center column content.
Decorated markup:

         ...
         center column content
         ...

       ...
       left column content
       ...

       ...
       right column content
       ...

JS Fiddle: https://jsfiddle.net/3n5Lvr84/
The idea is that the center column is 100% width with a -100% right-hand margin, bringing the left and right columns to the top of the center column, and the center column inner element makes room for the columns with -offset- and -inset- margins.
I have included the full set of compiled -inset- rules in the CSS of the fiddle; you need 0-12 as in the -offset- rules as well as a -12 for the center column outer element. The left and right hand column source ordering can be switching by changing the element that is float:right.
Finally, I find it tidier using the mixins. Here are the SASS-flavoured inset mixins created by repurposing Bootstrap's mixins\_grid.scss. The LESS mixins and mixins\_grid-frameword.scss can be similarly repurposed if you prefer to use the markup & class-based Bootstrap responsive grid and/or LESS.
_inset.scss
@mixin make-xs-column-inset($columns) {
  margin-right: percentage(($columns / $grid-columns));
}
@mixin make-sm-column-inset($columns) {
  @media (min-width: $screen-sm-min) {
    margin-right: percentage(($columns / $grid-columns));
  }
}
@mixin make-md-column-inset($columns) {
  @media (min-width: $screen-md-min) {
    margin-right: percentage(($columns / $grid-columns));
  }
}
@mixin make-lg-column-inset($columns) {
  @media (min-width: $screen-lg-min) {
    margin-right: percentage(($columns / $grid-columns));
  }
}

Holy grail layout for the original markup at the top of the post (once the wrapping div has been added to #center):
_holygrail.scss
@import "bootstrap/variables";
@import "bootstrap/mixins";
@import "_inset.scss";

#center {
  @include make-xs-column(12);
  @include make-sm-column-inset(-12);
  > div {
    @include make-sm-column-offset(3);
    @include make-md-column-offset(3);
    @include make-md-column-inset(3);
    @include make-lg-column-offset(2);
    @include make-lg-column-inset(2);
  }
}

#left {
  @include make-xs-column(12);
  @include make-sm-column(3);
  @include make-lg-column(2);
}

#right {
  @include make-xs-column(12);
  @include make-md-column(3);
  @include make-lg-column(2);
}

.container #right {
  float:right;
}

Credit for the non-responsive holy grail layout idea used (Tanfa flexi_floats) to https://stackoverflow.com/users/669044/clairesuzy
Comment: JS Fiddle achieving submitter's desired behaviour: https://jsfiddle.net/rbgb6apd/