Electron App: Error: %1 is not a valid Win32 application

Question: I am writing code to load c++ dll from electron.I am using NaN and bindings (node-gyp) to achieve this. I am creating a 32 bit dll. Around 2-3 days before I was able to load the dll from electron. Suddenly I am now getting this error:
Error: %1 is not a valid Win32 application.
I did run the following commands but they did not help:
node-gyp clean configure build --verbose --arch=ia32
npm set npm_config_arch ia32
npm install --arch=ia32 electron-prebuilt -g
Reinstalled node and electron as well.
Comment: Try installing and using 32-bit node
Answer: Instead of re-installing node. Here's what I did, it works for me
<code>npm set npm_config_arch ia32
npm clean-install --arch=ia32
</code>
The first command set the node environment to 32bit. The second command re-install all the node packages that are 32bit compatible.
Answer: Doesn't work for me (node v18.14.0)
<code>$ npm set npm_config_arch ia32
npm ERR! `npm_config_arch` is not a valid npm option
</code>


Can wolframAlpha be wrong on this vector limit?

Question: We had a homework on multivariable analysis, and there was this problem and the teacher said that we didnt trust wolfram but I'm not convinced on it, because of this.
Is $f(x,y)=\frac{x^2}{x^2+y^2-x}$, Continuous on (0,0), if not say what kind of discontinuity is it.
Clearly $f(0,0)=\frac{0^2}{0^2+0^2-0}$, its a form of indeterminate. So we go to the limit. $\lim_{(x,y) \to (0,0)} \frac{x^2}{x^2+y^2-x}$
I get $0$, on some few cases, but i cant prove that its $0$, but i "asked" wolfram and he said its $0$, but some other of my class mates say that wolfram gave a non existing limit, or when they refreshed the site, it gave a different answer(which i think its very odd)
Is wolfram possibly wrong, or the limit there is $0$.
I got a little far on proving that the limit does exist but, i could be wrong, because i cant finish it.
Any ideas on that limit?
Comment: Consider the $k$-paths $t\mapsto (kt^2,t)$. Wolfram Alpha is awful for multivariable limits, but when it says the limit doesn't exist, it usually is the case. I at least have never seen it fail in this case. When it says it exists, though, tread carefully.
Comment: what's the value of $f$ on $(0,0)$?
Comment: @GitGud: It fails in both ways. The programmer behind it just dumps in a whole bunch of heuristics which may either give a limit when it does not exist or claim non-existence when it does. See https://i.stack.imgur.com/bxUZ2.png for **JUST ONE** example. After they saw me give this example just last month, they changed the program and now it gives **two contradictory answers**. Any proper mathematician can with some creativity produce a never-ending list of counter-examples that Wolfram Alpha will get wrong!
Comment: @user21820 "Any proper mathematician". Ouch! Thanks, though $\ddot \smile$
Comment: @GitGud: Sorry if it came off the wrong way! I simply meant that it's just a matter of creativity to trick WA, since WA is not doing proper mathematics. =)
Answer: When $x = y^2$, $f(x,y) = 1$, while when $x = 0$, $f(x,y) = 0$. Hence the limit doesn't exist as $(x,y) \rightarrow (0,0)$.
Answer: Computer algebra systems are notoriously bad at not checking essential side-conditions. They can be wrong and often are.
Comment: Indeed, though it's not the computer but the ridiculous programmers who only care about making money from the software. I've observed with my own eyes that they change the WA program whenever I produce some counter-example on Math SE. And see my other comment!
Comment: @user21820: from your comments, I suspect you don't have any experience of working in commercial software development. The **programmers** at Wolfram are clever folk doing what they are paid to do and instructed to do by their managers.
Comment: Programmers being clever does not imply my statement is false. There are indeed many **clever** programmers who only care about making **money** and hence will do **whatever** their boss says without any regard to **correctness**. I have inside information from a very large worldwide established software company. Of course, they don't take **all** the blame; their managers take more. But that doesn't absolve them. If you don't already know, 99.99% of professional programmers can't do basic mathematics correctly even if their life depended on it; they still make money alright.


Desabilitar as datas anteriores datapicker com bootstrap

Question: Colegas.
Através do site, implementei o datapicker no meu sistema, porém gostaria de desabilitar as datas anteriores da data atual. Pelo modelo deles, apresenta a seguinte forma:
<code>$('#sandbox-container input').datepicker({
    autoclose: true,
    datesDisabled: ['02/06/2016']
});
</code>
Notem que desabilitar apenas a data 02/06/2016. Como eu faria para desabilitar as datas anteriores antes da data atual?
Answer: Tente isso:
<code>$('#sandbox-container input').datepicker({ minDate: 0});
</code>
Veja funcionando aqui: http://jsfiddle.net/191c5apr/1/
Comment: @Jose.Marcos verdade, também é possível...
Comment: Certo... podemos usar também o startDate: "date", mas mesmo assim obrigado pela sua ajuda Berriel


When does a distribution not have a mean or a variance?

Question: I believe I read today a phrase which went something like this:

If a distribution has a mean and a variance ...

