Proving an inequality for positive numbers $a, b, c$

Question:
Let be $a,b,c$ positive numbers such that $a+b+c=3$. Prove that
  $$\frac{b+c+bc}{a^2+b^3+c^4}+\frac{c+a+ca}{b^2+c^3+a^4}+\frac{a+b+ab}{c^2+a^3+b^4} \le 3$$
Comment: Do you mean to say $a,b,c$ are positive numbers?
Comment: The fact that the inequality has mixed degrees (not homogeneous) makes it interesting and rare, even though it is hard to see how it relates to any other topic.
Comment: Welcome to math.SE: since you are new, we wanted to let you know a few things about the site. In order to get the best possible answers, it is helpful if you say in what context you encountered the problem, and what your thoughts on it are; this will prevent people from telling you things you already know, and help them give their answers at the right level.
Comment: Well if $a,b,c$ are positive integers and add up to 3 then $a=b=c=1$. And then $3=3$.
Comment: My bad. I mean, of course, positive real, not integer. I've just edited my post.
Answer: Using Cauchy Schwarz inequality:
$(a^2+b^3+c^4)(a^2+b+1) \ge (a^2+b^2+c^2)^2$. Do this for each denominator, then it suffices to show that
$$\sum (a^2+b+1)(b+c+bc) \leq 3(a^2+b^2+c^2)^2$$
where the sum is cyclic. Expand the left hand side, we get
$$\begin{eqnarray}
&\sum a^2b + b^2 + b + a^2c + bc + c + a^2bc + b^2c + bc \leq 3(a^2+b^2+c^2)^2 \\
\Leftrightarrow & 2 \sum a^2b + \sum a^2 c + \sum b^2 + \sum b + \sum c + 2\sum bc + \sum a^2bc \leq 3(a^2+b^2+c^2)^2 \\
\Leftrightarrow & \sum (a^2b+a^2c) + \sum a^2b + \sum a^2 + 3 + 3 + 2\sum ab + 3abc \leq 3(a^2+b^2+c^2)^2 \cdots (*)
\end{eqnarray}$$
using $a+b+c = 3$. Now note the identity
$$\sum(a^2b+a^2c) +3abc = a^2b+ab^2+b^2c+bc^2+c^2a+ca^2+3abc = (ab+bc+ca)(a+b+c)$$
which is equal to $3(ab+bc+ca)$ for this problem, so
$$(*)\Leftrightarrow \sum a^2 + 5 \sum ab + 6 + \sum a^2b \leq 3(a^2+b^2+c^2)^2$$
to be proved now.
Note the following inequalities:
$$\begin{eqnarray}(1) & \hspace{5mm}(a^2+b^2+c^2)^2 +3 \ge 4 \sum a^2b \\
(2)& \hspace{5mm}(a^2+b^2+c^2) \ge 3 \\
(3)& \hspace{5mm}(a^2+b^2+c^2) \ge ab+bc+ca
\end{eqnarray}$$
Here (1) follows from applying AM-GM to $a^4+a^2b+a^2b+1 \ge 4a^2b$ and sum up cyclicly. The other two are routine applications of Cauchy-Schwarz/AM-GM.
These implies
$$\begin{eqnarray}(1') &\hspace{5mm} \frac{(a^2+b^2+c^2)^2}{3} \ge \frac{1}{4} (a^2+b^2+c^2)^2 + \frac{3}{4} \ge \sum a^2b \\
(2')&\hspace{5mm} \frac{2}{3}(a^2+b^2+c^2)^2 \ge 6 \\
(3')&\hspace{5mm} \frac{5}{3}(a^2+b^2+c^2)^2 \ge 5(a^2+b^2+c^2) \ge 5\sum ab \\
(4')&\hspace{5mm} \frac{1}{3} (a^2+b^2+c^2)^2 \ge \sum a^2 \end{eqnarray}$$
The inequality then follows from $(1') + (2') + (3') + (4')$.
Comment: Is your Proof of Reduction to explain how CS leads the the first "suffices to show"? I do not really understand what you're trying to do.
Comment: @CalvinLin, yes. Maybe I should remove the words reduction to avoid confusion.
Answer: As a habit I write x,y,z for a,b,c. Letting $z = 3 - (x+y)$ and plotting the function in Mathematica reveals a local maximum on $[\{0,3\},\{0,3\}]$ which does appear to be very close to $x= y = 1,$ and the maximum attained is of course 3.
The partial derivative of the l.h.s. of the OP with respect to y letting x = 1 is zero at y = 1. The partial derivative of the l.h.s. with respect to x at y = 1 is zero at x = 1.
On the domain of interest, it does then appear that $a = b = c= 1$ give a maximum of 3 and the objective function is less than three for $(x,y)\neq (1,1)$ and so the inequality is true.
Answer: By Holder
$$\sum_{cyc}\frac{a+b+ab}{c^2+a^3+b^4}=\sum_{cyc}\frac{9(c^2+a+1)(a+b+ab)}{(c^2+a+1)(c^2+a^3+b^4)(1+1+1)(1+1+1)}\leq$$
$$\leq\frac{9\sum\limits_{cyc}(c^2+a+1)(a+b+ab)}{(a+b+c)^4}=\frac{1}{9}\sum_{cyc}(a^2b+a^2c+a^2bc+a^2+ab+a^2b+2+ab)=$$
$$=\frac{1}{9}\sum_{cyc}(2a^2b+a^2c+a^2bc+a^2+2ab+2)=\frac{1}{9}\sum_{cyc}(2a^2b+a^2c+abc+5)=$$
$$=\frac{2(a^2b+b^2c+c^2a+abc)+(a^2c+b^2a+c^2b+abc)+15}{9}\leq\frac{2\cdot4+4+15}{9}=3.$$
We used the following lemma.

Let $a$, $b$ and $c$ be non-negative numbers such that $a+b+c=3$. Prove that:
  $$a^2b+b^2c+c^2a+abc\leq4$$

A proof of the lemma.
Let $\{a,b,c\}=\{x,y,z\}$ such that $x\geq y\geq z$.
Hence, by Rearrangement and AM-GM we obtain:
$$a^2b+b^2c+c^2a+abc=a\cdot ab+b\cdot bc+c\cdot ca+xyz\leq x\cdot xy+y\cdot xz+z\cdot yz+xyz=$$
$$=y(x+z)^2=4y\left(\frac{x+z}{2}\right)^2\leq4\left(\frac{y+\frac{x+z}{2}+\frac{x+z}{2}}{3}\right)^3=4$$
Done!


Pitcher responsible for scored runs

Question: Which pitcher is responsible for the players left on base when the original pitcher leaves the game? For example, Pitcher A, is pulled out of the game with 2 men left on base.  A reliever - Pitcher B - comes in and a run is scored.  Is Pitcher A responsible for the men on base or the reliever, or pitcher B?
Answer: The pitcher who is responsible for putting the men on base is the one that the runs are charged against. In this case, the two men on base at the time the reliever came on are charged to the original pitcher, A. Runs for men put on base by pitcher B are charged to him.
It pitcher B came in while his team is leading by say, one run, and the reliever gives up a hit that scores one or two runs, he is charged with a blown save. If giving up the second run results in a loss (with no further runs scored in the game), the loss is charged to pitcher A,
Comment: He is only charged with a blown save if it was save situation in the first place.
Comment: The second paragraph should read (with the lead not again changing in the game); more runs may be scored on both sides so long as the lead doesn't change again.
Answer: The runners on base at the time of a pitching change are called inherited runners, and if any of them score, the run(s) are considered given up by the pitcher who allowed them on base (in your example that is Pitcher A).
Comment: There is a stat for "inherited runners scored" that can be used to measure pitchers who fail to pitch out of jams like this versus ones who succeed.

Pitcher responsible for scored runs


Composer: two vendor directories (one of them is symlinked) - shared library autoloading

Question: I need two vendor directories to be autoloaded within a Symfony 2 application. I will first explain why I need this, to make everything more clear:
I have many small projects/websites written in Symfony 2 that all symlinks a shared library which provides domain models etc.
One of the projects app structure:
|- app
|- library -> ../library (symlink)
|- src
|- vendor
|- web

The library project has many and important vendors (doctrine etc.), so I cannot install the vendors of library inside every's project vendors directory. This would take alot of disk space.
Do I need to merge the two vendors ([root]/vendors and [root]/library/vendors) so that they are all autoloaded but not copied? If I do this, my composer.lock would fail I guess, because the vendors live in different directories.
How would this be done with Composer? Any tips, I am out of ideas.
Thanks!
Comment: The key feature of Composer is to exactly allow to have different versions of a dependency inside every application you maintain. That way you have the freedom to update one application at a time and deal with the possible integration woes. Having one version centrally managed is one of the reasons nobody likes PEAR. It forces you to update everything at the same time. And also, by using a centrally managed library that is not mentioned as an application dependency, you don't know which parts are being used and cannot put the application elsewhere (read: another server) easily.
Comment: "Takes up too much disk space" shouldn't be an argument these days, unless you can tell us how much disk space all these dependencies really use that you save.
Comment: @Sven Well, diskspace is one thing, maybe not that big of an issue. But the big deal is that you need to update your vendors on xxx different places when you "copy" everything. If you symlink it, you have it all in one place. Which in my case is the best solution.

I already required both autoloaders, this works fine. But you will still have differences because the composer.lock file is not aware of the symlink.
Comment: @Sven I think you are right, I trying to get best of both worlds. But indeed, seperatly managed dependencies seems to be better. Also, the vendors take 380MB (for the shared library alone). It is quite a lot.  Well, thanks for getting me on the right path :)
Answer: The Symfony 2 app/autoload.php file can be used to add additional directories to load from.
/**
 * @var $loader ClassLoader
 */
// The Composer generated autoloader
$loader = require __DIR__.'/../vendor/autoload.php';

// An additional directory to load from
$loader->add('Cerad',   __DIR__  . '/../../cerad2/src');

// Majic
AnnotationRegistry::registerLoader(array($loader, 'loadClass'));

return $loader;

Comment: But how would I manage to keep both vendors, so the one in [root]/vendors and [root]/library/vendors in sync, so they do not contain copied vendors. In order words, both autoloaders (from library and the main) needs to know both dependencies. I already know how I can get them autoloaded, but it's more versions that can collide etc. when symlinking vendors.
Comment: I guess I answered the wrong question.  Don't use symlink and don't sweat the disk space issue unless it actually becomes a problem.


TypeScript: AWS CDK setting resource tags with loop

Question: I've faced a Circular dependency error. I'm about to create an aws tag, but I don't want to add each time the class instance; instead I've created a function, which iterates over a given object and applies them to tags.
Iterator:
 ....
 ResourceTagger = (this, id, props: cdk.CfnTag[]) => {
   props.forEach(tag => {
             cdk.Tags.of(this).add(tag.key, tag.value)
   })
 }

Function Call
....
ResourceTagger(this.vpc, id, [
 {
   key: "Stack",
   value: id,
 },
 {
   key: "Cidr IPv4",
   value: this.vpc.vpcCidrBlock,
 }

])
Error Message:
❌ Deployment failed: Error: Stack Deployments Failed: ValidationError: Circular dependency between resources:

Is there an efficient solution for this code, as well maybe there are a way without using cdk.CfnTag[] interface?
Answer: The problem is this.vpc.vpcCidrBlock which you're trying to use within your ResourceTagger. By default ec2.Vpc construct , creates many resources, which are not managed unless, if they are explicitly defined.
So in your case, when you adding a Tag some aws resources which are symbol sensitive, throws an error: ValidationError. If you want to add vpcCidrBlock try to change to string, and that should help.
As for cdk.CfnTag[]:
You can try something like this:
ResourceTagger = (this, props: Record<string, string>) => {
Object.entries(props).forEach(([key, value]) => {
  cdk.Tags.of(this).add(key, value)
});

ResourceTagger(this, {
"Foo1": "Bar1",
"Foo2": "Bar2",
})


Prove that $\lim_{x \to \infty} f(x) = \infty$ implies that $f$ is strictly increasing on some range $(a, \infty)$, ($a \in \mathbb{R}.$)

Question: Consider the following statement:
If
$$
\lim_{x \to \infty} f(x) = \infty,
$$
exists such an $a \in \mathbb{R}$, that $f$ is strictly increasing on $(a, \infty)$, i.e., for all $a < b < c$,  $f(b) < f(c)$.
Proof:
Assume on the contrary that there is an $a \in \mathbb{R}$ such that $f$ is monotonically decreasing on $(a, \infty)$, i.e., for all $a < b < c$ $f(b) \geq f(c)$. Let $B = \max_{b > a}\{
f(b) \} \in \mathbb{R}$. We see that $\lim_{x \to \infty} f(x) \leq B \in \mathbb{R}$; a contradiction.
Question:
Is my prove correct and rigorous? If not, how can I improve it?
Answer: The proof is wrong. It has to be, since the statement is false. Just consider $f(x)=x+2\sin(x)$. You have $\lim_{x\to\infty}f(x)=\infty$, but, for any $a\in\Bbb R$, $f|_{(a,\infty)}$ is not monotonous.
Concerning your proof, you seem to be assuming that if $f|_{(a,\infty)}$ is not increasing, then it is decreasing. That is false.
Answer: Monotonically increasing and monotonically decresing are not the only possibilities. If $f(x)=n$ for $2n \leq x <2n+1$ and $2n$ for $2n-1\leq x<2n$ then $f$ is neither monotonically decresing nor monotonically increasing so the assertion is false.


How to find sum of $n^{3}/n!$, when $n$ goes from 0 to infinity?

Question: I know that i should get sums of $1/n!$ which are equal to $e$, but i don't know how to begin and how should i transform $n^{3}$?
Answer: See that $$\begin{align}{n^3\over n!}
&= {n^2\over (n-1)!}\\
&= {n(n-1) \over (n-1)!} + {n \over (n-1)!}\\
&= {n\over (n-2)!} +{n\over (n-1)!}\\
&= {n-2\over (n-2)!}+{2\over (n-2)!} +{n-1\over (n-1)!} + {1\over (n-1)!}\\
&= {1\over(n-3)!} + {2\over(n-2)!} + {1\over(n-2)!} +{1\over(n-1)!}\\
&= {1\over(n-3)!} + {3\over(n-2)!} +{1\over(n-1)!}  \end{align}$$
And use what you know for $\sum {1\over n!}$
Thus $$\begin{align}
\sum_{n=0}^{+\infty} {n^3 \over n!}
&= 1 + 4 +\sum_{n=3}^{+\infty} {1\over(n-3)!} + {3\over(n-2)!} +{1\over(n-1)!}\\
&= 5 +\sum_{n=0}^{+\infty} {1\over n!} + 3\sum_{n=1}^{+\infty} {1\over n!} +\sum_{n=2}^{+\infty} {1\over n!}\\
&= \sum_{n=0}^{+\infty} {1\over n!} + 3\left(1+\sum_{n=1}^{+\infty} {1\over n!} \right)+2+\sum_{n=2}^{+\infty} {1\over n!}\\
&= \sum_{n=0}^{+\infty} {1\over n!} + 3\sum_{n=0}^{+\infty} {1\over n!} +\sum_{n=0}^{+\infty} {1\over n!}\\
&= 5e
\end{align}$$
Answer: The trick is to decompose $n^3$ as a sum of falling factorials,
$$n^3=n(n-1)(n-2)+an(n-1)+bn$$ that will simplify with the factors of $n!$
Identifying for two values of $n$ and solving
$$\begin{cases}
2^3=2(2-1)(2-2)+2(2-1)a+2b\\
3^3=3(3-1)(3-2)+3(3-1)a+3b\\
\end{cases}$$
you obtain
$$n^3=n(n-1)(n-2)+3n(n-1)+n$$ and
$$\frac{n^3}{n!}=\frac1{(n-3)!}+\frac3{(n-2)!}+\frac1{(n-1)!}.$$

Actually the decomposition can be obtained easily as the system is triangular:
$$\begin{align}n^3-&\color{green}{n(n-1)(n-2)}=3n^2-2n,\\
3n^2-2n-3&\color{green}{n(n-1)}=n,\\
n-&\color{green}{n}=0.\end{align}$$
This readily generalizes to any polynomial in $n$.
Answer: Hint: Expand $f(x)=e^x$ in a series and consider its derivatives.
Comment: Hem: what new will the derivatives of $e^x$ bring ?
Answer: You can consider the Euler operator $d_E=z\frac{d}{dz}$. Then
$$
\sum_{n\ge 0}\frac{n^3z^n}{n!}=(d_E)^3(e^z)
$$
but, in general
$$
(z\frac{d}{dz})^n=\sum_{k=0}^n S_2(n,k)z^k(\frac{d}{dz})^k
$$
where $S_2(n,k)$ are the Stirling numbers of the second kind. Here
$$
(z\frac{d}{dz})^3=z^3(\frac{d}{dz})^3+3\,z^2(\frac{d}{dz})^2+z(\frac{d}{dz})\ .
$$
Applied to $e^z$, one gets
$$
\sum_{n\ge 0}\frac{n^3z^n}{n!}=(d_E)^3(e^z)=(z^3+3z^2+z)e^z
$$
and specialization $z=1$ gives $\sum_{n\ge 0}\frac{n^3}{n!}=5e$.
This method gives, in general,
$$
\sum_{n\ge 0}\frac{n^m}{n!}=B_m\,e
$$
where $B_m$ is the $m$-th Bell number (Dobiński's formula).
Answer: $\newcommand{\bbx}[1]{\,\bbox[8px,border:1px groove navy]{{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$

In general, with $\ds{k \in \mathbb{N}_{\ \geq\ 0}}$:

\begin{align}
\sum_{n = 0}^{\infty}{n^{k} \over n!} & =
\sum_{n = 0}^{\infty}{1 \over n!}\,\
\overbrace{k!\oint_{\verts{z}\ =\ 1^{-}}{\expo{nz} \over z^{k + 1}}\,{\dd z \over 2\pi\ic}}^{\ds{n^{k}}}\ =\
k!\oint_{\verts{z}\ =\ 1^{-}}{1 \over z^{k + 1}}
\sum_{n = 0}^{\infty}{\pars{\expo{z}}^{n} \over n!}\,{\dd z \over 2\pi\ic}
\\[5mm] & =
k!\oint_{\verts{z}\ =\ 1^{-}}{\exp\pars{\expo{z}} \over z^{k + 1}}
\,{\dd z \over 2\pi\ic} =
\bbox[#ffe,10px,border:1px dotted navy]{\ds{k!\bracks{z^{k}}\exp\pars{\expo{z}}}}
\end{align}
The $\ds{\exp\pars{\expo{z}}}$-Taylor expansion is rather cumbersome for high values of $\ds{k}$ albeit it can be evaluated with some CAS. Namely,
\begin{align}
\sum_{n = 0}^{\infty}{n^{k} \over n!} & =
k!\bracks{z^{k}}\bracks{\expo{}\color{#f00}{z^{0}} + \expo{}\color{#f00}{z^{1}} + \expo{}\color{#f00}{z^{2}} +
{{\atop{\atop{\atop{\atop{\ds{5\expo{} \over 6}}}}}} \atop \uparrow}\!\!\!\color{#f00}{z^{3}} +
{5\expo{} \over 8}\,\color{#f00}{z^{4}} +
{13\expo{} \over 30}\,\color{#f00}{z^{5}} +
{203\expo{} \over 720}\,\color{#f00}{z^{6}} +
\,\mrm{O}\pars{\color{#f00}{z^{7}}}}
\end{align}

$$
\sum_{n = 0}^{\infty}{n^{3} \over n!} =
3!\,{5\expo{} \over 6} = \
\bbox[#ffe,10px,border:1px dotted navy]{\ds{{5\expo{}}}}
$$


Tangent vector to a curve.

Question: Given the curve
$$r(t)=(t,t^2,2)$$
I have to find the tangent vector to $r$ at $Q(1,1,2)$. From the coordinates of $Q$, I know that $t=1$, so the tangent vector is
$$r'(1)=(1,2,0)$$
But when I plot the curve $r$ and the vector $r'(1)-r(1)=(0,1,-2)$ in Geogebra it's not tangent at all. What's wrong?
Comment: Tangent vector at point $(1, 1, 2)$ is $(1, 2, 0)$
Comment: please find the gradient of the function and do dot product with unit vector $\frac{1}{\sqrt5}(1, 2, 0)$.
Comment: $(1, 1, 2) + (1, 2, 0) s$ will be tangent to $r(t)$.
Comment: @MathLover what is $s$?
Comment: a scalar, just like $t$
Comment: @MathLover So a tangent vector could be $(0,-1,2)$?
Comment: But tangent vector is just a direction. We need to also specify one of the points on the line in addition to tangent vector to uniquely identify the tangent line.
Comment: @MathLover I need to find the directional derivative of a function in the direction of the tangent vector to $r$ at $Q$.So I thought to take $(1,2,0)$.
Answer: Note that you must plot the vector $(1,2,0)$ starting at $Q(1,1,2)$ (you have possibly drawn it starting from $(0,0,0)$). A sketch is as follows

Tangent vector to a curve.


How to efficiently prepare for a 2km run

Question: so I run quite a lot, in the past 3 months I also started working out, so I reduced the number of my runs to 3-4 a week, but it's usually distances ranging from 5 to 20 km. There is this local competition for a best 2km time and I'd like to win it but I never ran short distances like this before. So if any of you have some specific advice, I would be very grateful, I have about a week to prepare.
Answer: I honestly believe that you should do some under-distances to work on your speed, because compared to the distances you are used to a 2km run is almost a sprint.
As things stand, you will struggle if you find a fast guy at the end of the race. You might stand no chance in beating him in a sprint.
So - I'd work on some repetitions over a shorter distance (say 500m) at a higher pace than you are used to do your long runs. Even better, try to make them in increasing pace and go hard for the last one. You really need to stimulate your muscles to react for the last sprint.
Answer: I am no athletics trainer whatsoever, so this is from my personal experience as a footballer who only occasionally takes part in a run.
In the next few days, train only on short distances with high pace. That can be anything from 1 km at full pace to a 5 km with intervals. Running anything more than 5 km makes no sense anymore. Your stamina is fine and should be the basis of a good performance.
Train until two days before the race, after that, only a bit of jogging (low pace, small distance) if you feel like to. You should not feel anything from training activities on the day of the race.
During the race, I think that you're best shot is to use your endurance training in your favor. So, try to get the pace up right from the beginning. Force the "sprinters" to put in enough effort right from the start to prevent them from getting a slow first kilometer and getting beat in a ferocious final kilometer.
Comment: Thanks a lot, I should have specified that I will be running on my own and be timed separately as will everyone else taking part in the competition.
Comment: Also, if I were to do 5km with intervals, what pace would you suggest for the interval and what pace for the rest period?
Comment: do the intervals with 80%-90% of your max. heartrate. The slow ones try to get in your aerobe zone or at least the transit zone. You might try 2min/5min intervals


Google chrome page load stuck on two windows 10 machines

Question: I have a strange problem with google chrome (latest version but I had the problem on previous version) on two windows 10 version 1909 Machines, on any other machine on the network I don't have this problem.

When I start chrome, if I open immediately youtube and play something I cannot open other sites. If I open another site in another tab the site load gets stuck on the first request.
If I don't open youtube, site load works but after some point in time, on new tabs site load stops working

Inspecting Network with developer tools I see that first request gets stuck in "Request sent" so any following request can't start. The other strange thing is that Performance tab tool doesn't work when the page is in this state. Page refresh obviously doesn't get things work.
I tried:

Uninstalling antivirus
Disabling windows firewall
Using another computer account
Creating and using another chrome "Person"
Clearing cache

Any advice?
Thank you
Matteo
Answer: At the end I solved reinstalling chrome after uninstalling it with the remove all personal data flag checked


Python Telegram Bot Job Queue

Question: I am trying to setup a bot that sends messages every hour, I tried everything I found in google and here in stack overflow, but can't seem to make job queue work. Here is my code, I pretty much took it from official python-telegram-bot git hub. Here is the code, any help is highly appreciated.
from telegram.ext import Updater

u = Updater('bot_token', use_context=True)
j = u.job_queue

def callback_minute(context):
    context.bot.send_message(chat_id='my_chat_id', text='One message every minute')

job_minute = j.run_repeating(callback_minute, interval=10)
u.start_polling()
u.idle()

This is traceback I am getting
Error submitting job "callback_minute (trigger: interval[0:00:10], next run at: 2021-09-06 08:50:47 UTC)" to executor "default"
Traceback (most recent call last):
  File "C:\Users\aeriu\AppData\Local\Programs\Python\Python39\lib\site-packages\apscheduler\schedulers\base.py", line 974, in _process_jobs
    executor.submit_job(job, run_times)
  File "C:\Users\aeriu\AppData\Local\Programs\Python\Python39\lib\site-packages\apscheduler\executors\base.py", line 71, in submit_job
    self._do_submit_job(job, run_times)
  File "C:\Users\aeriu\AppData\Local\Programs\Python\Python39\lib\site-packages\apscheduler\executors\pool.py", line 22, in _do_submit_job
    f = self._pool.submit(run_job, job, job._jobstore_alias, run_times, self._logger.name)
  File "C:\Users\aeriu\AppData\Local\Programs\Python\Python39\lib\concurrent\futures\thread.py", line 163, in submit
    raise RuntimeError('cannot schedule new futures after '
RuntimeError: cannot schedule new futures after interpreter shutdown

Comment: Note that you'll have to start the job queue - which is done automatically, once you call `u.start_polling/webhook` - otherwise it won't process any jobs
Comment: Tried that, it sends me an error ```Error submitting job "callback_minute (trigger: interval[0:00:10], next run at: 2021-09-06 08:34:21 UTC)" to executor "default"```
Comment: Is that the complete traceback? which ptb version are you on? The snippet works fine for me …
Comment: I am on version 13.7 and I edited main post to paste whole traceback
```
Comment: That traceback can not be produced by the snippet that you posted. you probably called `job_queue.stop()` somewhere … Please show a proper minimal working example. There is a guide on MWEs specifically for PTB [here](https://telegra.ph/Minimal-Working-Example-for-PTB-07-18)
Comment: I managed to get it to work, I pasted the code into google colab and it works there, but on my pc it gives the traceback that I pasted, I even removed and installed ptb again, but the result is still the same.
Answer: This will do the trick, when you press start:
from telegram.ext import Updater, CommandHandler

updater = Updater('YOUR_BOT_TOKEN')

def callback_minute(context):
    context.bot.send_message(chat_id='my_chat_id', text='One message every minute')

def set_timer(update,context):
    due= 10
    chat_id = update.message.chat_id
    context.job_queue.run_repeating(self.callback_minute, due, context=chat_id, name=str(chat_id))

dispatcher = updater.dispatcher
dispatcher.add_handler(CommandHandler("start", self.set_timer))
updater.start_polling()
updater.idle()

Comment: @bbfl now I'm not sure any more, is not fresh to me anymore, but i guess you need to add a handler to the dispatcher, with a function that makes contex.job_queue.stop()
Comment: thank you very much! This helped me a lot! However do you know how to stop the automatic message sender with another command like /stop?

Python Telegram Bot Job Queue


Como executar um callback quando uma animação CSS for encerrada?

Question: Eu vi que o angular-animate consegue detectar quando uma transação CSS está em progresso ou não para aplicar determinadas ações.
Eu preciso descobrir como eles fazem isso!
Exemplo:

#square{
   background-color: tomato;
   height: 100px;
   width: 100px;
   font-weight: bold;
   color: white;
   display: flex;
   justify-content: center;
   align-items: center;
   font-family: sans-serif;
   transition: background-color .2s linear, color 1s ease-out;
}

#square:hover{
    background-color: white;
    color: tomato;

}

   SQUARE

Como se faz para detectar o fim de uma transição de uma animação em Javascript Puro?
Respostas com jQuery não são bem-vindas :D
Comment: https://developer.mozilla.org/en-US/docs/Web/Events/transitionend
Comment: Possível duplicata de [Css3 parar depois de acabar a rotation?](https://pt.stackoverflow.com/questions/249479/css3-parar-depois-de-acabar-a-rotation)
Comment: Não entendi a parte do "Respostas com jQuery não são bem-vindas :D" ainda que a pergunta seja sua, ela não é para o bem da comunidade? E se alguém estiver procurando uma solução para jQuery?
Comment: @Raizant fiz isso porque sempre tem um espertão que colocam respostas que não tem nada a ver com o que foi perguntado para ganhar ponto fácil. era bem capaz de alguém colocar um `fadeOut` kkkkkkkk
Answer: O evento a se usar é o transitionend, os

let square = document.querySelector("#square");
square.addEventListener('transitionend', function (event) {
     console.log("Terminou:", event.propertyName);
});
#square{
   background-color: tomato;
   height: 100px;
   width: 100px;
   font-weight: bold;
   color: white;
   display: flex;
   justify-content: center;
   align-items: center;
   font-family: sans-serif;
   transition: background-color .2s linear, color 1s ease-out;
}

#square:hover {
    background-color: white;
    color: tomato;

}

   SQUARE

No entanto é importante notar que para cada efeito que será animado, no seu caso é color e background-color será disparado dois eventos transitionend.
Outra coisa muito importante de se notar, é que se você tirar o mouse de cima de elemento ele irá fazer a animação inversa, o que ainda é uma animação e portanto irá também disparar o evento, veja conforme o exemplo com tempos longos:

let square = document.querySelector("#square");
square.addEventListener('transitionend', function (event) {
     console.log("Terminou:", event.propertyName);
});
#square{
   background-color: tomato;
   height: 100px;
   width: 100px;
   font-weight: bold;
   color: white;
   display: flex;
   justify-content: center;
   align-items: center;
   font-family: sans-serif;
   transition: background-color 2s linear, color 3s ease-out;
}

#square:hover {
    background-color: white;
    color: tomato;

}

   SQUARE

O evento transitioncancel
Existe o evento transitioncancel que é capaz de checar se a animação/transição foi cancelada no meio do caminho

Só funciona no Firefox 53+, outros navegadores não tem suporte

conforme exemplo:

let square = document.querySelector("#square");
square.addEventListener('transitionend', function (event) {
     console.log("Terminou:", event.propertyName);
});
square.addEventListener('transitioncancel', function (event) {
     console.log("Cancelado:", event.propertyName);
});
#square{
   background-color: tomato;
   height: 100px;
   width: 100px;
   font-weight: bold;
   color: white;
   display: flex;
   justify-content: center;
   align-items: center;
   font-family: sans-serif;
   transition: background-color 2s linear, color 3s ease-out;
}

#square:hover {
    background-color: white;
    color: tomato;

}

   SQUARE

Retro-compatibilidade
Para navegadores antigos o transitionend é somente suportado com prefixos, se necessita de retro-compatibilidade então pode usar os seguintes eventos:

.addEventListener('webkitTransitionEnd'): antes do Chrome 36 e WebKit 7.0.6 (Safari e Android)
.addEventListener('oTransitionEnd'): Implementado no Opera 10.5
.addEventListener('otransitionend') (em minusculo): Implementado no Opera 12.0 (opera passou a suportar sem prefixo no 12.10)
Answer: Pra você que só quer javascript cru:
// Determinando o elemento
var e = document.getElementsByID('#square')[0];

// Checando o evento
function checkTransicao(){
    var t;
    var el = document.createElement('fakeelement');
    var transitions = {
      'transition':'transitionend',
      'OTransition':'oTransitionEnd',
      'MozTransition':'transitionend',
      'WebkitTransition':'webkitTransitionEnd'
    }

    for(t in transitions){
        if( el.style[t] !== undefined ){
            return transitions[t];
        }
    }
};

// Criando o evento
var transitEvent = checkTransicao();

transitEvent && e.addEventListener(transitEvent, function() {
    //aqui é o callback

});

Pra quem usa JQUERY:
Acredito que dê pra pegar sempre o fim da animação assim:
    $('#square').on('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend',
    function(e) {
    // execução do código pós término

  });

Ou você pode capturar o evento uma vez só assim:
    $('#square').one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend',
    function(e) {
    // execução do código pós término

  });

Você escolhe... ;)
Comment: Coloca a fonte de onde você copiou o primeiro bloco de código, por favor.
Comment: `msTransitionEnd` não esta documentado em lugar algum, existem lugares que afirmam que o correto é `MSTransitionEnd`, mas também não esta documentado.


GTM server side container setup not possible

Question: I have a problem setting up server-side container using the Google Cloud Platform. I get the message that my Google Cloud contingent would be used up (with 5 projects sitting there so far). I didn't limit it and I don't see how to unlimit it (Please take my money Google!). I looked around for an hour for a solution but can't find any. Anyone here has a solution for that?
Answer: GTM server side container setup not possible
https://measuremindsgroup.com/set-up-gtm-server-side


AWS Instance accept connection from VPN in same VPC

Question: I did setup an OpenVPN server, which works fine and the IP of the server shows instead of my machine's IP.
I am using this VPN to connect to EC2 instance, and restricting access to only instances within the same VPC, for all ports including HTTP, HTTPS & SSH.
To do so, in the inbound rules I set to only accept connection from the VPC CIDR. However whenever I try to open that server, it doesn't work and I get site can't be reached.
PS: The server used to work fine, before I restrict the access from AWS Cloud Firewall.
Answer: This is how your instances in your default VPC (172.31.0.0/16) should be configured:

The target EC2 instance

IP 172.31.16.185
Security Group permits SSH, HTTP and HTTPS access from 172.31.0.0/16

The VPN Gateway

IP 172.31.4.201
Security Group permits all outbound traffic
Disable Source/Dest check (not necessary if you NAT though)
OpenVPN is configured to NAT all the outbound traffic on eth0 which means all the traffic appears to originate from 172.31.4.201

Your laptop / OpenVPN client

SSH to 172.31.16.185 - that should go through the VPN tunnel, be NAT'ed on the VPN gateway and connect to the target system.

No public IPs involved.
Hope this helps :)
Comment: Is that how I should NAT
sudo iptables -t nat -I POSTROUTING -s 172.31.4.201/24 -o eth0 -j MASQUERADE
Comment: Close - `iptables -t nat -I POSTROUTING -o eth0 -j MASQUERADE` or with `-s the-vpn-cidr/prefix`, e.g. if the addresses inside your VPN are 10.10.10.0/24 it would be `-s 10.10.10.0/24`.
Comment: Or omit that `-s ...` altogether, it should work too.
Comment: OK, I've done all the steps above. For the NAT I used the following exactly
sudo iptables -t nat -I POSTROUTING -s 10.10.10.0/24 -o eth0 -j MASQUERADE
Still no luck :( There has to be something wrong with me.
Comment: Run `tcpdump -i tun0 -n host 172.31.16.185` on the VPN gateway and verify that you see the packets coming in from the tunnel. Then run `tcpdump -i eth0 -n host 172.31.16.185` to verify that they are coming out from the VPN GW instance NAT'ed and destined to the target box.
Comment: 0 packets
But google shows the IP of the VPN :D
Comment: Looks like your OpenVPN isn't working properly. What routes are you pushing to the client from the VPN server? What is the internal tunnel CIDR?
Comment: In the server.conf I have the following
push "route 172.31.0.0 255.255.0.0"
push "redirect-gateway def1 bypass-dhcp"
push "dhcp-option DNS 184.108.40.206"
push "dhcp-option DNS 188.8.131.52"
Comment: That looks good. What are the tunnel internal IPs? What IP does your VPN client get assigned on the tunnel interface?
Comment: What is that :D ?
Is it in base.conf? If yes, I have that remote 18.104.22.168 1194
Comment: Nope that would be in the server config, like like: `server 192.168.142.128 255.255.255.192`
Comment: server 10.8.0.0 255.255.255.0
Comment: Ok, so the iptables command should have been: `iptables -t nat -I POSTROUTING -s 10.8.0.0/24 -o eth0 -j MASQUERADE`. Delete the old rule with  `iptables -t nat -D POSTROUTING -s 10.10.10.0/24 -o eth0 -j MASQUERADE` first.
Comment: I've done the new command, but when trying to deleted the old rule I got Bad argument `**-D**'
Comment: Just `-D`, not `**-D**`.
Comment: And as far as I know iptables are like some kind of firewall right?
Because I have used it on the server, I use AWS Cloud Firewall.
Comment: Still no luck, is that the longest thread you have ever had on serverfault?
Comment: Yes, iptables is a firewall.
Comment: I didn't configure IP tables and I don't use it.
The problem I see it, is if the VPN server had a problem I wouldn't be able to get Netflix for USA, or get access to currently blocked sites in my country or get the VPN's IP when I check for my IP through browser.
I believe the problem is with the target EC2 Instance, don't you think so?
Comment: Quite likely it is :) We'll be told off and moved to chat soon. Anyway, what does `tcpdump -i tun0 -n` on the vpn server show when you try to SSH from the client to the target server? Any traffic at all?
Comment: Well, just typing this command gave me and still does lots of activity.
Comment: Restrict it to the VPC CIDR logging: `tcpdump -i tun0 -n net 172.31.0.0/16`
Comment: Nothing so far, and I can't SSH to the target while using the VPN. I can SSH to other servers, but not the target.
Comment: I will contact you through email.
Answer: That sounds like a configuration problem on the OpenVPN server side. Check the following:

You've got IP forwarding enabled.
You're NAT'ing all outbound traffic to the IP of your OpenVPN server.

Get some inspiration in this answer: OpenVPN not default gateway for all traffic.
Hope that helps :)
Comment: If I explicitly allow the IP of the OpenVPN server from the Inbound rules of that instance, it works and only me can connect to that instance.
The problem only happens when I try to allow the whole VPC by using the CIDR.
Comment: @MZaza CIDR should work too. Have you got the correct prefix length specified? If it's a default VPC it will probably be something like 172.31.0.0/16 (note the /16). What IP address has the OpenVPN server, what is the destination server and what was the CIDR that you specified?
Comment: First, to clear things up I tried to check for my IP after connecting to VPN and it showed my VPN IP, I tried a couple of blocked websites in my country just to check and they opened up.

I tried restricting access to my VPN IP only and it worked, but when I try CIDR Block it doesn't work. my CIDR block is exactly as you wrote 172.31.0.0/16.

The private IP address for the OpenVPN server is 172.31.4.201
The private IP address for the destination server is 172.31.16.185
The CIDR I specified is 172.31.0.0/16
Comment: @MZaza something isn't quite right in the setup - so you're saying that if you put 172.31.4.201/32 as a source into the 172.31.16.185's security group it works but if *in the same security group* you change it from 172.31.4.201/32 to 172.31.0.0/16 it stops working??
Comment: No, I mean if I use the public IP of the VPN which is something like 188.8.131.52 it works but if I use the CIDR, which is 172.31.0.0/16 of the VPN it doesn't work.
Comment: I see. To use VPC CIDR you have to make it work over private IPs. If you SSH to the VPN server can you then SSH to the target server's private IP 172.31.16.185? Yes/No? If not that means the Target server security group is isn't permitting access from 172.31.4.201. You'll have to get this working first.
Comment: I can SSH, I just get permission denied (public key)
Comment: I am sure I am missing something in AWS, not VPN related.
There is something I didn't do, I should have done :D
Comment: Ok, and from your VPN tunnel client (e.g. from your laptop) can you SSH to 172.31.16.185 with the VPN up?
Comment: I have SSH port also restricted to the VPC.
If I change the restricting to the public IP of the VPN, SSH will work.
Otherwise it will not
Comment: Should I disable Dest/Source check for the EC2 Instance?
Comment: Added one more answer.


Is there something wrong with this explanation of Chebyshev's Inequality?

Question: So I was revising (more like re-learning coz I suck) Chebyshev's Inequality using this document. Specifically, I am referring to Example $7$ on Page $3$, which I shall reproduce below.

Question
A coin is weighted so that the probability of landing on heads is $0.2$. Suppose the coin is flipped $20$ times. Using Chebyshev's Inequality, find a bound for the probability it lands on heads at least $16$ times.
Answer
\begin{align}
P(X \geq 16) & =
P(0 \leq X \leq 16)
\\[5 mm] & =
P(-8 \leq X \leq 16)
\\[5 mm] & =
P(|X - 4| \geq 12)
\\[5 mm] & \leq
\frac {Var(X)} {12^2}
\\[5 mm] & =
\frac {(20)(0.2)(0.8)} {144}
\\[5 mm] & =
\frac 1 {45}
\end{align}

I understand if we skip the first jump from $P(X \geq 16)$ to $P(|X - 4| \geq 12)$ because, as suggested in the document, $X \geq 0$. However, what I cannot get is how the first equality makes sense. In particular, how does $P(X \geq 16)$ equal $P(0 \leq X \leq 16)$? Also, how does $P(-8 \leq X \leq 16)$ equal $P(|X - 4| \geq 12)$?
I know the answer is correct but I cannot help but feel that the proof is not entirely mathematically right. Anyone who can explain why the first $3$ equalities make sense please do tell.
Comment: The document would be better if it started $P(X \geq 16)  = 1 -
P(0 \leq X \lt 16) = 1-P(-8 \lt X \lt 16)  = P(|X - 4| \geq 12)$
Comment: In the first line, shouldn't it be $1-P(0<X<16)$?
Comment: @Alex that's what I thought, but that's not what is written in the document. What's written in the document is what I typed. So I'm correct and the document is wrong, right?
Comment: @Henry Yes, exactly what I thought.
Answer: I think it should be
$$
P(X>16)=P(X-4>12) < P(|X-4|>12)<\frac{20 \cdot 0.2 \cdot 0.8}{12^2}
$$
This is because $|x|>x$ always
Comment: Yes. This is what I was thinking too. Basically I feel that the proof would be correct if they had skipped the first $2$ inequalities and went from $P(X > 16)$ to $P(|X - 4| > 12)$ and the rest of the steps have no issue. But I just cannot wrap my head around the first $2$ inequalities.
Comment: It would be the case if $P(0\leq X \leq 16)=\frac{1}{2}$
Comment: But that was specified nowhere in the example, was it?
Comment: Since you have $n,p,q$, you can check it yourself: $\sum_{k=16}^{20}\binom{20}{k}p^k q^{20-k}$
Comment: @Alex: that second expression  would be about $0.000000014$ which is indeed less than$ \frac1{45} \approx 0.022$
Comment: @Alex what do you mean by $|x|>x$ always? I mean if $x$ is positive, then $|x|=x$?


Is low humidity (20%) bad for wooden instruments?

Question: I live in the Midwest USA, so that means that it is about 0 degrees Fahrenheit this time of year, or lower. This means that my home's heater is put to work in the winter months.
I purchased a humidity monitor which tells me that recently the humidity has been as low as 20% in my room with the temperature at 72 degrees Fahrenheit. Is it bad to store instruments such as violins, acoustic guitars, and electric guitars in this room? How so?
The instruments are never stored in their case; they sit on a rack in the open air.
This question, What is the proper humidity range for an acoustic guitar?, reveals that

A wooden instrument is ideally kept at about 40-60% humidity

But what will happen to a wooden instrument that is stored in a room with 20% humidity for long periods of time?
If low humidity is to be avoided at all costs, is the only solution to purchase a humidifer unit (to increase the humidity of the room and counteract the effects of a heater)? Of course, one resolution is to shut off the heater, but my comfort supersedes my instruments' comfort, naturally.
Answer: When storing guitars and other instruments made of wood, one of the most important consideration is the environmental conditions that the guitar will be subject to during storage. This would include extremes of temperature and most importantly, relative humidity.
Wood is very susceptible to relative humidity levels (basically the amount of moisture in the air). Too little humidity and the wood drys out and your guitar can develop any number of problems. Conversely, if your guitar is exposed to conditions where there is too much moisture in the air, the wood can swell and cause different problems. Here is a link Humidity and Guitars that tells you more about how humidity can affect an acoustic guitar and the optimal humidity range.
Many people choose to store their guitars and other wood instruments in a hard-shell case with either a sound hole or an inside the case humidity control system.
There are several sound hole humidifiers that work great for acoustic guitars stored in their case.  Here are some of the popular varieties.
  This gadget drops in the sound hole and is suspended by the strings.  You wet the small sponge inside whenever it dries out.
  This is a Dampit Soundhole instrument humidifier.  It can be used in instruments with F holes as well as larger soundholes so it will work with violas or cellos for example.  Again it uses a sponge to hold moisture.
 This is another Planet Waves Product called Humidipack and is a two way humidifier.  According to the description on
Planet Waves dot com this is a

maintenance free, two-way humidity control system for guitar. It automatically maintains the optimal 45-50% relative humidity level within your instrument case, eliminating the guesswork and potential mess related to refilling a humidifier. Unlike refillable humidifiers, this system provides true "two-way" purified humidity control by adding and removing moisture on demand.

There are also many YouTube videos describing how to make a simple homemade humidifier using a sponge and something like a plastic sandwich bag with small holes punched in it. By making your own, you can size it to conform to any instrument or to whatever air space (however tight) might exist in your instrument's case.  I have found that denser sponges tend to hold moister longer than the cheaper light weight ones.  You can cut any sponge to fit the size you need.
If not all of your wood instruments are stored in a hard shell case or if you want to leave one on display or handy so you can play it daily without removing it from the case - you might consider a room humidifier to maintain the optimal humidity level in the room where your instruments will reside. Many models of humidifiers will automatically maintain a pre-set humidity level. You set the level and then leave it on.  When the humidity drops below the pre-set level, it will automatically come on and run until the desired humidity level is restored.
A room humidifier will not work well in a wide open space.  Ideally it should be used in a room with a door that can be kept closed during the dry heating season.  You might also add some foam weather stripping to seal any gap below the door to make it even more efficient.
Regardless of which method you choose, it is important to maintain an adequate humidity level for the health of your instruments.  With 20% or below, I am afraid your instruments may be susceptible to deleterious effects of drying.
Good luck.
Comment: What's interesting is that I have stored my wooden instruments on a rack in this very low humidity environment for several winter seasons now and I haven't noticed any issues. (I did not buy a humidity monitor until recently, and thus was wholly unaware of just how low the indoor relative humidity level sank during the winter.) Do you think that I just got lucky?
Comment: Not all guitars are as susceptible as some.  The most intolerant are acoustic guitars with solid wood tops backs and sides made from less dense woods such as spruce and cedar.  Mahogany and maple can tolerate lower humidity due to the density of the wood.
Comment: You focused on the acoustic guitar in your answer, as did the website you linked to explaining the effects of low humidity on a guitar. Are _solid-body electric_ guitars/basses as vulnerable under low relative humidity levels? All of the instrument humidifiers that I've ever seen are designed to be inserted into an instrument's sound hole (which a solid-body obviously lacks, perhaps implying that humidifiers are not obligatory for a solid-body instrument). But, then again, solid-body electric guitars are still made of wood...so I don't see how they would be any different.
Comment: @Bolt Solid Body Electric Guitars tend to be less susceptible to humidity levels than acoustics.  The wood in solid body electric guitars is typically well sealed with a finish topped by varnish or lacquer that seals the wood and inhibits the loss or absorption of moisture.  Acoustic guitars on the other hand have raw exposed wood in the inside of the body and often have a lighter finish on the outside of the body to facilitate more responsiveness since the vibrations in the body are what produces the sound.  Too much lacquer on an acoustic may dampen the sound.  Not so on electric.
Comment: Ah, that makes sense. I only have two acoustic instruments, but I am going to take your advice and get my humidity level under control, because I'd hate to see any damage to my instruments. After all, the electric guitars still have wooden fingerboards, and I'd imagine that fingerboards are not as well-sealed as the bodies. Just look at the havoc that dry air did to the sealed exterior of [this upright piano](https://youtu.be/vAvGApO1Mp4?t=5s) - yikes!
Comment: Upon further reading on this topic, I've learned that a relative humidity of 20% isn't healthy for human bodies, either. See [_"Effects of Low Humidity on Health"_](http://articles.mercola.com/sites/articles/archive/2014/01/13/low-humidity-health-effects.aspx) and, to keep it in the Stack Exchange community, [_"Does low humidity have negative health effects?"_](http://skeptics.stackexchange.com/questions/14511/)
Comment: For that reason, a _whole-home humidifier_ (which has so far been unmentioned in the answers here) is also a tenable route for me and others who live in dry or heated environments who want to care for themselves and their instruments at the same time. See [_"What are the pros and cons of a whole house humidifier?"_](http://diy.stackexchange.com/questions/2814/) for an instructive overview.
Comment: @Bolt I started to mention whole house humidifier but most folks might think that is overkill.  But you are right, in some climates and homes with certain types of heat, a whole house humidifier is a good idea if you can afford it.
Answer: At low humidity the wood will dry out and contract (shrink).  This will put stress on instrument and can cause parts of it to crack or for (glued) wood joints to come apart.
Other than room-wide humidification, the most common approach is to use miniature humidifiers that go into the instrument case with  the instrument.
A search on "instrument humidifier" should point you in the right direction.
Basically you end up using the instrument cases as tiny humidity controlled rooms.
Exposing instruments to somewhat low humidity for a few hours a day while you use them should not adversely affect them.
Comment: Good tip about the instrument humidifier, but I have 7 instruments and some of the instrument cases (e.g., for an electric guitar) are too snug to squeeze a humidifier in there. So, it seems like buying a room humidifier probably makes more sense (both in terms of price and convenience) than buying 7 humidifiers and a couple new, larger cases.
Answer: Solid wood instruments like mid to high end acoustic guitars are actually quite sensitive to humidity. It probably depends a bit on what wood(s) an instrument is made of and how the wood is seasoned.
When the ambient relative humidity is low, water will evaporate out of tone woods. When it is high, tone woods will absorb water from the atmosphere. The wetter wood is, the more dense it is and the more it swells to a larger size, and vice-versa for dryer wood.
The density of a masterial greatly affects its sonic properties, so we would want the correct moisture content in our instruments to get the best sound. What's more critical is the swelling and shrinking of tone woods as their humidity changes. This can cause quite serious permanent damage to an instrument. Even short of damage, the sizes of the different materials do not all change in the same proportion, so the instrument geometry can be thrown off leading to all kinds of problems with tuning and playability.
Most instrument manufacturers recommend keeping instruments in their cases for protection. This also helps with temperature and humidity changes, and you can merely humidify your cases instead of an entire room. If you don't want to keep instruments in their cases, then a humidifier and possibly dehumidifier is necessary to preserve them properly.
Answer: I have found that what hurts instruments the most is sudden and violent changes in temperature or humidity. If you can keep the humidity and temperature relatively constant trough the year, you should be OK.
It is things like an extended car ride in the boot of your car that has it in it to kill your instrument. I can direct you to a famous guitar dealer who I recently saw a video discussing this topic.
Comment: Agreed that extreme changes can do more harm that gradual - however constant low humidity is never good for wood which will dry and crack and shrink in the absence of enough humidity.


PyTorch ValueError: Target and input must have the same number of elements

Question: I am kinda new to PyTorch, but I am trying to understand how the sizes of target and input work in torch.nn.BCELoss() when computing loss function.
import torch
import torch.nn as nn
from torch.autograd import Variable

time_steps = 15
batch_size = 3
embeddings_size = 100
num_classes = 2

model = nn.LSTM(embeddings_size, num_classes)
input_seq = Variable(torch.randn(time_steps, batch_size, embeddings_size))
lstm_out, _ = model(input_seq)
last_out = lstm_out[-1]
print(last_out)

loss = nn.BCELoss()
target = Variable(torch.LongTensor(batch_size).random_(0, num_classes))
print(target)
err = loss(last_out.long(), target)
err.backward()

I received the following error:
Warning (from warnings module):
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/torch/nn/functional.py", line 767
"Please ensure they have the same size.".format(target.size(), input.size()))

File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/torch/nn/functional.py", line 770, in binary_cross_entropy
"!= input nelement ({})".format(target.nelement(), input.nelement()))
ValueError: Target and input must have the same number of elements. target nelement (3) != input nelement (6)

This error definitely comes from the different sizes of last_out (size 3x2) and target (size 3). So my question is how can I convert last_out into something like target (of size 3 and containing just 0s and 1s) to compute loss function?
Answer: The idea of nn.BCELoss() is to implement the following formula:

Both o and tare tensors of arbitrary (but same!) size and i simply indexes each element of the two tensor to compute the sum above.
Typically, nn.BCELoss() is used in a classification setting: o and i will be matrices of dimensions N x D. N will be the number of observations in your dataset or minibatch. D will be 1 if you are only trying to classify a single property, and larger than 1 if you are trying to classify multiple properties. t, the target matrix, will only hold 0 and 1, as for every property, there are only two classes (that's where the binary in binary cross entropy loss comes from). o will hold the probability with which you assign every property of every observation to class 1.
Now in your setting above, it is not clear how many classes you are considering and how many properties there are for you. If there is only one property as suggested by the shape of your target, you should only output a single quantity, namely the probability of being in class 1 from your model. If there are two properties, your targets are incomplete! If there are multiple classes, you should work with torch.nn.CrossEntropyLossinstead of torch.nn.BCELoss().
As an aside, often it is desirable for the sake of numerical stability to use torch.nn.BCEWithLogitsLossinstead of torch.nn.BCELoss() following nn.Sigmoid() on some outputs.
Comment: Hello mbpaulus! I have seen your comment while looking around for my target-input size mismatch problem. I am trying to use BCELoss, but getting "Target size (torch.Size([64])) must be the same as input size (torch.Size([64, 256]))" error. How can I match these sizes? Thanks!


Changing menu paths for existing nodes in Drupal 7

Question: So I have created around 100 articles of a specific content type and provided all of them a menu path under a specific menu.
Now the requirement is to alter these menu paths and give these nodes a new menu path under another menu. The longer and obvious way to go about doing this is to edit each of these content types manually and then edit the menu path to edit and point it to the new menu. This is a painstaking procedure that shall consume time. I am sure there are alternatives such as a Drupal module that let's you mass alter menu paths for a specific content type?
Alternately, is there a way for me to get into the drupal database and find out where these menu paths for a specific node/content type are stored? And I can simply execute a query that goes in and changes that?
Thanks!
Comment: Your approval rate is kind of low. Consider accepting the best answers on your posts and upvoting the ones you deem acceptable so the help you received can help others. Thanks friend.
Answer: Take a look at the Pathauto module. You can configure it to create paths automatically with a given pattern for individual content types. It also has options to bulk delete and update existing paths.
Answer:
I think you can just use Pathauto module for this.
Refer Pathauto
Rename the URL pattern and use the Bulk update function to regenerate all aliases.
You can also do this through the content overview screen (/admin/content) by filtering out the content type and then select all and choose "Update URL alias" from the drop down menu
Answer: You might want to check out these modules:
D6 - Menu Editor - provides a better interface to make it easier to edit the paths in case you have to do it manually.
D6/D7 - Menu Import  - I believe you can use this by writing up a properly formatted/syntax text file, with all of your new menu items, and import it into Drupal. If you are handy with keyboard and copy/paste regex or whatever, this might be faster.
Comment: thanks @DavidCsonka, Menu_editor does not seem to have a Drupal 7 version of it's module. Does it make any sense to give the version 6 iteration a chance anyways ? thanks!
Comment: Probably only if you don't mind using Drupal 6 core.


Google Maps Api Fusion Table select geometry where name equals variable

Question: Basically I want to pass the inputValue variable into the fusion table query to find the geometry where the value of column 'Name' equals inputValue.
I just need to know how this should be written. Any help would be greatly appreciated. Code Below:
jQuery(document).ready(function($) {

//   function init() {

var baseLatLng = new google.maps.LatLng(52.7713,-1.5550);
var newLatLng;

var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 12,
    center: baseLatLng
});

var searchOptions = {
    center: baseLatLng,
    mapTypeID: 'roadmap',
    componentRestrictions: {country: "uk"}
};

var input = document.getElementById('search');

var autocomplete = new google.maps.places.Autocomplete(input, searchOptions);

var inputValue = document.getElementById('search').value;

var geocoder = new google.maps.Geocoder();

$("#go").click(function(event) {
    event.preventDefault();
    geocodeAddress(geocoder);
    layer.setMap(map);

});

function geocodeAddress(geocoder) {
    var address = document.getElementById('search').value;
    geocoder.geocode({address: address, region: 'uk'}, function(results, status) {
        if (status === 'OK') {
        } else {
            alert('Geocode was not successful for the following reason: ' + status);
        }
        var latitude = results[0].geometry.location.lat();
        var longitude = results[0].geometry.location.lng()
        newLatLng = latitude + ',' + longitude;
        document.getElementById('results').innerHTML = "latitude:" + latitude + "
" + "longitude:" + longitude;

    });
}

var layer = new google.maps.FusionTablesLayer({
    query: {
        select: 'Geometry',
        from: 'xxxx',
        where: "'Name' = inputValue" ---HERE!
    },
    styles: [{
        polygonOptions: {
            fillColor: '#00FF00',
            fillOpacity: 0.3
        }
    }]
});
});

Thanks,
Ollie
Comment: Your "Name" column is of type number.
Comment: I can select a boundary like this: where: "'Name' = 'Derbyshire'" but I want to replace the county with the search variable
Comment: The search variable isn't going to match the names in the columns.
Answer: Figured out the solution. I'll leave this here for anyone in the future.
function getBoundry() {
        var address = document.getElementById('search').value;
        var query = "\"\'Name\' =  " + "\'" + address + "\'" + '\"';

        var layer = new google.maps.FusionTablesLayer({
            query: {
                select: 'Geometry',
                from: 'xxxxx',
                where: query
            },
            styles: [{
                polygonOptions: {
                    fillColor: '#00FF00',
                    fillOpacity: 0.3
                }

            }]

        });
        layer.setMap(map);
    }

Then the funciton is called in the click event.
$("#go").click(function(event) {
        event.preventDefault();
        getBoundry();

    });


Extension to web server to write scripts using C++?

Question: Well I was wondering if there is any extension for a web server which allows me to "script" in C++ instead of a scripting language like php?
some pseudo code:
<code>#include <iostream>

cout << "<html><title>this is a webpage</title></html>";
</code>
I know this sounds silly but I am really wondering if such thing exists.
Or maybe there is something that allows to run compiled C++ code as a webpage from a web server?
Comment: "PHP server" is a non sequitur, unless you're talking about the PHP 5.4 built-in dev server, which you most certainly aren't from the context.  What does this actually have to do with PHP?  Are you just looking for a quick and dirty C++-based web application framework ... thing?
Comment: What web server are you using? Most are not php specific and allow you to generate pages pretty much any way you want.
Comment: @Gam, if your host supports CGI, then you have your answer.  CGI is an API (well, specification, whatever), and any old program can implement it, from a freaking DOS batch file to, well, C++.
Comment: yeah just looking for a quick way for generating pages from C++ instead of PHP scripts, the webserver I hired has cgi and php support, but I don't think it allows custom extensions to be loaded. have to check that out. But it would be cool to play with it on localhost
Comment: If I understand this correctly, you are trying to work out how you can configure a web server, which is currently configured for PHP, to serve the output of a program you have written in C++. If you can confirm, you're liking looking at writing CGI scripts in C++. Take a look at http://www.geekdaily.net/2007/08/06/c-a-basic-cgi-tutorial/
Comment: oh lol CGI is the answer, CGI does have all the C++11 features?
Comment: @GamErix CGI has no concept of C++, it's just a standardized method for a web server to delegate the generation of a web page to some other executable. You can create that executable using whatever method you wish, including C++11.
Comment: em, how would I run a CGI script which has this: `#include void main(){cout << "Content-type: text/plain" << "Hello, World!";}` ? I try to run it in my localhost/file.cgi but I get an http 500 error :$
Comment: @GamErix CGI will run any type of executable file, be it a script with an interpreter directive (`!#`) or a binary executable. So for C++ you would compile your code and put that executable wherever you want the cgi program to be.
Comment: Oh thanks works :D well back to cross compatibility programming in C++, no more msvc stuff hehe :F
Comment: You can write a PHP extension in C++... This loads like any other PHP extension, and is available as a PHP function like any other PHP function.  Alternatively, if you are using Apache (or IIS), you can write an Apache (or IIS) extension, which instructs Apache (or IIS) to route certain requests to your extension (which can be written in  C++).  The latter approach is more difficult because it requires some non-trivial setup in the C++ code.  I have utilized both of these approaches for commercial clients.
Answer: Well, as said in comments you can do what you want using CGI. If your need is to make a webapp using c++, WT is probably the framework you want :
http://www.webtoolkit.eu/wt


Populating one DropDownList with another in a DataList control

Question: Have two dropdownlist inside the edit template of a DataList. The first dropdwon is for state while the second is for town. The state is populated from a table state while the second from a table town when state is selected.
Comment: Possible duplicate of a lot of questions. Search the site, it's been answered a lot of times (like this: http://stackoverflow.com/questions/8119165/how-to-filter-dropdown-list-values-by-another-dropdown-list-in-asp-net-c-sharp)
Answer: If you are using webforms, then you can create SelectedIndexChanged event who added to second dropdownlist values.
If simpley html use javacript and ajax. When selects the first dropdownlist value, create javascript ajax event to get data and put them all in second dropdownlist.


hook_menu() to display node view mode

Question: How to create hook_menu to display node view mode?
node/% - full view mode (default)
node/%/subpage - custom created view mode of this node, for example "subpage"
I've tried this: How to render custom view mode in d7 but it doesn't work. Maybe something is wrong with the code?
Answer: There is a module exists that does just that: View Mode Page.
Check it out and inspect the source to see how it works.

hook_menu() to display node view mode


Given $a,b,c,d>0$ and $a^2+b^2+c^2+d^2=1$, prove $a+b+c+d\ge a^3+b^3+c^3+d^3+ab+ac+ad+bc+bd+cd$

Question:
Given $a,b,c,d>0$ and $a^2+b^2+c^2+d^2=1$, prove  $$a+b+c+d\ge a^3+b^3+c^3+d^3+ab+ac+ad+bc+bd+cd$$

The inequality can be written in the condensed form
$$\sum\limits_{Sym}a\ge\sum\limits_{Sym}a^3+\sum\limits_{Sym}ab$$
I was told that this is a pretty inequality to prove, but I have been unable to do so.
I've tried naive things like multiplying both sides by $a+b+c+d$, and rewriting $(a^2+b^2+c^2+d^2)^2$, but nothing panned out (and the computations were relatively time-consuming). I also tried looking for clever applications of Cauchy-Schwarz (which seems like the way to go) and AM-GM, but nothing sprung out at me.
Comment: Cancelling $\sum\limits_{Sym}a^3$ in $\left(\sum\limits_{Sym}a^2\right)\left(\sum\limits_{Sym}a\right)\ge \sum\limits_{Sym}a^3 +\sum\limits_{Sym}ab$, then squaring and multiplying RHS by $\sum\limits_{Sym}a^2$ again, leads to a homogenius form: $2\sum\limits_{Sym}a^3b^3+3\sum\limits_{Sym}a^2b^2c^2\ge 6\sum\limits_{Sym}a^3bcd$, but doesn't help much though...
Answer: Let $a+b+c+d=4u$, $ab+ac+bc+ad+bd+cd=6v^2$ and $abc+abd+acd+bcd=4w^3$.
Hence, $16u^2-12v^2=1$ and our inequality is equivalent to $3v^6-4uv^2w^3+w^6\geq0$.
By Roll's theorem there are $x>0$, $y>0$ and $z>0$, for which
$x+y+z=3u$, $xy+xz+yz=3v^2$ and $xyz=w^3$.
After this substitution we need to prove that
$\sum\limits_{cyc}(x^3y^3-x^3y^2z-x^3z^2y+x^2y^2z^2)\geq0$, which is Schur.
Comment: Oh man, lots of jumps, still, this is amazing....+1
Answer: I got some hints from Crux Problem 3059, click here for more details=)
Based on the hints (which tries to relate the inequality with a constrained optimization problem), I worked out a proof as follows:
We have
\begin{align}
\frac{1}{2}(a+b+c+d)^2=&\frac{1}{2}(a^2+b^2+c^2+d^2)+ab+ac+ad+bc+bd+cd\\
=&\frac{1}{2}+ab+ac+ad+bc+bd+cd
\end{align}
by assumption. Thus, in order to prove the inequality, it is equivalent to prove
$$
a+b+c+d\geq a^3+b^3+c^3+d^3+\frac{1}{2}(a+b+c+d)^2-\frac{1}{2}.
$$
This can further be simplified as proving
$$
a^3+b^3+c^3+d^3+\frac{1}{2}(a+b+c+d-1)^2\leq1.~~~~(*)
$$
Now we try to maximize the LHS under the constraint, i.e.
\begin{align}
\max&~~f\triangleq a^3+b^3+c^3+d^3+\frac{1}{2}(a+b+c+d-1)^2\\
s.t.&~~a^2+b^2+c^2+d^2=1.
\end{align}
Now we try to use the Lagrangian multiplier method. Let
$$
L=f+\lambda(a^2+b^2+c^2+d^2-1).
$$
Take the derivative of $L$ regarding $a,b,c,d$ respectively and let the derivative equal to $0$ gives the following set of equations:
\begin{align}
L_a=&a+b+c+d+3a^2+2a\lambda=1\\
L_b=&a+b+c+d+3b^2+2b\lambda=1\\
L_c=&a+b+c+d+3c^2+2c\lambda=1\\
L_d=&a+b+c+d+3d^2+2d\lambda=1,
\end{align}
Notice that these four equations share exactly the same form. Thus, either
$$
3x^2+2\lambda x=0,~~x=a,b,c,d,~~~~(case1)
$$
or
$$
a=b=c=d.~~~~(case2)
$$
We analyse these two cases separately:
Case 1:
Under this case, we have
$$
a+b+c+d=1.
$$
Since
$$
a^2+b^2+c^2+d^2=1,
$$
the only possibility is one of four elements $a,b,c,d$ equal to $1$ and others are all $0$, which gives $\lambda=-3/2$ and $f=1$.
Case 2:
By the assumption
$$
a^2+b^2+c^2+d^2=1,
$$
it follows
$$
a=b=c=d=\frac{1}{2},
$$
which gives $\lambda=-7/4$ and $f=1$.
Above all we have the maximum of $f$ is $1$ and this proves $(*)$.
Answer: instead of solving this problem let's solve a simpler version of it :
Given a,b>0 and a^2+b^2=1, prove
a+b≥a^3+b^3+ab
you need to use what you have been given :
we know a^2 + b^2 = 1
adding 2ab to both sides of equation we have :
a^2 +b^2 + 2ab = 1 + 2ab
then :
(a+b)^2 = 1 + 2ab (1)
what we need to prove is that
a+b≥a^3+b^3+ab (2)
by adding 3a^2b + 3ab^2 to the both sides of (2) we have :
a + b + 3a^2b + 3ab^2 ≥ a^3 + b^3 + 3a^2b + 3ab^2 + ab (2)
(3ab+1)(a+b) ≥ (a+b)^3 +ab
using (1) we have
(3ab+1)(a+b) ≥ (2ab+1)(a+b) +ab
(ab)(a+b) ≥ ab
a+b ≥ 0
true statement based on assumption
so
a+b≥a^3+b^3+ab
we can use the same procedure to solve the original problem in the case that :
a^2+b^2+c^2+d^2=1   (1)
and then try to turn it to an equation which is simpler and easier to use in
equation below
a+b+c+d≥a^3+b^3+c^3+d^3+ab+ac+ad+bc+bd+cd  (2)
so by adding 2ab +2ac + 2cd + 2ad + 2bc + 2bd we turn (1) into
a^2+b^2+c^2+d^2 + 2ab +2ac + 2cd + 2ad + 2bc + 2bd = 1 + 2ab +2ac + 2cd + 2ad +
2bc + 2bd
(a+b+c+d)^2 = 1 + 2ab +2ac + 2cd + 2ad + 2bc + 2bd (3)
then we use equation (3) to simplify equation (2)
a+b+c+d
+ ab^2 + ac^2 + a*d^2 + 2a^2b +2a^2c + 2acd + 2a^2d + 2abc +
ba^2+bc^2+bd^2 + 2ab^2 +2abc + 2bcd + 2abd + 2b^2c + 2b^2d+
ca^2+cb^2+cd^2 + 2abc +2ac^2 + 2c^2d + 2acd + 2bc^2 + 2bcd+
da^2+db^2+dc^2+ 2abd +2acd + 2cd^2 + 2ad^2 + 2bcd + 2bd^2
≥
a^3+b^3+c^3+d^3+ab+ac+ad+bc+bd+cd +
ab^2 + ac^2 + a*d^2 + 2a^2b +2a^2c + 2acd + 2a^2d + 2abc +
ba^2+bc^2+bd^2 + 2ab^2 +2abc + 2bcd + 2abd + 2b^2c + 2b^2d+
ca^2+cb^2+cd^2 + 2abc +2ac^2 + 2c^2d + 2acd + 2bc^2 + 2bcd+
da^2+db^2+dc^2+ 2abd +2acd + 2cd^2 + 2ad^2 + 2bcd + 2bd^2 =
(a+b+c+d)^3 +ab+ac+ad+bc+bd+cd =
(1 + 2ab +2ac + 2cd + 2ad + 2bc + 2bd ) ( a+b+c+d) +ab+ac+ad+bc+bd+cd =
a + 2a^2b + 2a^2c + 2acd + 2a^2d + 2abc + 2abd +
b + 2ab^2 +2abc + 2bcd + 2abd + 2b^2c + 2b^2d+
c + 2abc +2ac^2 + 2c^2d + 2acd + 2bc^2 + 2bcd+
d + 2abd +2acd + 2cd^2 + 2ad^2 + 2bcd + 2bd^2+
+ab+ac+ad+bc+bd+cd
a+b+c+d

ab^2 + ac^2 + a*d^2 + 2a^2b +2a^2c + 2acd + 2a^2d + 2abc +

ba^2+bc^2+bd^2 + 2ab^2 +2abc + 2bcd + 2abd + 2b^2c + 2b^2d+
ca^2+cb^2+cd^2 + 2abc +2ac^2 + 2c^2d + 2acd + 2bc^2 + 2bcd+
da^2+db^2+dc^2+ 2abd +2acd + 2cd^2 + 2ad^2 + 2bcd + 2bd^2≥
a + 2a^2b + 2a^2c + 2acd + 2a^2d + 2abc + 2abd +
b + 2ab^2 +2abc + 2bcd + 2abd + 2b^2c + 2b^2d+
c + 2abc +2ac^2 + 2c^2d + 2acd + 2bc^2 + 2bcd+
d + 2abd +2acd + 2cd^2 + 2ad^2 + 2bcd + 2bd^2+
+ab+ac+ad+bc+bd+cd
after simplifying we reach to a true statement
Comment: This is an attempt to answer, no?
Comment: Please [see this page](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) for some information on how to format your posts using math tags. Right now your post is a bit hard to read.
Comment: Yes it is. a method has been shown to prove the case with two variables same method works for four variables.


Taxonomy widget - select maximum level depth

Question: I want to make a taxonomy field widget that allows me to select the maximum level depth of the taxonomy vocabulary. This widget should be used in node forms and the value (selected term) should be saved in the node object.
What is the best (Drupal) way to approach this?
I don't want to use hierarchal select.
Comment: Can you explain a bit more what your problem is. Don't you know how to create a widget, or is there something specific in the widget you are creating that is giving you trouble?
Comment: I have a taxonomy vocabulary with 3 levels/depths. In my node form I want to add a widget which allows the user to only select a term our of the first 2 levels of my vocabulary. (so the third level should can't be chosen).
Answer: Content Taxonomy is what you're looking for. It extends the default select list widget and adds a maximum level depth.
Answer: For me not works any module to remove unnecesary taxonomy depths, but I can fix it with my own code like this:
function _remove_sub_services(&$form, &$form_state) {
<code>foreach ($form['profile_fields']['field_select_the_service'][LANGUAGE_NONE]['#options'] as $index => $value){

    if(strstr($value, '--')){
        unset($form['profile_fields']['field_select_the_services'][LANGUAGE_NONE]['#options'][$index]);
    }
}

return $form;
</code>
}
// I call this code inside a hook_form_alter
Answer: There is a new module called Client-side hierarchical (https://www.drupal.org/project/cshs) that does a good UI and solves it.


Probability of not A or not B

Question: Probability of A = $87\%$
Probability of B = $37\%$
Probability of both A and B = $25\%$
I've determined that the probability of A or B = $97\%$,
the probability of not A and not b = $3\%$
I'm not quite sure how to proceed to determine the probably of "not A or not B". I have a feeling it's equal to $1 - P( A \text{ and } B)$ but don't really understand if this is right, and if yes, why?
Comment: De Morgan's law: $A^C \cup B^C = (A \cap B)^C$.
Comment: I Understand De Morgans law, but in stats does simply stating not mean that nota= 1 - (theProbability of A)?

In this case I obtained 75%, but to me' if you don't want A or B to happen then Should it not also be 3% where is this extra 72% coming from?
Comment: Yes, $P(X^C)=1-P(X)$ for every measurable set $X$. So if you put $X=A \cap B$, you get $$P(A^C \cup B^C)=1-P(A \cap B)$$ since by de Morgan's law, $X^C=A^C \cup B^C$.
Comment: In your comment you say "you don't want A or B to happen".  That sounds to me like you are thinking "A doesn't happen" and "B doesn't happen", that is, "not A and not B", which isn't what your question asked.  Perhaps this is causing confusion.
Comment: @David I also think that is what is causing confusion. I don't understand what the difference is.
Answer: This is sort of a reply to the OP's comment, but I believe it addresses the confusion in the question.
IMHO the best way to understand basic logic is to think about common language situations - though always remembering that common language is not always as precise as we need for mathematics.
Suppose you are interested in taking two subjects,say MAT234 and CSC567, but they are scheduled at the same time and you can't do both.  Then you have to skip one or the other.
Now notice that in the previous paragraph we have described the same situation in two ways.  If M means "I will take MAT234" and C means "I will take CSC567", we have

not (M and C)

and

(not M) or (not C)

These mean the same thing, which is one of De Morgan's laws.  Note that it includes the possibility that you change your mind and do neither subject: this works fine with the above formulae since in mathematics we always take "or" to mean the inclusive or, unless clearly specified otherwise.
If you say as in your comment "you don't want M or C to happen", that means you won't take either of the subjects, that is,

not ( M or C )

which is the same as saying you will do neither,

(not M) and (not C)

this is De Morgan's other law.  Note it is not the same as saying you won't take both subjects as we discussed above.

Hope this helps.
Comment: Nice answer, +1.
Comment: @David I think my problem goes deeper then that. I understand De Morgans. What I'm having issue is the difference between not A and not B, and, not A or not B. I'm trying to find a Diagram of it so I can visually Picture it, but I'm not having any luck. Edit: I've been doing my stats work by picturing diagrams in my head, but I can't picture what not a or not b represents. If I look at this diagram, I can't seem to locate not A or not B. Where is it?! I can't seem to locate not (A and B)

https://astarmathsandphysics.com/igcse-maths/the-regions-on-a-two-set-venn-diagram-html-m5bebdd77.gif
Comment: (1) "not A or not B" consists of regions which are outside the A region, or outside the B region, or both, while (2) "not (A and B)" consists of everything except the $A\cap B$ region.  Regions (1) and (2) are the same.

Probability of not A or not B


Android Load Your String Resources Programmatically

Question: How do I Load Your String Resources Programmatically from a Class file and not an Activity:
this is in my Strings.xml

    <string-array name="facts">
        <item>facts 1</item>
        <item>facts 2</item>
...
    </string-array>

Here my Class File
public class FactBook {

    public String[] mFacts;

    mFacts = getResources().getStringArray(R.array.facts);

    public String getFact() {

        String fact = "";

        // Randomly select a fact
        Random randomGenerator = new Random();
        int randomNumber = randomGenerator.nextInt(mFacts.length);

        fact = mFacts[randomNumber];

        return fact;
    }
}

I get a erro. - Invalid Method declaration, return type required.
Comment: `Load Your String Resources Pro-grammatically from a Class file` get call `getResources()` you should need valid current component `Context`. so use `FactBook` class constructor for getting context during object creation and then access String array as `context.getResources().getStringArray(R.array.facts)`
Comment: You can't access `getResources()` from outside. If you want then only using a `Context`.
Answer: You need to create Constructor and pass Context as first argument.
public class FactBook {

public String[] mFacts;

Context context;

public FactBook(Context con){
context=con;
mFacts =con.getResources().getStringArray(R.array.facts);
}

public String getFact() {

    String fact = "";

    // Randomly select a fact
    Random randomGenerator = new Random();
    int randomNumber = randomGenerator.nextInt(mFacts.length);

    fact = mFacts[randomNumber];

    return fact;
 }
}

Now, you called this Facebook class like
FactBook fb=new Facebook(your_Activity.this);
String str=fb.getFact();


Symfony route without controller

Question: I have to work on a Symfony project that I never met before. There is a route that I'd like to figure out what script generates the result. Normally int the routing.yml the the _controller in the defaults tells this, but this route does not have any controller associated with:
vendorname_admin_generate_external_site_admin:
    path: /admin/
    host: "{current}.%vendorname_academic_base_host%"
    defaults: {current: %vendorname_academic_base_subdomain%}

The two parameters are:
vendorname_academic_base_host: vendordomain.com
vendorname_academic_base_subdomain: developmentserver-vpn

Could you help me to understand what does this route definition do?
Comment: I think `current`is your locale ....so host would be `en.vendordomain.com` as an example.
Comment: Did you look at info generated by the profiler?. Maybe it helps.
Answer: Because of the fact it is defining a specific host (ie, a domain name) as part of the route, makes me think that it's just an alias to an external website, that isn't actually in the same codebase.  -- Also the fact its called 'external_site_admin'.
I've just added a similar route with a specific host, mine is still in the same codebase, but under a specific, shorter URL, but I defined my route as a template that I can use to setup as an alias.

Symfony route without controller


Use irreducible fibers to show $X$ is irreducible

Question: Let $\pi:X\rightarrow Y$ be a proper morphism to an irreducible variety and all fibers of $\pi$ are nonempty, irreducible, and of the same dimension.
Show $X$ must also be irreducible.
Thanks (Any hints would work too)
Comment: If you know that $\pi$ is open, then (independent of properness or dimension) this is a fact about topological spaces, proved as tag 004Z in the Stacks project. So, if you were to replace "proper" with "flat," then the result follows (because flat morphisms that are locally of finite presentation are open). I'm not sure how to do without flatness (if you imposed some additional conditions, e.g. $X$ equidimensional and $X$ and $Y$ regular, then flatness would hold). But presumably there is an easier way with the hypotheses you're given.
Comment: I remember having seen this somewhere in EGA with a reference to Bourbaki's Topologie generale. Without properness assumption. But actually it's a good exercise in basic topology.
Comment: Related http://math.stackexchange.com/questions/242360/irreducible-fibers-of-a-closed-subset-implies-irreducibility
Comment: I see the proof for the case where $\pi$ is open. Here we know that $\pi$ is closed, but the analogous proof doesn't seem to work.
Answer: This is exercise 11.4.C of Ravi Vakil's notes. I'll give a sketch of the solution.
First note that since $\pi$ is proper $X$ is finite type over a variety so it has finitely many irreducible components $Z_i$. Furthermore, $\pi$ is closed so $\pi(Z_i)$ is closed in $Y$ for each $i$ and we can conclude that some $\pi(Z_i) = Y$ by the irreducibility of $Y$. Call this component $Z_0$.
Let $X_y$ denote $\pi^{-1}(y)$. $X_y$ is irreducible and $X_y = \bigcup X_y \cap Z_i$ is a union of closed subsets so $X_y = X_y \cap Z_i \subset Z_i$ for some $i$. It then follows that if $x \in Z_i$ but not in $Z_j$ for $j \neq i$, then $X_{\pi(x)} \subset Z_i$.
By applying proposition 11.4.1 in Vakil's notes on the restriction of $\pi$ to $Z_i \to Y$, we see that $\dim X_y \cap Z_i \geq \dim Z_i - \dim \pi(Z_i)$ with equality on some open subset of $\pi(Z_i)$. However, for each $y$ there exists a $k$ such that $X_y \cap Z_k = X_y$ so in that case $\dim X_y = \dim Z_k - \dim \pi(Z_k)$ on some open subset. Since the fibers are equidimensional of dimension $d$, we can then conclude that $\dim Z_k - \dim \pi(Z_k) = d$ for every $k$. In particular, if $X_y$ intersects $Z_k$, then $\dim X_y \cap Z_k \geq d$ by the first inequality but $\dim X_y = d$ by assumption and $X_y \cap Z_k = X_y$. Therefore each connected component $Z_k$ is the union of fibers $X_y$ that intersect it. In particular, $Z_0$ is the union of fibers that intersect it, but every fiber intersects $Z_0$ so $Z_0$ is the union of all the fibers thus $Z_0 = X$ and $X$ is irreducible.
Comment: This is a great answer, but I think there's a slight mistake in the second sentence of the final paragraph. I think it should read "However, for each $k$, given any non-empty open subset of $\pi(Z_i)$, there exists a $y$ such that $X_y\cap Z_k = X_y$, so taking $y$ in the open subset where equality holds, $\rm{dim}X_y = \rm{dim}Z_k - \rm{dim}\pi(Z_k)$." I could be wrong, but I think we're trying to prove a result about an arbitrary component, rather than about an arbitrary point, and this replacement would make that work.
Comment: Hi, I would like to ask why is it that when $X$ is finite type over a variety, it has finitely many irreducible components? Thanks!
Comment: @enoughsaid05 $f : X \to Y$ being finite type over a variety $Y$ means two things: 1) for every affine $Spec B \subset Y$, and every affine $Spec A \subset f^{-1}(Spec B)$ has $A$ a finite type $B$-algebra by the natural map of pulling back (this is the meaning of locally of finite type).  2) $f$ is also quasi-compact: preimages of affines are quasi-compact... Now, Since $B$ is a variety, it is quasi-compact and finite type over a field $k$, hence a Noetherian scheme. As finitely generated rings over Noetherian rings are Noetherian (Hilbert Basis Theorem), each $A$ is Noetherian.
Comment: @enoughsaid05 It follows that $X$ is Noetherian - it is quasi-compact since it can be covered by finitely many of the $Spec A$ of the form 1), using quasi-compactness of the map $f$, plus quasi-compactness of $Y$. Then since affines are quasi-compact, and something which is covered by finitely many quasi-compacts is quasi-compact, the quasi-compactness of $X$ follows. (Noetherian schemes are locally Noetherian and also quasi-compact.)
Comment: @enoughsaid05 Now, it is a fact that Noetherian schemes have only finitely many irreducible components. This may be familiar a commutative algebra fact about the finiteness of primary decomposition of $(0)$ in the Noetherian ring case. This is because a Noetherian topological space (one that satisfies the descending chain condition on closed subsets) has this property, and Noetherian schemes have underlying topological spaces which are Noetherian spaces.
Answer: I just wanted to add that M. Mustaţă proves a slightly more general fact here - without assuming that the morphism is proper, but assuming $X$ is equidimensional, which is often useful: http://www-personal.umich.edu/~mmustata/Note1_09.pdf.


Creating an office network and monitoring all activity without a proxy

Question: We are setting up our office network and would like to track all the websites visited by our employees. However, we would not like to use any proxy based solutions.
Our work is highly dependent on applications in which you cannot configure a proxy. Hence, the approach we would like to follow is setting up a router inside a computer (something like this : http://www.techrepublic.com/article/configure-windows-server-2003-to-act-as-a-router/5844624)
This will also allow us to attach multiple ethernet cards and have redundancy in internet connectivity with complete abstraction from the user about which connection is being used.
But most importantly, since all the traffic will be going through the computer (configured as a router) I assume there will be a way to run packet analysis on all the request / responses being made. For example, list all the FTP servers connected to (port 21), give a graph of all the URLs visited per day by frequency.
Is there already a software which does this ? Or is it possible to build something like this ?
Answer: Use a transparent proxy. Your applications then don't need any configuration change.
Comment: Is there any transparent proxies that impose almost no extra latency. Do you know what's the fastest transparent proxy? Would it be better to split the connection to a listener instead of having a proxy in the middle?
Answer: Why not use a [hardware] firewall? (Or cluster of firewalls for HA/failover.)
Every major firewall I've worked with has the capabilities you're asking about.  Cisco ASAs are solid and standard for this kind of functionality, and Palo Alto Networks make great "next gen" firewalls with more advanced application and url-level filtering and reporting, if that's where your primary concern lies.
Using a computer as a router and trying to hack together some packet-capture to url filter/report sounds like a nightmare that's easily avoided by using the standard tool for this job.
Answer: You could route all your internet traffic through a server running Microsoft Forefront Threat management gateway http://www.microsoft.com/en-us/server-cloud/forefront/threat-management-gateway.aspx. This contains a firewall and anti-malware filtering also so doubles up to protect your network.
It has quite flexible reporting which should help you monitor the activity of web and application traffic but also allow you to block content from sites you don't want your employees visiting.
Comment: I can assure you that TMG is a proxy-based solution that won't work for the OP.
Comment: I thought considering @robert mentioned using a server as a router, TMG would be the natural choice for the application layer to configure access, provide monitoring and reporting?
Comment: Except that it acts as a proxy and is very far from transparent.  The line's also being discontinued, which alone is enough to make it hard to recommend, even without its other problems and assorted pains in the ass.
Answer: This is highly unpractical compared to just setting up a transparent proxy or using your gateway/firewall... You could consider a network tap off your gateway interface. Send a copy of all traffic Flowing though that link to monitoring solution. I know this company has some carrier class stuff to do that. Not sure about smb or mid range. www.netoptics.com/partners/tap/agilent
Also, if this is a small company. Less then 100 users. Take a look at untangle. Just google it. It can function as a pretty decent transparent proxy!

best of luck to you!


drupal 7 add element after the username input text element on login form

Question: I would like to add the domain name of my company in a simple  element right after the username login text input element. Something like this:

I already tried the instructions defined in https://drupal.org/node/350634 and this only affects the text field label or anything around the login form, but not the input fields themselves (unless I'm misunderstanding the directions). This method doesn't seem to affect how I can add an html element after the username text field but before the password text field.
I'm not certain how I should attempt this? Any direction would be wonderful.
BTW - I tried LoginToboggan to simply allow my users to use either their username or their email address, but that solution only partially works. We have LDAP integration, so for the first time the user attempts to log into our Drupal site they must use just their username (without the @companydomain.com) to allow the LDAP authentication to go through. I did not see a way to configure LoginToboggan to force the username through to the LDAP authentication.
Thanks
Answer: You need to add suffix element to username field in login form. You can do it using hook_form_alter(&$form, &$form_state, $form_id)
Implement above hook in your custom module
<code>function YOURMODULENAME_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_login_block' || $form_id == 'user_login') {
    $form['name']['#suffix'] = '@mycompany.com';
  }
}
</code>
Comment: Since I don't have a custom module, can I add the above function in my template.php file for my custom theme? Or should I build a custom module?  Which is the better route?
Comment: hook_form_alter() is one of the hooks that's invoked for both themes and modules so putting it in your template.php file is fine. You can replace YOURMODULENAME with YOURTHEMENAME. You can build a custom module too. For more information https://drupal.org/developing/modules/7
Answer: While Anil Sagar's answer is perfectly correct, sometimes you'll want to use '#field_suffix' instead of '#suffix' (when you add a title as well).


How does one cross-validate a model of binomially distributed data?

Question: I'm ultimately looking to apply cross-validation to a much more complicated scenario, but for now consider the simple task of leave-one-out-cross-validating logistic regression. When you compare the left-out value against its respective model's predicted value, I presume you must convert the predicted value to the probability scale, but then do you also round the predicted value so that its either 0 or 1, or leave it unrounded? Any ideas on which is the better approach (and maybe why)?
Example data and by-hand loocv of a logistic model:
myData = data.frame(
 x = seq(-2,2,length.out = 10)
)
myData$y = rbinom(nrow(myData),1,plogis(myData$x))

myData$preds = NA
for(i in 1:nrow(myData)){
    thisFit = glm(
        data = myData[(1:nrow(myData)!=i),]
        , formula = y~x
        , family = binomial
    )
    myData$preds[i] = predict(thisFit,newdata=myData[(1:nrow(myData)==i),])
}

myData$predsProb = plogis(myData$preds)

#one approach:
myData$squaredError1 = (myData$y - myData$predsProb)^2
SSE1 = sum(myData$squaredError1)

#alternatively:
myData$squaredError2 = (myData$y - round(myData$predsProb))^2
SSE2 = sum(myData$squaredError2)

#which is a "better" estimate of future prediction error, SSE1 or SSE2? Why?

Answer: It would be wise to study proper scoring rules, which will score continuous risk predictions.  Also, make sure you want to do (expensive) leave-out-one cv instead of bootstrap or averaging multiple runs of 10-fold cv.
Take a look at the following functions in the R rms package: lrm, validate.lrm, calibrate.lrm, val.prob (the latter is for external validation but provides a larger set of accuracy scores).


How to beautify the output of phing?

Question: Phing, by default, or even with any of built-in loggers (phing.listener.NoBannerLogger, phing.listener.AnsiColorLogger, phing.listener.XmlLogger and phing.listener.HtmlColorLogger) has quite verbose output.
My use-case is to use Phing for running tests as a pre-commit hook. Therefore I don't care about all that information in log phing may provide me.
I just use it as a multiplatform tool for running tests.
Example:
Buildfile: /private/var/workspace/www/me_com/build.xml

SBKSWWW > main:

   [delete] Deleting /private/var/workspace/www/me_com/temp/pre-commit-hook/changed_files
   [delete] Deleting directory /private/var/workspace/www/me_com/temp/pre-commit-hook
    [mkdir] Created dir: /private/var/workspace/www/me_com/temp/pre-commit-hook
  [phplint] Parse error: parse error in ./www/MyTest.php on line 2
[phpcodesniffer] 2 files where checked
[phpcodesniffer] No syntax errors detected

BUILD FINISHED

Total time: 0.3430 seconds

Many of these lines are really redundant and useless for my use case. I actually even don't run "build" in the original meaning.
What I would love to make phing log to look like is simply sth like this:
 ✔ Commited code matches coding standards
 ✘ Commited code has syntax errors!
   Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE in MyTest.php on line 2

If you think I am using the bad tool for my purpose, tell me that too, I would be happy to know there's something else.
Answer: What you could try is using phing.listener.XmlLogger and piping it through xsltproc with your own stylesheet.
Given a basic build.xml file that just lints your PHP:
<?xml version="1.0" ?>
<project name="Example" basedir=".">

    <target name="lint" description="PHP syntax check">
        <phplint>
            <fileset dir="src">
                <include name="**/*.php"/>
            </fileset>
        </phplint>
    </target>

</project>

Coupled with parse.xsl:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:output method="text"
        omit-xml-declaration="yes"/>

    <xsl:template match="/build">
        <xsl:variable name="newline"><xsl:text>
</xsl:text></xsl:variable>

        <xsl:for-each select="target">
            <xsl:text>Task: </xsl:text>
            <xsl:value-of select="concat(@name, $newline)" />

            <xsl:choose>
                <xsl:when test="task/message[@priority = 'error']">
                    <xsl:value-of select="concat(task/message[@priority = 'error'], $newline)"/>
                </xsl:when>
                <xsl:otherwise>
                    <xsl:text>No errors</xsl:text>
                    <xsl:value-of select="$newline" />
                </xsl:otherwise>
            </xsl:choose>
        </xsl:for-each>
    </xsl:template>

</xsl:stylesheet>

Invoked with phing -logger phing.listener.XmlLogger lint | xsltproc parse.xsl - will give you something clean like:
Task: lint
Fatal error: Only variables can be passed by reference in Request.class.php on line 128

Answer: Since Phing 2.11.0 you would use the phing.listener.SilentLogger
Answer: u have a sytax error on line 2 mytest
it comes basically when inapropriate code is passed or is not properly closed like {}
can you post the line 2 of mytest
Comment: Did you read the whole question? I am not asking about the error, I am asking about the tool. The error is there intentionally.

How to beautify the output of phing?


Canvas remove white Pixels in Images

Question: I have been looking at canvas ImageData remove white pixels to get ride of white pixels in my images but it doesn't work as it doesn't recognise putImageData(). Is there a way to create a method to get rid of white pixels by passing an image in and returning the image back again. I have multiple images already on the canvas but all have white backgrounds.
Comment: OK well you'll have to post the code you're trying to use in order for anyone to help.
Comment: What do you mean, "it doesn't recognise putImageData()"?
Comment: @Pointy It is mentioned at the bottom of the example I linked to but it never works for me
Comment: In what way does it not work? Do you get errors in the developer console?
Comment: @pointy yes states that it is not a function
Comment: Are you getting a warning about a Security Error if you look in the Console?
Answer: Check the following:
1: Is the putImageData definitely being called from ctx?
2: is the first argument in putImageData, "imageData"?
3: This is the most important one. Is the image being called from another domain? If so, you need to download the image to your domain by right clicking the image, clicking "save image as...", and then posting it to your directory. Hope this helps,
Awesomeness01

Canvas remove white Pixels in Images


How to check the first item/content on Drupal View

Question: I'm currently using Drupal Views and I'm trying to figure how to check the first item/content on the view. On a twig template I could write
{% for items in related_content.entity.field_content_items %}

    {% if loop.first %}

    first element

    {% endif %}

{% endfor %}

I tried writing the same condition within the view using {% if loop.first %} but it doesn't work. Is there similar code to achieve this within Drupal Views Custom Text
Answer: Have you tried to print other stuff of the loop variable, maybe {{ loop.index }}, did this work? You then could if-request this. As far as I remember loop.index worked fine in Drupal.
Next thing you can try is to iterate over the keys and if-request the key for your logic. Pretty much the same as loop.index.
{% for key, items in related_content.entity.field_content_items %}
  {% if key == 0 %}

Last resort would be to target related_content.entity.field_content_items[0] directly.
But I think the first two suggestions should give you at least one opportunity to do what you want.

Thanks for the clarification. Views custom text only. OK, in that case consider to use 2 views (or just 2 displays of the same view) as outlined here https://drupal.stackexchange.com/a/104608. Then you'd attach the first view (or display) - which is limited to display only 1 row - before your second view (there must be an attachment option somewhere) and your second view then should be configured to have an offset of 1.
Comment: @clestcruz – Maybe no. But there's the Views attachment before/after thing. And there might be some Views header/footer thing if I remember it right. So, depending on what exactly you want to output there, these might become pretty handy :)
Comment: Just to clarify I'm using Drupal 8 views `custom text`. I believe the looping syntax you have provided is for `twig templates` https://imgur.com/a/JUOIOKB
Comment: @clestcruz – In that case consider to use 2 views  (or just 2 displays of the same view) as outlined here https://drupal.stackexchange.com/a/104608. Then you'd attach the first view (or display) - which is limited to display only 1 row - before your second view (there must be an attachment option somewhere) and you second view then has an offset of 1.
Comment: I see, there is no syntax in detecting the first content/item.