So I guess that means some distributions do not have means or variances?
I fiend that a bit difficult to understand - for example:
I could get data which is said to follow such a mean-less and variance-less distribution and as an estimation compute the mean and variance of such a data set.
could someone help shed some light on what I am missing?
Comment: The mean and/or variance don't exist when the limits implied by the improper integrals don't exist; e.g. for the mean, $\lim_{a,b\rightarrow\infty}\int_{-a}^b x\, dF$ has to exist for the mean to exist (for a continuous density $dF = f(x)dx$). For a non-Cauchy example, consider the discrete distribution $P(X=x)= \frac{6}{\pi^2x^2};\,x=1,2,3,...$, a particular case of the zeta distribution; in this case neither variance nor mean exist (it's the case that if the mean doesn't exist, the variance won't either, but the mean can exist when the variance doesn't).
Comment: The [Cauchy distribution](http://en.wikipedia.org/wiki/Cauchy_distribution) is a famous distribution that has neither a mean nor a variance (no finite moments in general). [This post](http://stats.stackexchange.com/questions/36027/why-does-the-cauchy-distribution-have-no-mean) explains very nicely why not. You can, of course compute the *sample* mean and variance.
Comment: The wiki article **http://en.wikipedia.org/wiki/Cauchy_distribution#Estimation_of_parameters** explains well _what_ are you estimating by calculating the sample mean, and how "good" is this estimation.
Comment: See this [related question](http://stats.stackexchange.com/questions/91512/how-can-a-distribution-have-infinite-mean-and-variance). The *sample* mean and variance will always exist (the sample consists of a finite collection of numbers, for which the sample quantities will be well-defined), it's the things that they estimate that are not finite (either infinite or undefined), and as such the sample estimates can't really convey useful information about the population.
Comment: I just read the post - fascinating, fascinating
Answer: The canonical example of a distribution with no mean (and hence no variance) is the Cauchy distribution.
True, you could compute the sample mean for a sample of data from a Cauchy distribution, but you would have to interpret such a sample mean carefully; increasing the sample size would not correspond to getting a better estimate of the TRUE mean, because there is no true (i.e., large sample) mean.


Does there exist an $a_0$ such that the sequence $a_{n+1} = 2a_n + 1$ is prime for all $n \ge 0$?

Question: I believe I see that $a_n = 2^n(a_0+1) - 1$ but am somewhat uncertain where to proceed afterwards. I am a complete beginner at number theory and would appreciate it if someone could point me in the right direction--surely there is some obvious argument I am missing.
Comment: See [here](https://math.stackexchange.com/a/66258/242) for a *proof* of a more general result (replace $10x+1$ by $2x+1$)
Answer: No.
General term in your sequence is $a_n = 2^n(a+1) - 1$, where, by assumption, $a$ is prime.
There is some sufficiently large $n$ such that $2^n \equiv 1 \pmod{a}$, or in other words $2^n = k a + 1$. But then $a_n$ is divisible by $a$, hence not prime.
EDIT: As Ben Frankel rightly notes, there is a special case when $a = 2$. Argument above fails, but $a_5 = 95$ is composite, so we are in good shape regardless.
Even more general statement is true: If $p$ is a prime, $p \neq 2$, and $p$ divides one of $a_n$, then $p$ divides infinitely many $a_n$'s. In particular, if $a_n$ is an odd prime, then $a_n \mid a_m$ for infinitely many $m$, and these $a_m$'s are composite.
Comment: Unless $a = 2$, but then $a_5 = 95$ which is composite.
Comment: Thank you very much -- I understand now.
Answer: This is equivalent to find an integer $k.2^{n_0}$ such that $k$ is odd and $p_n=k.2^{n+n_0}-1$ is a prime for all $n\ge 0.$
If $k=1,$ then $p_n$ is not a prime for composite $n+n_0,$ As

If $k=2m+1$ where $m\ge1,$ then we can find a large $n$ such that
$p_n=k(2^{n+n_0}-1)+(k-1)$ is not a prime.
Answer: By assumption $a_0=p$ is a prime and $a_n = 2^n(p+1)-1$.
If $p$ is an odd prime, then by Fermat's little theorem we have $2^{p-1} \equiv 1 \bmod p$, so $a_{p-1} \equiv 0 \pmod {p}$ and $a_{p-1}$ is composite (notice $a_{p-1}>p$).
Remaining case $p=2$ can be seen by simply enumerating first few values which yields $a_5=95$, a composite number.


Resultado do sql no spring boot

Question: Boa tarde,
Preciso de uma ajuda para fazer um endpoint no Spring Boot, no banco de dados (MySQL), eu tenho a seguinte query:
SELECT U.NOME, P.DESCRICAO FROM USUARIO_PERMISSAO UP
    JOIN USUARIO U ON UP.ID_USUARIO = U.ID
    JOIN PERMISSAO P ON UP.ID_PERMISSAO = P.ID

A tabela Usuario_Permissão, ela é criada pelo banco, ManyToMany da tabela usuário e permissão, gostaria de saber como faço um endpoint que posso trazer o resultado.
Como não tenho essa "model", não estou conseguindo fazer o retorno do repository.
Estou tentando fazer assim:
@Query(nativeQuery = true, value = "SELECT U.NOME, P.DESCRICAO FROM USUARIO_PERMISSAO UP JOIN USUARIO U ON UP.ID_USUARIO = U.ID JOIN PERMISSAO P ON UP.ID_PERMISSAO = P.ID")
Object findByUsuarioPermissao();

@GetMapping
public Object findUsuarioPermissao() {
    return usuarioRepository.findByUsuarioPermissao();
}

Porém na hora de testar está aparecendo esse erro:
"message": "query did not return a unique result: 20; nested exception is javax.persistence.NonUniqueResultException: query did not return a unique result: 20"

Comment: faz um favor pra gente? edita a pergunta e insere esses código ai de cima. Valeu.
Comment: Olá, o que já tentou fazer em termos de código?
Comment: De acordo com o erro essa query está retornando uma lista, tem duas maneiras de resolver, fazendo o retorno ser uma List ou colocar um LIMIT 1 na query sql. PS recormendo fazer a entity dessa tabela, fica bem mais facil trabalhar, nao sei se o Object vai funcionar pois n é serializable.
Answer: O erro é porque o método findByUsuarioPermissao espera o retorno de um objeto apenas e sua consulta está retornando mais de um objeto.
O ideal seria mudar para List<Object> ou limitar sua query para trazer apenas um resultado.

Resultado do sql no spring boot


Server is too optimized?

Question: I have a linux 4gb Quad core server w/ apache that is used for this website. I notice when I go to SSH and type TOP to see load averages, they are usually around 0.80.
Now from what I understand, if you have a quad core, your load average is usually around 4.0
Does this mean that my server is too optimized? That maybe it is bottle-necking potential traffic ?
Comment: I think you misunderstand. There would be no reason for the load to be 4.0 just because you have a quad core processor. The load average is just the measure of processes waiting in the run queue. Are you seeing errors of some kind?
Answer: "if you have a quad core, your load average is usually around 4.0"
Incorrect, load averages is how long it takes each process to get a slot at the CPU (It's a bit more complicated than that, it actually involves the CPU 'queue' but saying time is a lot easier than trying to explain that). As a highly simplistic example, when running Apache, the load average is the approximate time each request has to wait before being seen too.
A server can never be too optimized, if Apache was causing a bottle-neck most likely the load average would be a lot higher.
We have a 32 core server running LAMP stack, if the load average is above about 3 we start to see a noticeable performance decrease.
Answer: You can't have a server which is "too optimized".  With load average of 0.8, it means some of your server is idle.
For a quad core your load isn't "usually around 4.0".  However with a quad core, you usually don't have to worry about performance if your load is under 4.

Server is too optimized?


Como retirar o estilo quando o checkbox é desmarcado em AngularJS?

Question: Preciso mudar a cor de fundo da página quando marco o checkbox e voltar a cor original quando desmarco, consegui apenas o 1º passo e não consigo voltar a cor original, alguém ajude.

<input type="checkbox" ng-checked='fundo={"background-color":"#333", color:"white"}'>Fundo escuro
Answer: Tente isso:

var app = angular.module("testApp", []);
app.controller('testCtrl', function($scope){
   $scope.inventory = {productName:false};
})
.checked{
    background-color:grey;
  }

.unchecked{
   background-color:white;
  }

   <input type="checkbox"  class="checkbox" ng-model="inventory.productName"  />Fundo escuro

Comment: não funcionou o codigo
Comment: no compilador da Stack esta funcionando, clica no botão "Executar"


Index arithmetic for $9x^8 \equiv b \pmod{17}$

Question: I wish to find all b such that $9x^8 \equiv b \pmod{17}$ has a solution using index arithmetic. I have figured out that 3 is a primitive root, giving:
$$\text{ind}_39+8\text{ind}_3x \equiv 2+8\text{ind}_3x \equiv \text{ind}_3b \pmod{16}$$
But, where can I go from here? A hint would be appreciated.
Comment: $$x^8\in\{-1,0,1\}\pmod{17},$$ can you guess why?
Comment: AH! Yes. Thank you. That clears it right up. Does anyone know of a way to salvage my approach, though?
Comment: No, can you explain further?
Comment: https://en.wikipedia.org/wiki/Fermat%27s_little_theorem
Comment: @zz20s: for any odd prime $p$ (and $17$ is an odd prime) $$\left(\frac{a}{p}\right)\equiv a^{\frac{p-1}{2}}\pmod{p}$$ is the Legendre symbol, which equals zero if $a$ is a multiple of $p$ and $\pm 1$ otherwise, according to $a$ being a quadratic residue $\!\pmod{p}$ or not. In particular the given problem has a solution iff $b\in\{0,8,9\}\pmod{17}$.
Comment: What is $\text{ind}_3$ mean?  Is that like a logarithm?
Comment: Yes, that is my professors notation for the discrete logarithm: http://mathworld.wolfram.com/DiscreteLogarithm.html
Answer: Clearly, if $17|b,17\mid x$
otherwise,
$$\text{ind}_3b-2\equiv8\text{ind}_3x \pmod{16}\begin{cases}0 &\mbox{if } \text{ind}_3x \text{ is even}\iff b\equiv3^2\pmod{17} \\8& \mbox{if }\text{ind}_3x \text{ is odd}\iff b\equiv3^{8+2}\end{cases}$$
Comment: See also: https://math.stackexchange.com/questions/2571015/solving-a-congruence-using-primitive-roots


Can't get PHP to stop showing errors

Question: Contrary to most people's problem I cannot get PHP to stop showing errors, I have in my php.ini display_errors set to off but it still shows them, I have also tried .htaccess, and inline ini_set and error_reporting variables but the errors still show.
What can I do to prevent this overide?
Mac OS X Lion Server 10.7.1
MAMP Compiled using instructions from DIY Mac Server (diymacserver.com)
UPDATE:
This is where my php.ini file is stored...

This is the value of my display_errors setting at run time

And this is the copy and paste value written in /etc/php.ini
display_errors = Off

Comment: Have you checked `phpinfo()` to make sure you're using the same php.ini that PHP is using (also, whether it says its on or off)?
Comment: I had not but I have now and it was correct, I changed short tags to on in there and that worked so it's working and reading the file, but its not adhering to the settings for error reporting.
Comment: I have added some more detail about my configuration
Comment: I have managed to figure out that its happening because my php.ini isn't being read although its in place, can anyone suggest what permissions would be correct for a Apache 2 install running as _www in the group _www (mac os x)
Answer: make sure your editing the right php.ini file as there are two ini files, one for apache and one for CLI.
Comment: Yes I am editing the right file, as I managed to enable short tags successfully.
Answer: I came across similar behaviour recently and found out that the php.ini layout is quite confusing: listing of the default values etc. is at the top of the file while description of the setting and the setting itself are way further down. (see php 7 ignores ini files, but claims to load).

It could well be that a later setting overrides yours. Browse or search the ini file for all occurences of "display_errors": grep -n display_errors/etc/php.ini
What is the value of "Loaded Configuration File "?
Answer: The display_errors directive can be altered at runtime with the ini_set function. Make sure that none of the code is turning error display back on.
Also, when you update php.ini settings, make sure to restart Apache.
Comment: Indeed it can and I have tried that but it still shows errors...
Answer: Do you have an auto_append_file= setting that is causing php to include code on every page that uses ini_set() to turn the display back on?
Comment: It is set to blank
Answer: It is worth bearing in mind that even if you don't display or log errors, they still have a big impact on throughput and performance.
The 3 most obvious causes are:
1) you are changing the wrong php.ini file (which you've already addressed).
2) the php.ini setting is over-ridden somewhere else - if this is mod_php then that could be in the httpd.conf files or .htaccess
3) you didn't restart the PHP process (httpd when we're talking about mod_php) after making the changes

Can't get PHP to stop showing errors


Intuitive "proof" of the Euler theorem

Question:
Let $a$ and $n$ be coprime. Then $$a^{\varphi(n)} \equiv 1 \mod n$$

Can you think of an easy, possibly visual, way to justify this theorem without delving into the group theory? In other words, if you were to explain the gist of this theorem to your 12-year-old sibling, how would you do it?
Comment: $x \mapsto ax$ is a bijection on coprimes $\bmod n$ - I would focus on that. This gets understood by "anyone" who just started studying this bit of ENT, and I don't see a way to put things simpler...
Comment: It happens that I have a 12-year-old daughter. But I think that it will be a waste of time to try to explain her why this is true.
Comment: I think that **anyone really needing**, or being interested, in knowing "the gist of that theorem" would need to learn first the very small amount of group theory needed to understand it...Sometimes things cannot be dumbbed down that much.
Comment: I'd do it using reduced residue classes (see https://math.stackexchange.com/questions/50542/proof-of-eulers-theorem-without-abstract-algebra) though it would require some further explanation on your part. Perhaps someone else would know how to adjust this to a 12 year olds level.
Comment: In any case one has to introduce some elementary number theory. And this is already the way to abstract algebra. So why not start this way. If you are twelve, then you will also (usually) not be interested in arithmetic functions like $\phi(n)$. So I don't see too much sense in explaining this without any abstract algebra.
Answer: The easiest proof relies on $x \mapsto ax$ being a permutation of $U(n)$. That's the proof in Wikipedia.
This proof does not depend on Lagrange's theorem of group theory. It actually provides a simple proof of Lagrange's theorem for all finite abelian groups. Whether this proof can be explained to a child, I don't know.
Comment: See also https://math.stackexchange.com/questions/50542/proof-of-eulers-theorem-without-abstract-algebra.
Comment: That $x\mapsto ax$ is a permutation could definitely be explained to a 12 year old, but would you mind expanding your answer or give a reference?
Answer: For 12 year olds rigorous deductive proofs are difficult I would go inductive. Start with a =2 and n as any prime. Most 12 year old should be able to figure this out .then generalize it to square free composite numbers as n. Then you can extend it to all odd numbers and proceed step by step . Will take some time but nothing difficult.

Intuitive "proof" of the Euler theorem


MaltParser cannot find configuration file if it is not in current directory

Question: I have trained a model using maltparser version 1.8.1, and I can parse text just fine, but I tried to do it from a non-local directory,
java -Xmx6G -jar /Users/me/maltparser-1.8.1/maltparser-1.8.1.jar -c /Users/me/maltparser-1.8.1/configFile -m parse

and I get the following error:
Couldn't find the MaltParser configuration file: /Users/me/maltparser-1.8.1/configFile.mco
However, the file definitely exists. I copied the text from the error:
$ ls /Users/me/maltparser-1.8.1/configFile.mco
/Users/me/maltparser-1.8.1/configFile.mco

The only way that I can get it to work is if I run java in the directory where the configuration file is. Is there something special that I have to do to use a full path for the configuration file?
It would be possible, I suppose, to cd in a shell script to make this work, but I still want to understand why doing it this way doesn't work.
Answer: I was facing the same problem, but then I looked into the source code and found out that you need to provide the relative path of the configuration file from the place you are executing the java command. This is because the path where you have executed the program is prepended to the path of the config file you provide as argument, unless you have mentioned the working directory as argument(in this case put the config in the working directory).


Evaluating the surface integral $\iint_S {({x^2} + {y^2})} \,dS$ using spherical coordinates

Question: For the integral $$\iint\limits_S {({x^2} + {y^2})} \,dS\quad,\,S:{x^2} + {y^2} + {z^2} = 2z$$The
correct answer is $${{8\pi } \over 3}$$ I used Spherical coordinate system, it turns to $$\int_0^{2\pi } {d\theta \int_0^{{\pi  \over 2}} {({r^2}{{\sin }^2}\varphi } )({r^2}\sin \varphi )\,d\varphi } ,r = 2\cos \varphi $$Then use $r = 2\cos \varphi$, it turns to $$32\pi \int_0^{{\pi  \over 2}} {{{\sin }^3}\varphi {{\cos }^4}\varphi \,d\varphi }  = {{64} \over {35}}\pi $$Doesn't match the answer, I wonder where am I wrong.
Comment: Toby Mak,yes so$${x^2} + {y^2} = {r^2}{\sin ^2}\varphi $$
Comment: The correct substitutions are $x = r \sin \phi \cos \theta, y = r \sin \phi \sin \theta$.
Answer: The mistake in your approach is that you just substituted $r=2\cos\phi$ into the usual formula with $dS = r^2\sin\phi\,d\phi\,d\theta$. This formula is only valid when $r$ is a constant.
In particular, if you do the standard algorithm of parametrizing the surface and computing the fundamental vector cross product, you find that $$\vec g(\phi,\theta) = \big(2\cos\phi\sin\phi\cos\theta,2\cos\phi\sin\phi\sin\theta,2\cos^2\phi\big).$$
Then $$\left\|\frac{\partial\vec g}{\partial\phi}\times\frac{\partial\vec g}{\partial\theta}\right\| = 4\sin\phi\cos\phi.$$
Now you can proceed.
Comment: It's usual spherical coordinates with $\rho=2\cos\phi$.
Answer: A fast track: We have $S= \{ (x,y,z): x^2+y^2+(z-1)^2=1\}$, a sphere of radius 1 centered at $(0,0,1)$. By spherical symmetry:
$$ \int_S x^2 \, dS= \int_S y^2 \, dS= \int_S (z-1)^2 \, dS= \frac{1}{3}\int_S 1 \, dS =\frac{4\pi}{3}$$
The result follows.
Answer: The surface $S$ is a sphere of radius $1$ centered at $(0,0,1)$, which can be determined by completing the square:
$$x^2+y^2+z^2=2z\implies x^2+y^2+(z-1)^2=1$$
Parameterize the surface in spherical coordinates, translating the $z$ coordinate accordingly:
$$\mathbf s(\theta,\phi)=\cos\theta\sin\phi\,\mathbf i+\sin\theta\sin\phi\,\mathbf j+(\cos\phi+1)\,\mathbf k$$
The surface element is
$$\mathrm dS=\left\|\frac{\partial\mathbf s}{\partial\theta}\times\frac{\partial\mathbf s}{\partial\phi}\right\|\,\mathrm d\theta\,\mathrm d\phi=\sin\phi\,\mathrm d\theta\,\mathrm d\phi$$
so the integral indeed has a value of
$$\iint_S(x^2+y^2)\,\mathrm dS=\int_0^{2\pi}\int_0^\pi\sin^3\phi\,\mathrm d\phi\,\mathrm d\theta=\boxed{\frac{8\pi}3}$$

Alternatively,
$$\iint_S(x^2+y^2)\,\mathrm dS=\iint_D(x^2+y^2)\sqrt{\left(\frac{\partial f}{\partial x}\right)^2+\left(\frac{\partial f}{\partial y}\right)^2+1}\,\mathrm dx\,\mathrm dy$$
where $f(x,y)=z=1\pm\sqrt{1-x^2-y^2}$ (corresponding the top and bottom halves of the sphere) and $D$ is the disk in the plane $z=1$ centered at $(0,0,1)$ given by
$$D=\{(r,\theta)\mid0\le r\le1\land0\le\theta\le2\pi\}$$
For either hemisphere, we have
$$\sqrt{\left(\frac{\partial f}{\partial x}\right)^2+\left(\frac{\partial f}{\partial y}\right)^2+1}=\frac1{\sqrt{1-x^2-y^2}}$$
So the integral over either hemisphere in polar coordinates is
$$\iint_D\frac{x^2+y^2}{\sqrt{1-x^2-y^2}}\,\mathrm dx\,\mathrm dy=\int_0^{2\pi}\int_0^1\frac{r^3}{\sqrt{1-r^2}}\,\mathrm dr\,\mathrm d\theta=\frac{4\pi}3$$
which gets doubled to account for the other hemisphere to again yield $\boxed{\frac{8\pi}3}$.
Answer: As an extra, there is a way of computing this integral without ever integrating by using spherical coordinates, which all hinges on symmetry. Notice that the sphere could also be written as
$$x^2+y^2+(z-1)^2=1$$
Since the integrand doesn't depend on the location in $z$ at all, we could safely translate the sphere down and be assured that
$$\iint\limits_{x^2+y^2+(z-1)^2=1}x^2+y^2\:dS = \iint\limits_{x^2+y^2+z^2=1}x^2+y^2\:dS$$
holds. Second, notice that by rotational symmetry (or just pairwise swapping the variables AKA reflectional symmetry) on the second surface we have that
$$\iint\limits_{x^2+y^2+z^2=1}x^2\:dS = \iint\limits_{x^2+y^2+z^2=1}y^2\:dS = \iint\limits_{x^2+y^2+z^2=1}z^2\:dS \equiv I$$
which is a quantity we will denote by $I$. Then the beauty of being on a sphere tells us that
$$3I = \iint\limits_{x^2+y^2+z^2=1}x^2+y^2+z^2\:dS = \iint\limits_{x^2+y^2+z^2=1}1\:dS = 4\pi$$
Thus the answer to the problem is $2I$, or
$$\frac{8\pi}{3}$$
Answer: $x^2+y^2+z^2=2z$ in spherical coordinates is $\rho=2\cos\phi$. It has the parametrization
$\vec r=\langle\cos\theta\sin2\phi,\sin\theta\sin2\phi,2\cos^2\phi\rangle$ and the area differential element
$dS=||\vec r_\theta\times \vec r_\phi||d\theta d\phi=2\sin2\phi d\phi d\theta.$ Hence
$$\int\int_S(x^2+y^2)dS=\int_0^{2\pi}\int_0^{\frac\pi 2}(\sin^22\phi)(2\sin 2\phi)d\phi d\theta=4\pi\int_0^{\frac\pi 2}\sin^32\phi d\phi=\frac{8\pi}3$$


How can I prove that (p→q)∧(p→r) ⇔ p→(q∧r)

Question: How can I prove that (p→q)∧(p→r) compound statements and
compound statement p→(q∧r) are logically equivalent?
And can I use logical equivalences on this proof?
Comment: Via a table of logic?
Answer: $$(p\implies q) \land (p\implies r)$$
is equivalent to
$$( q \lor \lnot p) \land ( r \lor \lnot p)$$
is equivalent to
$$(q \land r) \lor \lnot p$$
is equivalent to
$$p \implies (q\land r)$$
Comment: @Elementary:  you can learn MathJax [here](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference)
Answer: $(p→q)∧(p→r) $ is the same as
$(\overline{p} \vee q)\wedge   (\overline{p} \vee r)$ which is the same as
$(\overline{p}\vee(\overline{p}\wedge r)\vee(q\wedge\overline{p})\vee(q\wedge r))$
From here, it is clear that if both $\overline{p}$ and  $(q\wedge r)$ is false, the complete statement is false. If either is true, then the full statement is true.  And so the full statement is the same as the statement $p→(q∧r)$ because  $p→(q∧r)$ is the same as $\overline{p} \vee (q\wedge r)$.
Answer: The other answers showed how to use logical equivalences to prove the result. Here is a proof using natural deduction in a Fitch-style proof checker.

The inference rules are listed on the proof checker's page.
They are

conjunction introduction ($\land$I),
conjunction elimination ($\land$E),
implication introduction or conditional proof ($\to$I),
implication elimination or modus ponens ($\to$E) and
biconditional introduction ($\leftrightarrow$I).

Kevin Klement's JavaScript/PHP Fitch-style natural deduction proof editor and checker http://proofs.openlogicproject.org/


How should I deal with enharmonics on the Chromatic Harmonica?

Question: I have sheet music for a song that is in the key of Eb Major; three flats. To play these notes on a chromatic harmonica I have to transpose those three flats ( E, B and A) to sharps (D,A & G), I think. If this is true what happens to the key of the piece, is it just in the key of C major now? The harp is in the key of C, orchestra tuned.
Thanks!
Comment: @BenHughes - On a modern chromatic in the key of C, there are no 'literal' flats. Without using the slide you have all the notes of the C major scale. Using the slide, every note is raised by half a step, effectively giving you the key of C#. So - when you go to play Eb, you actually have play to the D hole and hit the slide to make it D#, the enharmonic equivalent of Eb.
Comment: I don't understand? Why would you have to transpose 3 flats to sharps? And 3 sharps is not D, A and G? It's F, C and G. Are you just trying to transpose a piece in Eb into C?
Comment: Hi Ben, thanks for responding. On a diatonic harmonica notes can easily be bent down to flats; not so on my harp so my thought is to play those flats I have to sharp the preceding note. First, is that correct? Maybe I am making more of this than I have to; maybe I do want to just transpose it to C. Confused.
Comment: FYI - _Orchestra Tuning_ on chrom generally means the first hole is G below C : you get half an octave below the lowest C so you can play bass notes against the higher octaves. That's the standard layout on 14 hole chrom, or a 12 hole _Orchestra Tuned_  chrom. On a 12 hole, they eliminate the high end of last octave, which is little used, to give the ability to play those bass notes.
Answer: It's pretty straightforward. On chromatic harmonicas, the notes are sharpened when the button is pressed in. So, on a C harmonica, all notes are diatonic C, and no flats per se are capable of being played.
So, to make Bb, Eb and Ab, they need to be seen and played with the button in, as A#, D# and G# respectively.Thus, keeping the piece in Eb, all the 'accidentals' are played in this way. Unless transposition is the name of the game, in which case, play it all in C, which may not be possible, as other accidentals may occur.
Answer is if you change those 3 notes, to b OR #, it will be played in Eb, effectively.
Answer: Don't worry about the mechanics of the instrument, that's the player's business.   Write the music correctly.  He'll take care of playing it.
Comment: I didn't realize at first that the question was about writing the music, but playing it. But from the language of the question, sounds like you're probably correct. I adjusted my answer because of yours.
Answer: I have to transpose those three flats ( E, B and A) to sharps (D,A & G), I think.
No, you don't have to transpose anything:
Depending on whether you're in a flat or a sharp key, the notes should be referred to in terms of their appropriate enharmonics.
In your case, although most chromatic layout charts say that when the slide is pushed on a D hole, the resulting note is D#, that's correct when in the key of E Major, for example.
But if you're in Eb, there is usually no reason to think of it as D# - in the key of Eb that note is Eb, not D#. That is how a player should think of it and that is how it should be written.
The slide notes should be considered like the black keys of the piano - their names change depending on the key. In E Major, the black key following D is D#, but in the key of Eb it's Eb.
Nothing has to be transposed at all, because the 'virtual' instrument layout changes based on the key being played.
Here is an arrangement of the tune My Funny Valentine for Chromatic Harmonica. As we can see, it is written in Eb, with no transposition for the chromatic: Eb is notated as Eb, etc:
It is found in this book:

(At first I thought the question was about playing the song yourself, but perhaps you just mean writing a the music for the chromatic, in which case the following is not relevant to you as a composer, but to a musician playing the chromatic)
Practice your scales, going through the Circle of Fifths, and focus on spelling each scale correctly using the appropriate enharmonics. After a while it will become natural to name the slide notes based on the key you are playing in.


Overfitting in polynomial regression and other concerns

Question: Given a set of data and training points, suppose we obtain a polynomial regression of the form
$$f(x) = w_0 + w_1 x + \ldots w_n x^n$$

Is there a rule of thumb as to what order of the polynomial is it
more likely to overfit? For example, can we say that as the order of the polynomial grow, the likelihood of overfitting increases?
Also, is it common to observe explosive behavior for higher order
polynomials? For example, your data is concentrated between range
$[-5, +5]$. Could the polynomial regression explode to the range of
say $[-1000, 1000]$ due to the higher order terms $x^n$, the weights,
and possibly the outliers in the training data?
Comment: If I may: whenever you can, please look at a plot of the data along with your fitted model. "Good" statistical measures do not preclude nonsensical results, cf. Anscombe's quartet.
Comment: Even the saturated model may be an underfit of the true process if there is not enough data.
Answer:
There is no such rule about specific order polynomials which is agnostic to your dataset. If any such rule existed, I would expect it to be a function of your data or your data generating process - without knowing something about that, it's hard to say. Without saying anything about specific order polynomials, your general statement is right - larger order polynomials are more likely to overfit. As the order of the polynomial increases, so does the variance of the estimator.
Yes, this is a common issue with higher order polynomials. It is similar in spirit to Runge's phenomenon. The common solutions are to find the best order via cross-validation (grid search), or by controlling the size of the coefficients with regularization.


Finding out version, and updating to latest stable core version

Question: I have inherited a site that uses Drupal, but I've not had any experience with it before. I'm trying to move it over to a server that has PHP 7 on, but I get all kinds of errors:

warning: Declaration of
  cck_facet::build_root_categories_query(&$query) should be compatible
  with faceted_search_facet::build_root_categories_query() in
  /home/user/web/foo.org/public_html/sites/all/modules/cck_facets/cck_facets.inc
  on line 16. warning: Declaration of
  author_facet::build_root_categories_query(&$query) should be
  compatible with faceted_search_facet::build_root_categories_query() in
  /home/user/web/foo.org/public_html/sites/all/modules/faceted_search/author_facet.module
  on line 0. warning: Declaration of
  content_type_facet::build_root_categories_query(&$query) should be
  compatible with faceted_search_facet::build_root_categories_query() in
  /home/user/web/foo.org/public_html/sites/all/modules/faceted_search/content_type_facet.module
  on line 0. warning: Declaration of
  date_authored_facet::build_root_categories_query(&$query) should be
  compatible with faceted_search_facet::build_root_categories_query() in
  /home/user/web/foo.org/public_html/sites/all/modules/faceted_search/date_authored_facet.module
  on line 0. warning: Declaration of
  taxonomy_facet::build_root_categories_query(&$query) should be
  compatible with faceted_search_facet::build_root_categories_query() in
  /home/user/web/foo.org/public_html/sites/all/modules/faceted_search/taxonomy_facets.module
  on line 0. warning: Creating default object from empty value in
  /home/user/web/foo.org/public_html/sites/all/modules/panels/panels.module
  on line 1093. user warning: You have an error in your SQL syntax;
  check the manual that corresponds to your MySQL server version for the
  right syntax to use near 'IN ('hebergement')) AND (.status = '1') AND
  (node_data_field_photographie.field_' at line 1 query: SELECT
  DISTINCT(node.nid), changed FROM node node LEFT JOIN
  content_field_photographie node_data_field_photographie ON node.vid =
  node_data_field_photographie.vid INNER JOIN node_access na ON na.nid =
  node.nid WHERE (na.grant_view >= 1 AND ((na.gid = 0 AND na.realm =
  'all') OR (na.gid = 0 AND na.realm = 'og_public'))) AND ( (.type IN
  ('hebergement')) AND (.status = '1') AND
  (node_data_field_photographie.field_photographie_fid > 0) AND ((.uid
  NOT IN ('1','45','42') OR .uid IS NULL)) ) ORDER BY DESC LIMIT 0, 12
  in /home/user/web/foo.org/public_html/includes/database.mysqli.inc on
  line 154. user warning: You have an error in your SQL syntax; check
  the manual that corresponds to your MySQL server version for the right
  syntax to use near 'IN ('promotion')) AND (.status = '1') AND
  (DATE_FORMAT(STR_TO_DATE(node_data_fie' at line 1 query: SELECT
  DISTINCT(node.nid),
  node_data_field_date_de_dbut.field_date_de_dbut_value AS
  node_data_field_date_de_dbut_field_date_de_dbut_value, node.title AS
  node_title, node_data_field_date_de_dbut.field_date_de_dbut_value2 AS
  node_data_field_date_de_dbut_field_date_de_dbut_value2, v9node.nid AS
  v9node_nid, v9node.title AS v9node_title FROM node node LEFT JOIN
  content_field_date_de_dbut node_data_field_date_de_dbut ON node.vid =
  node_data_field_date_de_dbut.vid INNER JOIN nodefamily
  nodefamily_child ON node.nid = nodefamily_child.child_nid LEFT JOIN
  node v9node ON nodefamily_child.parent_nid = v9node.nid INNER JOIN
  node_access na ON na.nid = node.nid WHERE (na.grant_view >= 1 AND
  ((na.gid = 0 AND na.realm = 'all') OR (na.gid = 0 AND na.realm =
  'og_public'))) AND ( (.type IN ('promotion')) AND (.status = '1') AND
  (DATE_FORMAT(STR_TO_DATE(node_data_field_date_de_dbut.field_date_de_dbut_value2,
  '%Y-%m-%dT%T'), '%Y-%m-%d') > '2017-06-16') ) ORDER BY
  node_data_field_date_de_dbut_field_date_de_dbut_value ASC LIMIT 0, 10
  in /home/user/web/foo.org/public_html/includes/database.mysqli.inc on
  line 154. warning: mysqli_real_escape_string() expects parameter 2 to
  be string, array given in
  /home/user/web/foo.org/public_html/includes/database.mysqli.inc on
  line 383. warning: mysqli_real_escape_string() expects parameter 2 to
  be string, array given in
  /home/user/web/foo.org/public_html/includes/database.mysqli.inc on
  line 383. user warning: You have an error in your SQL syntax; check
  the manual that corresponds to your MySQL server version for the right
  syntax to use near '= '1') AND (.type IN ('bon_plan')) AND (.tid AND
  '') AND (. > 0) ) ORDER BY DE' at line 1 query: SELECT
  DISTINCT(node.nid), changed, node.title AS node_title, users.name AS
  users_name FROM node node LEFT JOIN content_field_photographie
  node_data_field_photographie ON node.vid =
  node_data_field_photographie.vid INNER JOIN node_access na ON na.nid =
  node.nid WHERE (na.grant_view >= 1 AND ((na.gid = 0 AND na.realm =
  'all') OR (na.gid = 0 AND na.realm = 'og_public'))) AND ( (.status =
  '1') AND (.type IN ('bon_plan')) AND (.tid AND '') AND (. > 0) ) ORDER
  BY DESC LIMIT 0, 20 in
  /home/user/web/foo.org/public_html/includes/database.mysqli.inc on
  line 154. user warning: You have an error in your SQL syntax; check
  the manual that corresponds to your MySQL server version for the right
  syntax to use near '= '1') AND (.type IN ('hebergement')) AND
  (node_data_field_photographie.field_ph' at line 1 query: SELECT
  DISTINCT(node.nid), random, node.title AS node_title, location.city AS
  location_city, location.postal_code AS location_postal_code FROM node
  node LEFT JOIN content_field_photographie node_data_field_photographie
  ON node.vid = node_data_field_photographie.vid LEFT JOIN userpoints
  userpoints ON node.uid = userpoints.uid LEFT JOIN location_instance
  location_instance_node ON node.vid = location_instance_node.vid LEFT
  JOIN location location ON location_instance_node.lid = location.lid
  INNER JOIN node_access na ON na.nid = node.nid WHERE (na.grant_view >=
  1 AND ((na.gid = 0 AND na.realm = 'all') OR (na.gid = 0 AND na.realm =
  'og_public'))) AND ( (.status = '1') AND (.type IN ('hebergement'))
  AND (node_data_field_photographie.field_photographie_fid > 0) AND
  (userpoints.points > '40') ) ORDER BY ASC LIMIT 0, 1 in
  /home/user/web/foo.org/public_html/includes/database.mysqli.inc on
  line 154. user warning: You have an error in your SQL syntax; check
  the manual that corresponds to your MySQL server version for the right
  syntax to use near '= '1') AND (.type IN ('hebergement')) AND
  (votingapi_cache_vote_percent_average.' at line 1 query: SELECT
  DISTINCT(node.nid), votingapi_cache_vote_percent_average.value AS
  votingapi_cache_vote_percent_average_value,
  votingapi_cache_vote_percent_count.value AS
  votingapi_cache_vote_percent_count_value,
  votingapi_vote_vote_percent.value AS
  votingapi_vote_vote_percent_value, node.title AS node_title FROM node
  node LEFT JOIN votingapi_cache votingapi_cache_vote_percent_average ON
  node.nid = votingapi_cache_vote_percent_average.content_id AND
  votingapi_cache_vote_percent_average.content_type = 'node' AND
  votingapi_cache_vote_percent_average.value_type = 'percent' AND
  votingapi_cache_vote_percent_average.tag = 'vote' AND
  votingapi_cache_vote_percent_average.function = 'average' LEFT JOIN
  votingapi_cache votingapi_cache_vote_percent_count ON node.nid =
  votingapi_cache_vote_percent_count.content_id AND
  votingapi_cache_vote_percent_count.content_type = 'node' AND
  votingapi_cache_vote_percent_count.value_type = 'percent' AND
  votingapi_cache_vote_percent_count.tag = 'vote' AND
  votingapi_cache_vote_percent_count.function = 'count' LEFT JOIN
  votingapi_vote votingapi_vote_vote_percent ON node.nid =
  votingapi_vote_vote_percent.content_id AND
  votingapi_vote_vote_percent.content_type = 'node' AND
  votingapi_vote_vote_percent.value_type = 'percent' AND
  votingapi_vote_vote_percent.tag = 'vote' INNER JOIN node_access na ON
  na.nid = node.nid WHERE (na.grant_view >= 1 AND ((na.gid = 0 AND
  na.realm = 'all') OR (na.gid = 0 AND na.realm = 'og_public'))) AND (
  (.status = '1') AND (.type IN ('hebergement')) AND
  (votingapi_cache_vote_percent_average.value > 20) ) ORDER BY
  votingapi_cache_vote_percent_average_value DESC,
  votingapi_cache_vote_percent_count_value DESC LIMIT 0, 10 in
  /home/user/web/foo.org/public_html/includes/database.mysqli.inc on
  line 154.

I've already done a search and replace of &$ to just $, as I read that this method was depreciated in PHP 5.4 onwards.
perl -p -i -e 's|\&\$|\$|g' `grep  --include \*.inc -rl '&$' .`
perl -p -i -e 's|\&\$|\$|g' `grep  --include \*.module -rl '&$' .`
perl -p -i -e 's|\&\$|\$|g' `grep  --include \*.php -rl '&$' .`

So now I'm trying to figure out how I update all of the modules / apply all the Drupal 7 patches. I'm used to Wordpress, where it just does it all for you. To me, it seems like everything has to be done manually here. Is that correct?
Any ideas / suggestions would be much appreciated - I'm drowing a bit here!
Answer: You can update your site as follows:

Via Drush: run drush rf && drush ups to check for updates. To update a module run drush up [module-name] or drush up drupal to update core.
Via the interface: visit /admin/modules. Note that this is not recommended. Also core updates cannot be done through the interface. If possible use Drush.
Manual: download the new module packages individually from Drupal.org and replace them in your modules folder. Note that this is not recommended, use Drush.

You can check your site's status via /admin/reports/status. A lot of information is deplayed here, including the core version.
More information about installing Drush: http://docs.drush.org/en/master/install/
Comment: You're using Drupal 5 @Andrew? There's basically no chance you'll get that working with php7, the code is far too old. Php 5.2.x is the latest supported for D5. You need to upgrade to a newer version of drupal, which can't be done automatically and isn't a simple process. You'll need to come up with a migration plan based on the core/custom/contrib  modules you're using, manually rewrite any custom themes so they work with the version you're migrating to, and so on. Put aside a few days, it's a big job
Comment: I think you could install Drush via Composer: `composer global require drush/drush:4.*`. Do not that Drupal 5 and 6 are currently unsupported. It is strongly recommended to upgrade to at least Drupal 7!
Comment: @AndrewNewby That one's a bit of an oxymoron - any host that still offers 5.2 can't really be considered "decent", it's been EOL for years and has no support. You could run it yourself on a custom server, but it's a really bad idea IMO
Comment: Thanks. I just installed `drush` using apt-get, but when running I get: `Drush 5.10.0 does not support Drupal 5. Use Drush 4 instead.`. How to get around that?
Comment: Ah man, rubbish :( The worst part, is that it only gets a couple of thousand hits a month. Not sure its worth spending several days on it :( Are there any decent hosts who still use PHP 5.2 that I could stick it on?
Comment: @Clive haha ok, I get the point :) We are basically migrating from another server to a new one (on Linode), that has a decent spec. I may just have to see if we "convert" this site into static pages, and leave it at that (its more aimed at sending traffic to our main site, and doesn't get any real use)
Comment: @Gun5m0k3 - while your answer doesn't fix my problem, I'm going to accept it (as it would have worked if I'd been using Drupal 6 or 7, like I was thinking I had)


How do I identify unknown protocols on my Cisco 2811?

Question: I have a misbehaving Cisco 2811.  It serves our office of 20 with internet and phones via Call Manager Express.  Except that lately the phones aren't working right and internet is choppy.  The outside interface attached to our ISP is fine.  The inside interface is attached to a 2960 where our internal network is connected. There are obvious issues in the show interface:
    FastEthernet0/1 is up, line protocol is up
  Hardware is MV96340 Ethernet, address is 001b.d40a.e071 (bia 001b.d40a.e071)
  Internet address is 192.168.1.254/24
  MTU 1500 bytes, BW 100000 Kbit/sec, DLY 100 usec,
     reliability 255/255, txload 13/255, rxload 19/255
  Encapsulation 802.1Q Virtual LAN, Vlan ID  1., loopback not set
  Keepalive not set
  Full-duplex, 100Mb/s, 100BaseTX/FX
  ARP type: ARPA, ARP Timeout 04:00:00
  Last input 00:00:00, output 00:00:00, output hang never
  Last clearing of "show interface" counters 00:54:10
  Input queue: 1/150/420/0 (size/max/drops/flushes); Total output drops: 0
  Queueing strategy: fifo
  Output queue: 0/40 (size/max)
  5 minute input rate 7463000 bits/sec, 1038 packets/sec
  5 minute output rate 5244000 bits/sec, 880 packets/sec
     3021883 packets input, 2691686783 bytes
     Received 7649 broadcasts, 0 runts, 0 giants, 95 throttles
     2155 input errors, 0 CRC, 0 frame, 0 overrun, 2155 ignored
     0 watchdog
     0 input packets with dribble condition detected
     2537251 packets output, 1717084791 bytes, 0 underruns
     0 output errors, 0 collisions, 0 interface resets
     464 unknown protocol drops
     0 babbles, 0 late collision, 0 deferred
     0 lost carrier, 0 no carrier
     0 output buffer failures, 0 output buffers swapped out

I have replaced the cable with a brand new one, with no effect.  I have set the switchport nonegotiate on the 2960 it is attached to.  I have verified that the settings are the same on both interfaces (100M, Auto/Auto).  I have ensured CDP is on, and keepalives are off.
I am remote today, but I'm going to put a SPAN port on the 2960 tomorrow to try to get more info.  Is there anything else I can do to figure out where these problems are coming from?
I did a sho interface mac-accounting and one person's computer is sending about 80% of the total traffic to the router...2800M bytes out of 3100M bytes total.  My assistant checked on her PC and found nothing out of the ordinary.
EDIT:
By request, here's the sh int from the switch port:
GigabitEthernet1/0/48 is up, line protocol is up (connected)
  Hardware is Gigabit Ethernet, address is b414.89ba.32b0 (bia b414.89ba.32b0)
  MTU 1500 bytes, BW 100000 Kbit, DLY 100 usec,
     reliability 255/255, txload 22/255, rxload 4/255
  Encapsulation ARPA, loopback not set
  Keepalive not set
  Full-duplex, 100Mb/s, media type is 10/100/1000BaseTX
  input flow-control is off, output flow-control is unsupported
  ARP type: ARPA, ARP Timeout 04:00:00
  Last input 00:00:03, output 00:00:00, output hang never
  Last clearing of "show interface" counters never
  Input queue: 0/75/0/0 (size/max/drops/flushes); Total output drops: 20147
  Queueing strategy: fifo
  Output queue: 0/40 (size/max)
  5 minute input rate 1883000 bits/sec, 693 packets/sec
  5 minute output rate 8721000 bits/sec, 1020 packets/sec
     64561402 packets input, 46701593519 bytes, 0 no buffer
     Received 109892 broadcasts (102372 multicasts)
     0 runts, 0 giants, 0 throttles
     0 input errors, 0 CRC, 0 frame, 0 overrun, 0 ignored
     0 watchdog, 102372 multicast, 0 pause input
     0 input packets with dribble condition detected
     66138056 packets output, 36914890016 bytes, 0 underruns
     0 output errors, 0 collisions, 0 interface resets
     0 babbles, 0 late collision, 0 deferred
     0 lost carrier, 0 no carrier, 0 PAUSE output
     0 output buffer failures, 0 output buffers swapped out

Comment: Can you post the output of "sh int" for the corresponding switch interface? I'm suspecting a duplex mismatch. Both sides need to be set to Auto/Auto or to the same speed/duplex settings. You can't have one side set to Auto/Auto and the other side hard coded, that will always cause problems.
Comment: Is your switch port configured as an 802.1q trunk?
Comment: Yes, it is.  It carries several VLANs: data, voice, and a few ancillary for other things. (7 altogether)
Answer: Try tuning off DTP on the switch's interface. switchport nonegotiate Since the router isn't a switch, it won't understand the Dynamic Trunking Protocol.
Comment: This I have done, as I said in the original question, but thanks.  It looks like at present the unknown protocol drops are occurring about every 5 seconds.
Comment: Sorry, I missed that in the original question. Do you have VTP enabled on the switch? I'm trying to think of what else could be sending L2 frames the switch wouldn't understand.
Comment: I do have VTP enabled, and no worries...I'm trying to think of what else it could be as well.  Haven't found anything yet.
Comment: If you ever get around to a packet capture, you could put it up at http://www.cloudshark.org. I'm curious what it is. I'm sure at least part of it is VTP.
Comment: If the switch's code version is new enough you can add 'no vtp' on the switch interface connected to the router. On switch links to routers we disable DTP, VTP and enable portfast in trunk mode and that seems to cut down on weird counter increments.
Answer: So, going off a troubleshooting background, I'd look at it this way.
Everything is choppy/slow right? Internet and phones. And you've shown us the interface statistics. I'm looking at this bit here:
   ->3021883 packets input, 2691686783 bytes
->Received 7649 broadcasts, 0 runts, 0 giants, 95 throttles
->2155 input errors, 0 CRC, 0 frame, 0 overrun, 2155 ignored
->464 unknown protocol drops

First, lets eliminate the easy one, protocol drops and input errors. 464 drops accounts for 0.01% of those 3,021,883 packets input, again the input errors are a similar story. These things do happen occasionally, it is a concern that you have any, but I'm willing to bet you would say its worse than 0.01% slower right?
So anyway, the throttles may shed some light on the issues, throttles happen when then the device is overloaded. So that might be something to look into.
Slowness is a pain in the bum to diagnose though, I'd really try to tie it down to a time period, maybe stay late one night when most people have gone and see if its still slow? 90% of the time, I've found all slowness is capacity related.
So a few things to check.

Check the CPU usage ("show process cpu history") and see if there have been any peaks at all.
Are you using QoS? check for drops on the interface ("show policy-map interface xx/xx)
How many VLANs are you running? I assume you'll be using a router-on-a-stick setup if so?

I personally suspect some sort of CPU/Memory bottleneck somewhere, this wont show up on normal interface show commands. From the show command you've pasted, I don't see any "real" problems, nothing that would be causing noticeable issues.
Also, give it a reboot. You never know :)
Comment: Ignored errors are when your router interface is receiving packets faster than it can buffer, so they just get 'ignored'.  Although 2k ignored in 3m packets is generally not a problem.
Comment: I agree, just thinking if there's slowness, and a small sign pointing to an issue, it might be running very close to its limits. More than the interface stats are suggesting.
Comment: Very good steps to take, this is what I ended up doing, as well as configure MAC-accounting. It was a sort of CPU/memory bottleneck, I'm adding an answer to detail what I did.
Answer: Artanix suggested some great troubleshooting tips, which are a great way to get started on a router issue.
I also used some of the troubleshooting tips here because the CPU usage on the router regularly pegged at 99-100%.
Configuring MAC address accounting via NetFlow (as described here) led me to a single device that was generating 80% of the traffic coming in on the Fa0/1 interface.  Tracing that to a single computer, my intern found nothing he could lay blame to, but I checked her outbox in MS Outlook...she had sent an email with attachments over 50MB (our outgoing size limit is 40MB) to a co-worker in our office in another city.
According to my SPAN session, the mail server would dutifully receive all this data, then tell Outlook it was over the size limit, and drop the connection.  Outlook, knowing that it had not yet sent the message, continued to attempt to send it over again, and very aggressively.  I don't know why the error messages weren't getting back through, but I suspect that it had something to do with Outlook assuming bandwidth to the mail server being cheap.
Once we deleted this mail message from the outbox and had given a small lecture on using the file server to transfer large files rather than email, CPU usage fell back to the normal 40-60% range and phones and network returned to their normal state, and throttles on the interface returned to zero.
So, that fixed the problem and rendered the question relatively moot.  I still don't know what the unknown protocols were, but I am sure my SPAN session has them listed.


Proving $\mathbb{N} \times \mathbb{N} \cong \mathbb{N}$ when $\mathbb{N}$ includes $0$

Question: I am struggling to find an explicit bijection $\mathbb{N} \times \mathbb{N} \to \mathbb{N}$ when $\mathbb{N}$, by definition, includes $0$. If $\mathbb{N}$ were to exclude $0$, I could note that any positive integer can be written uniquely in the form $2^{a-1} (2b - 1)$ and then map $(a,b) \to n$. Including $0$, I have to change $a - 1$ to $a$ and $2b - 1$ to $2b + 1$, but I still run into the issue of what to map to $0$. I can't map $(0,0)$ to $0$, for example, because $2^{0} (2(0) - 1) = 1$ is the unique element of the form $2^{a-1} (2b - 1)$ mapping to $1$.
Does anyone have any tips for how to repair this bijection?
Comment: Can you find a bijection between $\mathbb{N}$ and $\mathbb{N}\cup\{0\}$? If you can, you can just run that bijection 'both ways' — on the input, go $\mathbb{N}\cup\{0\}\to\mathbb{N}$ to translate your inputs into the ones you know how to handle, and then on the output go $\mathbb{N}\to\mathbb{N}\cup\{0\}$ to map back.
Comment: See https://math.stackexchange.com/questions/1179491/explicit-bijection-between-mathbb-n-and-mathbb-n-times-mathbb-n or https://math.stackexchange.com/questions/222709/inverting-the-cantor-pairing-function for some other bijections that work.
Comment: If you have bijection $f:\mathbb N_+ \times \mathbb N_+ \to \mathbb N_+$ and by $g:\mathbb N_+ \to \mathbb N$ you denote bijection $g(n) = n-1$, similarly with $h:\mathbb N \times \mathbb N \to \mathbb N_+ \times \mathbb N_+$ by formula $h(n,m) = (n+1,m+1)$ then composition $g \circ f \circ h : \mathbb N \times \mathbb N \to \mathbb N$ will work
Comment: So am I correct in thinking that if I want to include $0$, I need to in some sense 'compose bijections', i.e., this map can't be defined piece-wise? That came to mind, but I was hoping there was a simpler approach. By injectivity of the original map, it makes sense to me that this wouldn't be possible.
Comment: " I can't map (0,0) to 0, for example, because 20(2(0)−1)=1 is the unique element of the form 2a−1(2b−1) mapping to 1."  So juist subtract $1$ from the results.
Comment: You've got something mapping to $N$ without $0$.  SO just substract $1$ from every result and you get somthing mapping to $N$ *with* the $0$.
Comment: You do $\mathbb N_0\to \mathbb N_1$ via $n+1$ and $N_1 \to N_0$ via $n-1$.  So.... just do it.  $N_1 \to N_1 \to N_1$ via $2^a(2b-1)$ works.  So $N_0\to N_0\to N_1$ via $2^{a+1}(2b+1)$ works and $N_0\to N_0 \to N_0$ via $2^{a+1}(2b+1)-1$.
Comment: "compose bijections', i... That came to mind, but I was hoping there was a simpler approach. "  As one of the bijections being composed is "adding/subtracting one" the composition is pretty dang simple.  You just add one to the $a,b$ and then subtract one from the result.
Answer: Just.... combine.
You have $f:\mathbb N_{1} \times \mathbb N_1 \to \mathbb N_1$ via $f(a,b) = 2^{a-1}(2b-1)$.
And you have $g:\mathbb N_0 \to \mathbb N_1$ via $g(n) = n+ 1$.
So you have $g\times g: \mathbb N_0 \times \mathbb N_0 \to \mathbb N_1 \times \mathbb N_1$ via $g\times g(a,b) = (g(a), g(b)) = (a+ 1, b+1)$ and
You have $f\circ g\times g:  \mathbb N_0 \times \mathbb N_0 \to \mathbb N_1 \times \mathbb N_1 \to \mathbb N_1$ via $f\circ g\times g (a, b) = f(a+1, b+1) = 2^a(2b + 1)$.
And you have $g^{-1}\circ f\circ g\times g: \mathbb N_0 \times \mathbb N_0 \to \mathbb N_1 \times \mathbb N_1 \to \mathbb N_1\to \mathbb N_0$ via $g^{-1}\circ f\circ g\times g(a,b) = g^{-1} (f(a+1,b+1)) = 2^a(2b+1) -1$.
======
Alternatively the other standard bijection (that works on the cross product of any two countable sets) is to simply list pairs by weaving a diagonal path:
$(1,1), (2,1), (1,2), (3,1), (2,2),(1,3),(4,1), (3,2),(2,3),(1,4), (5,1),(4,2).....(4,2),(1,5), (6,1),(5,2)....,(2,5),(1,6),(7,1).....\to$
$1,2,3,4,5,7......$
Then just adding the index $0$ does not change anything significant.
$(0,0),(1,0),(0,1),(2,0),(1,1),(0,2),(3,0),..... \to $
$0,1,2,3,4,5,6....$
The trouble is we aren't actually explicitely defining what the algebraic expression of the bijection is; just showing intuitively it must exist.  But then again there is nothing in the definition that says we have to define what the bijection is and if we can demonstrate via induction that it exists that is fine.
But with little math we can get the first one is:
For any $(1,k)$ we map $(1,k) \to \sum_{j=0}^k = j$.  And so for the following next batch $(k+1, 1)$ to $(1, k+1)$ we map $(a=(k+1)-(b-1), b)\mapsto (\sum_{j=0}^k j) + b$.... of $(a,b)\to [\sum_{j=0}^{a+b-1} j] + b = \frac {(a+b-1)(a+b)}2 + b= \frac {(a+b)^2+(b-a)}2$.
The second is similar.
If $k = a+ b+ 1$ then $(0, a+b)\mapsto [\sum_{j=0}^k j]-1 = \frac {(a+b+1)(a+b+2)}2 - 1 = \frac{(a+b)^2 +3(a+b)}2 + 1$ and $(a,b)\mapsto \frac{(a+b)^2 +3(a+b)}2 + 1- a = \frac {(a+b)^2 + (a+3b) +2}2$
It may or may not be worth noting with shifiting indexes.
The first $\frac {(a+b)^2+(b-a)}2$ becomes $\frac {(a+1+b+1)^2 - (b-1-a+1)}2-1$ is the same as the same as the second.


Adjust size of HTML fieldset

Question: I am using the <fieldset> tags for a website I am making to display information because the fieldset box makes separating the information more appealing.
The only issue is that the fieldset box spreads the width of the browser page and has lots of empty white space. Is there an attribute or way to make it so that it isn't as long across the screen?
Comment: Should you using a fieldset if it is only to make the page more appealing? - see the answer with 5 upvotes: https://stackoverflow.com/questions/9812898/is-it-wrong-to-use-the-fieldset-tag-without-form-tag
Comment: Make that six upvotes.  I would tend to agree with @Pete - while it may be technically "valid" HTML, it is certainly not _semantic_ markup if it is simply being used for styling purposes.  The same effect can be achieved with a more appropriate container/containers and CSS.
Answer: All block-level elements with unspecified size will take the full available width.
If you add some css to the fieldset to set it to display as an inline block, it will not go full width. You can also set a width there is you wanted.
fieldset{
  display: inline-block;
}

or
fieldset{
  width: 50%
}

The only issue you might have here is that the fieldset might not flow properly because it'll be inline. You could also set a width on the fieldset using CSS or wrap the fieldset in a div and set the DIVs width to whatever width you need.
Here's a codepen with examples of each: https://codepen.io/jamiecalder/pen/dyyYLVp
Comment: Okay so itd be {width: 50%} ****  where the * would be the data in a fieldset?
Comment: The code I showed above would be part of your CSS file. Take a look at the codepen I created, and you can see that it would be in a separate file.

Adjust size of HTML fieldset


Aspects from HttpServletResponse's sendError method explained by the official documentation

Question: I am in reference to HttpServletResponse's sendError method:
void sendError(int sc,
               java.lang.String msg)
               throws java.io.IOException

... and the official documentation provided:

Sends an error response to the client using the specified status and
clears the buffer. The server defaults to creating the response to
look like an HTML-formatted server error page containing the specified
message, setting the content type to "text/html". The server will
preserve cookies and may clear or update any headers needed to serve
the error page as a valid response. If an error-page declaration has
been made for the web application corresponding to the status code
passed in, it will be served back in preference to the suggested msg
parameter and the msg parameter will be ignored.
If the response has
already been committed, this method throws an IllegalStateException.
After using this method, the response should be considered to be
committed and should not be written to.

Can anyone please explain what is meant by "clears the buffer" and "If the response has already been committed"?
Answer:
what is meant by "clears the buffer"

The code will response.resetBuffer() which basically resets any written and unflushed data of response body.

and "If the response has already been committed"?

If the response headers are already sent to the client. This is a point of no return. The server cannot take back already sent data from the client and re-send a different response.
An example of the normal flow is as below:

user requests JSP
JSP writes some HTML to response body
some awkward code in midst of a JSP file throws an exception
server calls response.sendError(500) so that HTML of HTTP 500 error page will be written
user sees HTTP 500 error page

However, if between step 2 and 3 the response buffer is flushed (i.e. any so far written data gets actually sent from server to client), then the response is in a "committed" state. This cannot be resetted. The enduser basically ends up getting halfbaked HTML output representing the part until the point the exception has occurred.
That's also one of the reasons why doing business logic in a JSP file is a bad practice. See also a.o. How to avoid Java code in JSP files?


Why doesn't manyCharsTill combinator work if the "till" parser starts with spaces?

Question: I try to parse xml-like tags (but not a correct xml document..):
the goal is to get back just "Flange width" without the beginning or trailing whitespaces, but with the internal ones.
open FParsec

let testParser =
    pstring "<desc>" .>>. spaces
    >>. manyCharsTill anyChar (spaces .>>. pstring "</desc>")

run testParser "<desc> Flange width </desc>"

The expected result if I understood the parser combinators:
the anyChar parser to keep swallowing chars unit the "till" parser which looks for spaces followed by the end tag succeeds.
What actually happens, is the "till" parser fails on the space before "width" (as it should) but short circuits the manyTill parser instead of letting the anyChar swallow that space and continue onwards.
Output:
val it : ParserResult<string,unit> =
  Failure:
Error in Ln: 1 Col: 15
<desc> Flange width </desc>
              ^
Expecting: '</desc>'

What am I not getting? or what would be an idiomatic solution here?
Comment: As a side-note, I've also found that just doing `|>> fun (s : string) -> s.Trim()` is sometimes easier and even faster than trying to skip over whitespace.
Answer: The issue is that spaces parses successfully and moves the stream to the beginning of w. pstring "</desc>" then fails.
The end result is that the endp parser has failed, but it has changed the state (we've moved past the spaces). You want the parser to fail and not change the state (before the space). The docs for manyTill (which are referred to by manyCharsTill) explain this:

The parser manyTill p endp repeatedly applies the parser p for as long as endp fails (without changing the parser state).

You can do that using the .>>.? operator:

The parser p1 .>>.? p2 behaves like p1 .>>. p2, except that it will backtrack to the beginning if p2 fails with a non‐fatal error and without changing the parser state, even if p1 has changed the parser state.

So this instead:
let testParser =
    pstring "<desc>" .>>. spaces
    >>. manyCharsTill anyChar (spaces .>>.? pstring "</desc>")

See this fiddle for a working demo.


iOS How to fetch profile image for each user use Parse Swift

Question: I have an app in which I have news, which users are added and I want in a table view to show user photo which are taken from DB "_User" and I fetch data from class "news". My code is:
<code> var user = PFUser.current()
    let useravatar = user!["profilePicture"] as? PFFile
    useravatar?.getDataInBackground{ (imageData, error)in
        if imageData != nil {
            let image = UIImage(data: imageData!)
            cell.userPhoto.image = image

        }
    }
</code>
But this code loads only the current user photo, but I need the user photo for each row, how I can do this? Example:

As you see in pictures I have two user, but it loads only my profile photo.
Comment: Load image asynchronously by using DispatchQueue or Operation Queue.
Comment: Do you have example?
Answer: Load images asynchronously
<code>var user = PFUser.current() //you'e setting an image for same user

let useravatar = user!["profilePicture"] as? PFFile
useravatar?.getDataInBackground{ (imageData, error)in
    DispatchQueue.main.async {
      if imageData != nil, error == nil {
        let image = UIImage(data: imageData!)
        cell.userPhoto.image = image

      }
   }
}
</code>
Comment: are you using collection view of tableview?
Comment: No, i not use collection view
Comment: It seems that cell is repeating its content.
Comment: actually you are getting same user every time `var user = PFUser.current()` so it resulting same image.
Comment: Yes, it's because i so lazy, i copy two time one post, but to another user)
Comment: I think now issue is fixed.
Comment: But how i can load photo for each user?
Maybe i can sort by username some how
Comment: please post complete code...so that I can help you out.


Workflow: Restart PC, wait for powershell, execute commands

Question: Creating a script to restart devices on a specific network and add some notification or iteration variable that lets me know they have been restarted and powershell is available to be leveraged.  However, I can't even get the most basic of workflow to run as I expect it to.
I am getting no error messages, but at the same time nothing is happening so I have no way to even begin to understand why it isn't working.  Any insight is greatly appreciated.
Import-Module PSWorkflow

#Get list of workstation IP Addresses on the 87 VLAN
[System.Collections.ArrayList]$NetScan = get-content -path C:\temp\NetScan.log

Workflow Restart87Network{

    Foreach -parallel ($ComputerIP in $NetScan)
    {
        Restart-Computer -PSComputerName $ComputerIP -force -wait -for powershell;
        $ComputerIP
    }

}

Restart87Network

Short and sweet just for testing to see if it is working.  When it runs it doesn't restart the computers that are in the Array.  Doesn't throw any error messages, doesn't restart the devices in the array, and the $ComputerIP does not list the IP addresses that are held in that variable.
Maybe I am doing something wrong, or just overlooking something, but everything else I test works as I expect it to except this.
Workflows are definitely working because putting '$var + 1' in the workflow and calling $Var outside of it I get the expected result and other basic commands are working as well.  I know I can just use foreach without a workflow and have all the devices restarted, but I want to monitor each one to see when powershell is back up so that I can continue executing a script after.  I am currently on Powershell 5.1 so I believe my parallel options are limited.
Comment: "and the $ComputerIP does not list the IP addresses that are held in that variable." - how do you know that it ever reaches that statement and isn't just stuck waiting forever for the remove computer to restart? FWIW the parameter name is `-ComputerName`, not `-PSComputerName`, maybe try fixing that.
Comment: When used in a workflow -computername does not work, it will only accept -pscomputername for whatever reason.

The workflow executes and appears to be complete.  When it is complete it should output whatever resides in the $ComputerIP but it does not.  If I were to do a workflow with just $ComputerIP in there it would list the values within.  For some reason it is hanging up on the restart command as you mention, but there is no troubleshooting I can do as no error is presented.
Answer: The workflow can't "see" the NetScan variable from the calling scope.
Parameterize the workflow and pass the list as an argument:
Import-Module PSWorkflow

#Get list of workstation IP Addresses on the 87 VLAN
$NetScan = Get-Content -Path C:\temp\NetScan.log

Workflow Restart-87Network {
    param([string[]]$TargetComputer)

    foreach -parallel ($Computer in $TargetComputer) {
        # attempt to restart
        try {
            Restart-Computer -ComputerName $Computer -Force -Wait -For Powershell -ErrorAction Stop
            $success = $true
            $message = 'Reboot complete'
        }
        catch {
            $success = $false
            $message = "$_"
        }
        # output results
        [PSCustomObject]@{
            Target  = $Computer
            Success = $success
            Message = $message
        }
    }
}

Restart-87Network -TargetComputer $NetScan

I took the liberty of adding some error handling to your workflow
Comment: I will have to see if this works tomorrow.  I really appreciate the responses!

Out of curiosity, is it because the Foreach is only looking at the scope within the workflow for the $NetScan variable, and it cannot see it as it is outside of the workflow?

Because if I were to simply place $NetScan in the workflow it will output the array.
Comment: @ThePostMan That's right, only variables declared/assigned _within_ the workflow body can be resolved from inside it. This differs from regular script functions which can access the calling scope.
Comment: That's working!  Thank you so much!  However, do you happen to have any insight as to why my powerhsell will not accept the -computername parameter for Restart-Computer?  When I try to run using it, it says it could not find the computername parameter, and in Remote Connectivity it is handled by the PSComputerName Parameter.  When using PSComputerName as the parameter it works as expected.  I am on v5.1 if that makes any difference.


One-sided ttests in regression analysis with a clear prior

Question: This question has been asked virtually the same in this post:
Regression Slope and a Bilateral Test
However, I still don't get my head around why when I have a clear hypothesis of a positive relationship between my covariate of interest and the outcome in mind I should "waste" the power of testing whether the relationship could be negative. This is particularly strange to me in the case of experiments where the extra needed power implies having to spend more ressources to collect additional data. Does anybody have an opinion on this or knows statistical literature to read up on?
Answer: The linked thread considers a case where the alternative $H_1$ and the corresponding rejection region are chosen after the test statistic has been observed. This is bad practice as it distorts the $p$-value and may change the decision (in comparison to the valid way of conducting the test). Now if you choose $H_1$ before observing the test statistic, the problematic aspect of the former approach is eliminated.
One-sided tests exist and can be used and yield valid results. If you know $\theta<c$ to be impossible, you can formulate and test $H_0\colon \ \theta=c$ against a one-sided alternative $H_1\colon \ \theta>c$ no problem. Regarding power, indeed it would be a waste of time to employ the two-sided $H_1\colon \ \neq c$ instead. However, if $\theta<c$ is merely unlikely according to our understanding / is out of line with our favourite theory, this is usually not deemed sufficient to exclude this possibility from the alternative.
Regarding references, I think this is introductory level material and should be found in most classical textbooks, both theoretical and applied. A list of free statistics textbooks is available in this thread. This one contains some more (not necessarily free).
Comment: @Papayapap, perhaps because in many (most?) cases the "uninteresting" side of the alternative is not impossible, merely believed to be unlikely. Choosing a two-sided alternative ensures we do not ignore possibilities which do not align with our favourite theory.
Comment: Thanks! Then it is more a question of why so many in social sciences waste power conducting two-sided tests..


How to enable SELinux inside of a CentOS Docker container?

Question: I am trying to install SELinux inside of a Docker container in order to distribute an application that uses SELinux internally.
The default CentOS image does not have SELinux installed:
<code>$ docker run -it centos:latest /bin/bash
[root@38ae5a98273d /]# sestatus
bash: sestatus: command not found
</code>
After I install it from yum, SELinux is not enabled yet.
<code>[root@38ae5a98273d /]# yum install policycoreutils selinux-policy-targeted
...
[root@38ae5a98273d /]# sestatus
SELinux status:                 disabled
</code>
All the documentation I've found says that you need to issue a system reboot in order to install it.  However, I am not aware of a method to simulate a system reboot inside a Docker container.
How does one go about installing and enabling SELinux inside of a container?
Answer: SELinux is not namespaced, so individual containers cannot have their own separate SELinux policies. SELinux will always appear to be "disabled" in a container, though it is running on the host.
If your application requires SELinux, you cannot use it inside Docker. You will need to use a regular virtual machine.
Comment: tl; dr:containerisation isn't virtualisation.
Comment: c.f. https://www.youtube.com/watch?v=zWGFqMuEHdw
Comment: Too bad... spent some time to try test Ansible Molecule roles booth in KVM and in the rootless Podman container.


Imap local cache server

Question: I'am not sure if it's the good place to ask the question. I would like to know if it's possible to have a local Imap cache server. The main IMAP server is by the provider. To improve performance I want to install an Imap on the LAN. When a user retrieves his emails, he takes them from the server on the LAN. I have seen that Perdition is a proxy imap, but I think it can't store email locally. Does anyone know if a such architecture exists ? Florent
Answer: You can setup an usual IMAP-server like dovecot and fill it with messages fetched from the main server by fetchmail utility. If the main server is under your control and is also powered by dovecot you can use handy dovecot's tool dsync to syncronize both instances.

Imap local cache server


how to quickly locate which sheets/dashboards contain a field?

Question: I am creating a data dictionary and I am supposed to track the location of any used field in a workbook. For example (superstore sample data), I need to specify which sheets/dashboards have the [sub-category] field.
My dataset has hundreds of measures/dimensions/calc fields, so it's incredibly time exhaustive to click into every single sheet/dashboard just to see if a field exists in there, so is there a quicker way to do this?
Comment: If you are in an environment with a Tableau Server that has the Data Management Add-on installed, you can use Tableau's Data Catalog to quickly see which fields are used in which views.
Comment: Sadly, my company does not have that add-on installed
Comment: @AlexBlakemore is there anything I could do within tableau prep to assist with this?
Comment: @AlexBlakemore I did try opening up the workbook via notepad to view the XML code. Is there a quick reference in there that would indicate the sheet name that field is on?
Answer: One robust, but not free, approach is to use Tableau's Data Catalog which is part of the Tableau Server Data Management Add-On
Another option is to build your own cross reference - You could start with Chris Gerrard's ruby libraries described in the article http://tableaufriction.blogspot.com/2018/09/documenting-dashboards-and-their.html


sign of limit of a sequence

Question: Let us consider the following sequences: $\{X_{n}\}_{n=1}^{\infty}$ and $\{Y_{n}\}_{n=1}^{\infty}$ such that $X_{n} \xrightarrow{a.s.} a$ and $Y_{n} \xrightarrow{a.s.} a$,
for some constant $a > 0$. Next, assume that
$$
\sqrt{n}(X_{n} - a) \xrightarrow{d} Z_{x}
$$
and
$$
\sqrt{n}(Y_{n} - a) \xrightarrow{d} Z_{y},
$$
where $Z_{x}$ and $Z_{y}$ are some random variables.
Next, assume that $X_{n} \leq Y_{n}$ for all $n$.
Can we say something about the sign of sequence
$$
\frac{X_{n}}{n-1} - \frac{Y_{n}}{n}
$$
when $n\to\infty$?
Answer: I believe that the answer is generally "no". First, obviously if $X_n=Y_n$ then the sign is trivially +. We want to show that exist $X,Y$ such that the sign will be always -.
Let $a=1/2$. Let $X_n= a + \frac{1}{n}$ and $Y_n= a + \frac{2}{n}$. You can add some noise if you dont want $Z$ to be degenerate.  Then, $\frac{X_n}{n-1} - \frac{Y_n}{n} \approx \frac{a-1}{n(n-1)}<0$ for all $n>2$.

sign of limit of a sequence


Must cross-entropy method's true distribution be in-family with the proposal distribution?

Question: The cross entropy method is used in rare event estimation, such as when estimating $$\mathbb{E}_u\left[H(X)\right] = \int H(x) f(x; u) dx\text{,}$$ where $H$ is some performance function and $f(x; u)$ is your true probability distribution from which $x$ is sampled.
The standard algorithm is to find the parameterization $v$ for which importance sampling gives the best convergence. Your importance sampling proposal distribution thus ends up being some $f(x; v)$.
My question is whether it matters that the true distribution must be representable as $f(x; u)$. Is there anything stopping us from using some other parametric distribution for our importance distribution?
Answer: Okay, I figured it out.
The proposal distribution does not need to be in-family with the true distribution.
The standard formulation in the original cross-entropy paper writes it up this way, which is also what is found on wikipedia, but in general it does not need to be the case. More generally, such as given in "Improving Aircraft Collision Risk Estimation using the Cross-Entropy Method," the true distribution $p(x)$ and the importance sampling distribution $q(x; v)$ need not be of the same family. The math works out the same for the cross entropy optimization step:
$$
v^{(t+1)} = \text{arg}\,\text{max}_v \frac{1}{N} \sum_i H(x_i) \frac{p(x_i)}{q(x_i; v^{(t)})} \ln q(x_i; v)
$$
Also note that in importance sampling, the proposal distribution also does not need to be in-family with the true distribution.


Prove that $\text{tr}(((A+B)^T(A+B))^{1/2}) \leq \text{tr}((A^TA)^{1/2}) + \text{tr}((B^TB)^{1/2})$

Question: I'm trying to show that the nuclear norm (sum of singular values of the matrix) is actually a valid matrix norm. I know that
$$\sum\limits_{i=1}^n \sigma_i(A) = \text{tr}((A^TA)^{1/2})$$
So now what is left to prove is triangle inequality
$$\text{tr}(((A+B)^T(A+B))^{1/2}) \leq \text{tr}((A^TA)^{1/2}) + \text{tr}((B^TB)^{1/2}) \quad \forall A,B\in M_{n\times n}(\mathbf{R})$$
Which is what I'm currently stuck at. Any help would be appreciated.
UPD. What vector norm the matrix norm $\text{tr}((A^TA)^{1/2})$ is associated to?
Comment: $\langle A,B\rangle = \operatorname{Tr}(B^TA)$ is an inner product so $\sqrt{\langle\cdot, \cdot\rangle}$ is a norm. The triangle inequality follows from Cauchy-Schwarz.
Comment: @mechanodroid would you please elaborate more on that? What is $\sqrt{(\cdot, \cdot)}$ and why is it norm? How does the inequality in question follows from CSI? Also I added an update to the question -- would be interesting to know the vector norm this matrix norm is associated to.
Answer: The quantity $\|A\| = \sqrt{\langle A,A\rangle} = \operatorname{Tr}(A^TA)^{1/2}$ is a norm.
If you agree that $\langle A,B\rangle = \operatorname{Tr}(B^TA)$ is an inner product, then this inner product obeys the Cauchy-Schwarz inequality $|\langle A,B\rangle| \le \|A\|\|B\|$.
Therefore
\begin{align}
\|A+B\|^2 &= \langle A+B, A+B\rangle \\
&= \langle A,A\rangle + \langle A,B\rangle  + \langle B,A\rangle  + \langle B,B\rangle \\
&=\|A\|^2 + 2\langle A,B\rangle + \|B\|^2\\
&\le \|A\|^2 + 2|\langle A,B\rangle| + \|B\|^2\\
&\le \|A\|^2 + 2\|A\|\|B\| + \|B\|^2\\
&= (\|A\| + \|B\|)^2
\end{align}
so $\|A+B\| \le \|A\| + \|B\|$.
This matrix norm is not associated with any vector norm because for the identity matrix we have $\|I\| = \sqrt{n}$, and induced norms must satisfy $\|I\| = 1$.

The above discussion was for the norm $\|A\|_2 = [\operatorname{Tr}(A^TA)]^{1/2}$. This is about the norm $\|A\|_1 = \operatorname{Tr}[(A^TA)^{1/2}] =  \operatorname{Tr}|A|$ where $|A| = (A^TA)^{1/2}$.
Lemma $1$

For any matrix $A$ and two orthonormal bases $E = \{e_1, \ldots, e_n\}$ and $F = \{f_1, \ldots, f_n\}$ we have
  $$\sum_{i=1}^n \|Ae_i\|^2 = \sum_{i=1}^n \|Af_i\|^2$$
  In particular we have $\|A\|_2^2 = \sum_{i=1}^n \|Ae_i\|^2$.

Proof.
$$\sum_{i=1}^n \|Ae_i\|^2 = \sum_{i=1}^n \sum_{j=1}^n |\langle Ae_i, f_j\rangle|^2 =  \sum_{i=1}^n \sum_{j=1}^n |\langle e_i, A^Tf_j\rangle|^2 = \sum_{j=1}^n \|A^Tf_j\|^2$$
Applying this to $F$ and $F$ gives $\sum_{j=1}^n \|Af_j\|^2 = \sum_{j=1}^n \|A^Tf_j\|^2$ which completes the proof.
Let $G = \{g_1, \ldots, g_n\}$ be the orthonormal basis in which $A^TA$ diagonalizes with $A^TAg_i = \lambda g_i$. We have $$\|A\|_2^2 = \operatorname{Tr}(A^TA) = \sum_{i=1}^n \lambda_i = \sum_{i=1}^n \langle A^TAg_i, g_i\rangle = \sum_{i=1}^n \|Ag_i\|^2$$
Lemma $2$

For any positive matrix $A$ and two orthonormal bases $E = \{e_1, \ldots, e_n\}$ and $F = \{f_1, \ldots, f_n\}$ we have
  $$\sum_{i=1}^n \langle Ae_i, e_i\rangle = \sum_{i=1}^n \langle Af_i, f_i\rangle $$
  In particular, for any matrix $A$ we have $\|A\|_1 = \sum_{i=1}^n \langle |A|e_i, e_i\rangle = \||A|^{1/2}\|_2^2$.

Proof.
It follows from Lemma $1$:
$$\sum_{i=1}^n \langle Ae_i, e_i\rangle = \sum_{i=1}^n \|A^{1/2}e_i\|^2 = \sum_{i=1}^n \|A^{1/2}f_i\|^2 = \sum_{i=1}^n \langle Af_i, f_i\rangle$$
Let $G = \{g_1, \ldots, g_n\}$ be the orthonormal basis in which $|A|$ diagonalizes with $|A|g_i = \lambda_i g_i$. We have
$$\|A\|_1 = \operatorname{Tr}|A| = \sum_{i=1}^n \lambda_i = \sum_{i=1}^n \langle |A|g_i, g_i\rangle = \sum_{i=1}^n \||A|^{1/2}g_i\|^2 = \||A|^{1/2}\|_2^2$$
To prove the triangle inequality for $\|\cdot\|_1$ for the matrices $A$ and $B$, let $A = V|A|$, $B = W|B|$ and $A+B = U|A+B|$ be the respective polar decompositions, with $V,W,U$ unitary.
For any orthonormal basis $\{e_1,\ldots, e_n\}$ we have
\begin{align}
\|A+B\|_1 &= \sum_{i=1}^n \langle |A+B|e_i, e_i\rangle\\
&= \sum_{i=1}^n \langle U^*(A+B)e_i, e_i\rangle\\
&= \sum_{i=1}^n \langle (A+B)e_i, Ue_i\rangle\\
&= \sum_{i=1}^n \Big(\langle Ae_i, Ue_i\rangle + \langle Be_i, Ue_i\rangle\Big)\\
&= \sum_{i=1}^n \Big(\langle V|A|e_i, Ue_i\rangle + \langle W|B|e_i, Ue_i\rangle\Big)\\
&= \sum_{i=1}^n \Big(\langle |A|e_i, V^*Ue_i\rangle + \langle |B|e_i, W^*Ue_i\rangle\Big)\\
&= \sum_{i=1}^n \Big(\langle |A|^{1/2}e_i, |A|^{1/2}V^*Ue_i\rangle + \langle |B|^{1/2}e_i, |B|^{1/2}W^*Ue_i\rangle\Big)\\
&\le \left(\sum_{i=1}^n \||A|^{1/2}e_i\|^2\right)^{1/2}\left(\sum_{i=1}^n\||A|^{1/2}V^*Ue_i\|^2\right)^{1/2} + \left(\sum_{i=1}^n \||B|^{1/2}e_i\|^2\right)^{1/2}\left(\sum_{i=1}^n\||B|^{1/2}W^*Ue_i\|^2\right)^{1/2}\\
&= \||A|^{1/2}\|_2^2 + \||B|^{1/2}\|_2^2\\
&= \|A\|_1 + \|B\|_1
\end{align}
Comment: Thanks for the answer! Could you please clarify if the norm mentioned in the first line is the trace of sqrt or sqrt of the trace? In my question I asked about the first variant, although you seem to mean the latter one.
Comment: @Swistack Yeah, I completely misunderstood the question. Have a look now, I have added a proof for the norm you originally intended.
Comment: thank you! I read your solution, but there still seems to be a mistake or misunderstanding. For example, you claim that $Tr(|A|)$ is sum of $\lambda_i$, but since $\lambda_i$ are eigenvalues of $A^TA$ and $|A| = (A^TA)^{1/2}$, then something seems to be wrong. Did you mean $\lambda_i$  to be the eigenvalues of |A|?
Comment: @Swistack Yes, $\lambda_i$ should be the eigenvalues of $|A|$, thanks for pointing out.
Comment: @mechnodroid Thanks! Now it's much more clear. Do you know if this matrix norm is induced by any vector norm?
Comment: @Swistack There was another error here. $\|\cdot\|_2$ norm of unitary operators is $\|U\|_2 = \sqrt{\operatorname{Tr}(U^*U)} = \sqrt{n}$, and not $1$. However, for an orthonormal basis $\{e_1, \ldots, e_n\}$ we have
$$\|AU\|_2^2 = \sum_{i=1}^n \|AUe_i\|^2 = \|A\|_2^2$$
because then $\{Ue_1, \ldots, Ue_n\}$ is also an orthonormal basis.
Comment: And again, $\|\cdot\|_1$ is not induced by any vector norm because $\|I\|_1 = \operatorname{Tr}|I| = \operatorname{Tr}I = n$.
Answer: By padding the matrices with zeroes, we may assume that they are square. For any real square matrix $X$, let $X=USV^T$ be its singular value decomposition. Since $S$ is a nonnegative diagonal matrix and the diagonal entries of every real orthogonal matrix $W$ are bounded above by $1$, we have $\operatorname{tr}(S)=\max_{W^TW=I}\operatorname{tr}(SW)$. In turn, we have the following characterisation of the nuclear norm:
$$
\|X\|:=\operatorname{tr}\left((X^TX)^{1/2}\right)
=\operatorname{tr}(S)
=\max_{W^TW=I}\operatorname{tr}(SW)
=\max_{Q^TQ=I}\operatorname{tr}(XQ).
$$
Now the triangle inequality follows directly:
$$
\|A+B\|
=\max_{Q^TQ=I}\operatorname{tr}\left((A+B)Q\right)
\le\max_{Q^TQ=I}\operatorname{tr}\left(AQ\right)
+\max_{Q^TQ=I}\operatorname{tr}\left(BQ\right)
=\|A\|+\|B\|.
$$
Comment: Oh, I thought this was a new question, but actually someone bumped it up.


remove part of a string using PHP

Question: i have this PHP Code:
$sql="SELECT * from project_gallery where sequence = '".$_POST["project_sequence"]."' ";
    $rs=mysql_query($sql,$conn);
    $project=mysql_fetch_array($rs);

    $images = explode(',',$project['images']);

    $images = "," . $images . ","; // add comma to beginning and end of list

    foreach ($images_to_delete as $image_to_delete)
    {
        str_replace("," . $image_to_delete . ",", ","); // e.g. replaces ",image1.jpg," with ","
    }

    $images = substr($images, 1, -1); // remove comma from beginning and end

    echo $images;

i want to be able to remove the selected (in the previous HTML Form) part of a string from a cell in my MySQL Table.
in my table my image filenames are stored like:
[image1.jpg],[image2.jpg],[image3.jpg],[image4.jpg] etc...
so if the checkbox for image2.jpg is checked and the form is submitted, i want to make the string look like:
`[image1.jpg],[image3.jpg],[image4.jpg]`

here is my HTML Form too:
<?php
$sql="SELECT * from project_gallery where sequence = '".$_GET["project"]."' ";
    $rs=mysql_query($sql,$conn);
    $project=mysql_fetch_array($rs);

    $images = explode(',',$project['images']);
    ?>
    <form action="edit.php?project=<?php echo $_GET["project"]; ?>" method="post" enctype="multipart/form-data">

            Project Name

            <input type="text" name="project_name" value="<?php echo $project["name"]; ?>" style="width:100%;" />

            Add New Images
<input type="file" name="images[]" multiple="multiple" />

        <?php
        foreach($images as $image)
        {
            $display_image = substr($image, 1, -1);
            ?>

                <img src="/img/project-gallery/<?php echo $display_image; ?>" width="160px" />

                <input type="checkbox" name="images_to_delete[]" id="images_to_delete[]" value="<?php echo $display_image; ?>" />

            <?php
        }
        ?>

            <input type="text" name="project_sequence" id="project_sequence" value="<?php echo $project["sequence"]; ?>" />
            <input type="submit" name="submit" id="submit" value="Save Project" />

    </form>

Comment: **By building SQL statements with outside variables, you are leaving yourself wide open to SQL injection attacks.**  Also, any input data with single quotes in it, like a name of "O'Malley", will blow up your SQL query. Please learn about using parametrized queries, preferably with the PDO module, to protect your web app.  http://bobby-tables.com/php has examples to get you started, and [this question](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) has many examples in detail.
Answer: You can use PHP string replace (or something similar) to create your new string
$newList = str_replace($selectedEntry, '', $imageList);

then you can run a mysql UPDATE command to update that record in the database.
$sql = "UPDATE table_name SET column_name = '$newList' WHERE id = $id";

That said, you should probably not be doing what you're doing.  You don't want to have to manipulate records like that typically.  I would recommend having another table with all the image data (imageID, imageName, etc) and then inserting and removing whole rows into that table.  There are more efficient/complicated ways of doing things, but if you end up having to make a list via a string/text/varchar field in the database you're probably not doing something right.
edit:
Get the previous checked entries:
$(function () {
  $('#target').click(function () {
    var checkValues = $('input[name=checkboxlist]:checked').map(function() {
        return $(this).parent().text();
    }).get();
    //do something with your checkValues array
   });
});

Comment: i cant get the variables to work right - no data is being returned. the whole site has been coded like this and would take me ages to re code it all lol
Comment: Yeah as Andy said above, you really shouldn't be directly putting variables directly into queries like this, you should be parametrizing/serializing your queries so user-generated data is never directly inserted into your database.
Comment: you should be able to make a new list using str_replace like above.  Have you tried that?  What does print $newList return?
Comment: im not sure what to replace $selectedEntry and $imageList with in your example above
Comment: $imageList is your original string of images '[image1][image2][image3]' and $selectedEntry is the one you want removed '[image2]'
Comment: so i have this on my form submit page: $sql="SELECT * from project_gallery where sequence = '".$_POST["project_sequence"]."' ";
 $rs=mysql_query($sql,$conn);
 $project=mysql_fetch_array($rs);

 $images = explode(',',$project['images']);

 $newList = str_replace($selectedEntry, '', $images);
 echo $newList;
Comment: but im not sure how to get the $selectedEntry?
Comment: also, if more than one checkbox is checked how would i make it do all the checked ones?
Comment: you can get the $selectedEntry from your previous HTML form you alluded to.
Answer: You're doing it way too hard. Using PHP's builtin functions, e.g. array_diff(), results in code that is much more concise and (usually) performs better:
Example: I'm assuming $project is a row fetched from a query result, and $images_to_delete is an array. The result is a single string, containing the new list of images you want to keep.
Also I show usage of PDO, which is safer and easier than the deprecated ext/mysql functions.
$sql="SELECT * from project_gallery where sequence = ?";
$stmt = $pdo->prepare($sql)
  or trigger_error($pdo->error, E_USER_ERROR);
$stmt->execute(array($_POST["project_sequence"]))
  or trigger_error($pdo->error, E_USER_ERROR);
while ($project = $stmt->fetch(PDO::FETCH_ASSOC) { }

$images = explode(",", $project["images"]);
$images = array_diff($images, $images_to_delete);
$images = implode(",", $images);
echo $images . "\n";

Then remove the rest of your code:

$images = "," . $images . ","; // add comma to beginning and end of list
  foreach ($images_to_delete as $image_to_delete)
  {
      str_replace("," . $image_to_delete . ",", ","); // e.g. replaces ",image1.jpg," with ","
  }
  $images = substr($images, 1, -1); // remove comma from beginning and end
  echo $images;
Comment: see my edit on your question - i am getting the error: Warning: Invalid argument supplied for foreach() in /home/jrrevell/public_html/add_project/edit.php on line 23
Comment: Please edit your own question if you need to show new code you tried. Don't edit people's answers.

remove part of a string using PHP


Reloading webbrowser when screen rotates

Question: I have an application, and in this app I have a simple webbrowser where it opens a login page ( http://portaldopatchwork.klickmembersproject.com.br/login ) , so... after I login in the web page, if I rotate the screen, the webbrowser returns to the login page, I would like to know why? I would like my app could rotate normaly in webbrowser , without returns to login page...
Thanks for now...
Answer: When configuration changes happen the activity is recreated, so if you are opening the login page in a method such as onCreate it will navigate to the login page when you rotate your screen as onCreate will be called again.
Here is some useful documentation
Answer: Since you added xamarin as a tag I am assuming you are doing this in a Xamarin app.
In Xamarin, you can prevent this behavior by putting an attribute on your Activity, stating that you will deal with orientation changes yourself. It works like this (the ConfigurationChanges part is important):
[Activity(Label = "...", Icon = "@drawable/icon", MainLauncher = true,
    ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity {
    // ...
}

When you set this flag like above, your activity will not be restarted when the screen size or orientation changes. See the Xamarin documentation on Preventing Activity Restart.


Inside Panelizer, is there a trick to formatting image fields?

Question: Summary
In Panelizer, I have created one Panel. In Content for this panel there is an image field. I can find no option to change the image style.
From Manage Display in the content type,  I am able to select Image Style for various display settings but this makes no difference to the image in the Panel in Panelizer.
Where am I not looking?
Details
In Panelizer for Content Type = (Person), first row on the left "Full Page override" I clicked "Panelize" and "Provide Default Panel". I think I have created one Panel. In the Content for this panel, I have placed an image field (field_person_image) in the right column.
In Panelizer on R of field_person_image is a gear listing-
-"Settings". Formatter options for can select This Node, override title, change label position. There is an option for "Select a formatter" but the only option is "Image". There is no option to change the image style.
-Style which offers Pane Style for this node (rounded corners)
-Visibility rules
-Locking
-Caching
In Structure > Content Type > Person > Manage Display,  I am able to select Image Style for various display settings. Changing from Large to Medium to Small (using Default, Full Content) makes no difference to the image in the Default Panel in Panelizer.
This similar sounding question also has no answer. Using Image 7.43. There are no results at Issues for Drupal Core (Drupal.org) about Panelizer and image formatting.
What am I missing?
Answer: Although I could swear that I had done this before, I deleted the image in the panel. This time, when I added the image back into the panel, I got image formatter options. Which I set, and the node behaved correctly.
Despite the frustratingly long time I worked on this, it was a non-problem!
AMENDMENT:
When the panel is first created and saved, all of the fields appear in the panel. If the image field is left as is, there are no formatter options. However, if the image field is deleted from the panel and then re-added, then the formatter options appear. This is noteworthy, I think.