Ask the detail of Neyman-Pearson Lemma (Necessity Part)

Question: This is Theorem 8.3.12 (Neyman-Pearson Lemma) in George Casella stat inference. Consider testing $H_0: \theta=\theta_0$ versus $H_1: \theta=\theta_1$, where the pdf pr pmf corresponding to $\theta_i$ is $f(\textbf{x}|\theta_i),i=0,1.$, using a test with rejection region R that satisfies (8.3.1)
\begin{align}
\begin{matrix}
x\in R & \text{if}& f(\textbf{x}|\theta_1)>kf(\textbf{x}|\theta_0)\\
x\in R^c & \text{if} & f(\textbf{x}|\theta_1)<kf(\textbf{x}|\theta_0)
\end{matrix}\tag{8.3.1}\label{8.3.1}
\end{align}
for some $k \geq 0$, and
\begin{align}
\alpha=P_{\theta_0}(\textbf{x}\in R)\tag{8.3.2}\label{8.3.2}
\end{align}
Then (Sufficiency): Any test that satisfies the above is a UMP level $\alpha$ test.
(Necessity): If there exists a test satisfying (8.3.1) and (8.3.2) with k >0, then every UMP level $\alpha$ test is a size $\alpha$ test (satisfies (8.3.2)) and every UMP level $\alpha$ test satisfies (8.3.1) except perhaps on a set A satisfying $P_{\theta_0}(\textbf{x}\in A)=P_{\theta_1}(\textbf{x}\in A)=0.$
I feel difficulty to understand this Necessity. In the proof, it is clear that any test satisfying (8.3.2) is a  size $\alpha$ test. So I don't know why in the Necessity part, we say it again:

If there exists a test satisfying (8.3.1) and (8.3.2) with k >0, then
every UMP level $\alpha$ test is a size $\alpha$ test (satisfies
(8.3.2))

. And the expressions are different. It says we need to satisfy (8.3.1) and (8.3.2). But don't the truth be we only need to satisfy (8.3.2)?
Comment: @OliverDiaz I am sorry. I tried to see your answer this morning, but then it showed you deleted the answer. Now I am starting to see your answer.
Comment: @OliverDiaz Thank you. I am still seeing your solution and have asked you 2 questions in chat.
Answer: Before trying sketching any arguments, let me introduce some notation and remarks.
Let $T_*(x)$ denote the test described by $(8,3,1)$, that is
\begin{align}
T_*(x)=\left\{\begin{matrix}
1& \text{if}& f(\textbf{x}|\theta_1)>kf(\textbf{x}|\theta_0)\\
\gamma &\text{if} & f(\textbf{x}|\theta_1)=kf(\textbf{x}|\theta_0)\\
0 & \text{if} & f(\textbf{x}|\theta_1)<kf(\textbf{x}|\theta_0)
\end{matrix}
\right.
\end{align}
where $k$ and $\gamma$ is taken so that
$$E_{\theta_0}[T_*(X)]=P_{\theta_0}\big[f(X|\theta_1)>k f(X|\theta_0\big]+\gamma P_{\theta_0}\big[f(X|\theta_1)=k f(X|\theta_0)\big]=\alpha
$$
Notice that The function $t\mapsto P_{\theta_0}[f(X|\theta_1)>t f(X|\theta_0)]$ is positive, monotone nonincreasing and right continuous, so such $k$ and $\gamma$ exists and are unique. If one is dealing with continuous distributions, then the bit $\gamma P_{\theta_0}\big[f(X|\theta_1)=k f(X|\theta_0)\big]$ does not appear.
To show necessity, that is, that any UMP test $T_u(x)$ at level $\alpha$ satisfies $T_u(x)=T_*(x)$ in $\{x:f(x|\theta_1)\neq f(x|\theta_0)\}$, we should understand first what is so special about $T_*(X)$. Once this is established, necessity follows from some basic  measure theoretic arguments that I will only explain towards the end of my answer.

First we reproduce the arguments that show why $T_*(x)$ is a UMP at level $\alpha$, that is, we show that for any other test $T(x)$  with  $E_{\theta_0}[T(X)]\leq\alpha$, we have that $E_{\theta_1}[T_*(X)]\geq E_{\theta_1}[T(X)]$.
Here is more or less how the argument works.
Let $T(x)$ by any other test with power at most $\alpha$, that is $E_{\theta_0}[T(X)]\leq\alpha$. Recall that tests take only values between $0$ and $1$. Notice  that:

If $T_*(x)-T(x)>0$, then $T_*(x)>0$ (for $T(x)\geq0$  for all $x$); hence $f(\textbf{x}|\theta_1)\geq kf(\textbf{x}|\theta_0)$.
If $T_*(x)-T(x)<0$, then $T_*(x)<1$ (for $T(x)\leq1$ for all $x$); hence $f(\textbf{x}|\theta_1)\leq kf(\textbf{x}|\theta_0)$.

This means that
$$
\big(T_*(x)-T(x)\big)\big(f(x|\theta_1)-kf(x|\theta_0)\big)\geq0
$$
for all $x$. Integration gives
\begin{align}
\int_X\big(T_*(x)-T(x)\big)\big(f(x|\theta_1)-kf(x|\theta_0)\big)\,dx\geq0
\end{align}
simplifying the expression on the left-hand side gives
\begin{align}
E_{\theta_1}[T_*(X)-T(X)]&=\int_X\big(T_*(x)-T(x)\big)f(x|\theta_1)\,dx\\
&\geq
k\int_X (T_*(x)-T(x)\big)f(x|\theta_0)\,dx=kE_{\theta_0}[T_*(X)-T(X)]\\
&=k\big(\alpha-E_{\theta_0}[T(X)]\big)\geq0
\end{align}
Hence
$$ E_{\theta_1}[T_*(X)]\geq E_{\theta_1}[T(X)]$$
In other words, $T_*$ is more powerful that $T$.

Observation: The key parts of the argument above  are contained  (1) and (2).

We are now ready to argue for necessity, that is, that any test $T_u$ that is UMP at level $\alpha$, must be equal to $T_{*}(X)$ in $\{x: f(x|\theta_1)\neq k f(x|\theta_0)\}$.
Suppose now that that $T_u$ is another UMP of power $\alpha$; that is
$E_{\theta_0}[T_u(X)]=\alpha$, and $E_{\theta_1}[T_u(X)]\geq E_{\theta_1}[T(X)]$ for any other feasible test $T$. Then, since $T_*(X)$ is UMP, we must have that $E_{\theta_1}[T_*(X)]=E_{\theta_1}[T_u(X)]$.
Consider the set
$$ A:=\{x:T_*(x)\neq T_u(x)\}\cap\{x:f(x|\theta_1)\neq k f(x|\theta_0)\}$$
The arguments used in (1) and (2) imply that
\begin{align}
\begin{matrix}
\big(T_*(x)-T_{u}(x)\big)\big(f(x|\theta_1)-k f(x|\theta_0)\big)>0&\text{if} &x\in A\\
\big(T_*(x)-T_{u}(x)\big)\big(f(x|\theta_1)-k f(x|\theta_0)\big)=0&\text{if} &x\in X\setminus A
\end{matrix}
\end{align}
Integration gives
\begin{align}
\int_A\big(T_*(x)-T_{u}(x)\big)\big(f(x|\theta_1)-k f(x|\theta_0)\big)\,dx
&=\int_X\big(T_*(x)-T_{u}(x)\big)\big(f(x|\theta_1)-k f(x|\theta_0)\big)\,dx\\
&=E_{\theta_1}[T_*(X)-T_{u}(X)]-k E_{\theta_0}[T_*(X)-T_{u}(X)]\\
&=0
\end{align}
Since $\big(T_*(x)-T_{u}(x)\big)\big(f(x|\theta_1)-k f(x|\theta_0)\big)>0$ for all $x\in A$, then it must be that $A$ is negligible (i.e. $\int_A\,dx=0$). Therefore $P_{\theta_0}(A)=P_{\theta_1}(A)=0$, that is $T_*(X)=T_{u}(X)$ $\{P_{\theta_1},P_{\theta_0}\}$-almost surely.

The last bit is based on a couple of basic measure theory facts:

If $f\geq0$ and $\int f\,d\mu=0$, then $\mu(\{x:f(x)>0\})=0$. That is $f$ must be $0$ almost surely (with respect to the measure $\mu$).
If $\mu$ is a finite  measure with a density function  respect to another ($\sigma$-finite) measure $\nu$, then $\nu(A)=0$ implies that $\mu(A)=0$. (this is related to a deep result called Radon-Nikodym theorem).
Comment: At the very beginning, to find out $\gamma$, I think the notation should also include $E_{\theta_0, \theta_1}[T_*(X)]$, and also $P_{\theta_0, \theta_1}$.
Comment: But at the very beginning, we don't know $\alpha$ is just the lever. We only know $\alpha$ is the the expectation of $T_*(X)$, which is in terms of $\theta_0, \theta_1$.
Comment: @Mariana: Basically the whole problem of hypothesis testing is to find a test $T(X)$ that solves the following optimization problem:
\begin{align}
T^*&=\operatorname{arg}\sup_{\theta\in\Theta_1}E_{\theta}[T(X)]\\
&\quad\text{subject to}\\
&\sup_{\theta_0}E_{\theta_0}[T(X)]\leq\alpha
\end{align}
Comment: "First we reproduce the arguments that show why $T_*(x)$ is a UMP at level $\alpha$, that is, we show that for any other test $T(x)$  with  $E_{\theta_0}[T(X)]\leq\alpha$," Can you explain why the test is of level $\alpha$ is equivalent to saying $E_{\theta_0}[T(X)]\leq\alpha$? I only know a test with power function $\beta(\theta)$ is a level $\alpha$ test if $sup_{\theta \in \Theta_0}  \beta(\theta) \le \alpha$
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/122966/discussion-between-mariana-and-oliver-diaz).


Is there a way to use a PowerPoint presentation in a node?

Question: I've been spending a lot of time trying to find a solution to play a PowerPoint in a node. Converting the file to SWF won't work for me since I need this to also play on mobile. Third-party upload doesn't work either because more than one person will be using this, and we don't want to have any liability in sharing the files to public this needs to be private. This is also why Google docs don't work.
It is crazy that there is no module that will play a PPT on Drupal, being PPT so easy.
Please I need a light here. I'm not a pro in Drupal, and I only have access to the Drupal dashboard. I can't fix any PHP or files either.
Answer: Try using https://www.drupal.org/project/gdoc_field and field on node to upload and display powerpoint presentation.


Do these two functions both create collections of Classes?

Question: I've written a piece of code in C# that can create a collection of Classes and stores them all in an array. I know that code works and does the job fine and I've been using it to store results from a database to display.
Now I need to replicate the same behaviour using VB.NET and after some Google-ing it appears I've found the closest solution.
I've run the C#code through a translator (C# to VB.NET) but that did not give me the correct result and produced an error when placed inside my collection class.
Here's the code:-
C#
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace KnightOwl_BusinessLogic.DataObjects.Animal_Module
{
    public class AnimalCollection : Collection<Animal>
    {
        public Animal[] ToArray()
        {
            Animal[] array = new Animal[this.Count];
            this.CopyTo(array, 0);
            return array;
        }
    }

}

VB.NET:
Imports System.Collections.Generic
Imports System.Collections
Imports System.Collections.ObjectModel

Namespace DataModels

    Public Class VisitorListCollection

        Public VisitorList As New Collection

        Private Sub addVisitor()
            Dim tempVisitor As New Visitor()
            VisitorList.Add(tempVisitor)
        End Sub

    End Class

End Namespace

It all builds with no errors but I'm just not convinced it going to be doing the same job.
Comment: These two pieces of code seems to be totally unrelated. Could you clarify your problem? At least for me, it's not clear at all
Comment: That's not the same code. I can't imagine any translator turning that c# snippet into that vb snippet.
Comment: Basically I need the VB code to be doing the same as the C# code but with Visitors instead of Animals - I have a visitor class for a singular visitor but am trying to put something place for when multiple visitors need to be displayed instead of one - I've managed to do this in C# using the above code but not in VB.NET - and I was wondering if the VB.NET code above would create a collection of of the Visitor class?
Comment: In your first sample, the Collection class already has a [ToArray](https://msdn.microsoft.com/en-us/library/bb298736(v=vs.110).aspx). Why are you creating your own?  Your two sample are very different, one get an array, the other add to a list...
Answer: Your C# code creates a fixed size array of items. Your VB.Net code creates a list of items. They are both 'collections' but the VB.Net example creates a collection that you can add more items to. This may or may not be what you want.


Angular currency: Expected '€ 3,14' to equal '€ 3,14'. Why are these unequal?

Question: I wrote unit tests for an angular filter that makes use of angular's currency filter, and somehow all unit tests are failing, despite the fact that the actual strings it's comparing are identical.
What could be causing this?
Another filter that does something very similar but without using angular's currency filter works fine. Does the currency filter put some weird symbols in the string that can't be detected by the naked eye? How do I figure this out?
Comment: show your code please
Comment: We have absolutely no idea what you are comparing code wise, or even if the data exists when you are comparing. Where's your code?
Comment: I'm comparing the output of, ultimately, the currency filter, to a string that looks identical to it. The data is clearly there (as shown in the title). The issue is really nothing more than: "does the currency filter put anything funny in its output?" Fortunately @JB Nizet got it in one.
Answer: AngularJS uses a non-breaking space between the amount and the currency (in your locale at least). Replace your code with
<code>expect(formattedValue).toBe('€\u00a03,14');
</code>
Comment: Thanks! That is exactly what I needed to know.
Comment: This solution is still working in angular 4 when using the CurrencyPipe


Chocolatey no Windows Powershell

Question: Eu estou tentanto usar os comandos nativos do windows Powershell para instalar os pacotes do Chocolatey porém quando uso um comando como Get-ChocolateyVersion recebo a mensagem de erro:

C:\Program Files\WindowsPowerShell\Modules\chocolatey\0.0.48\Chocolatey.psm1:1597 caractere:9
  +         Throw "Chocolatey Software not found

Porém o arquivo existe e está instalado no caminho correto exceto que minha máquina é em pt-br logo a pasta é "Arquivos de Programas" e  não Program Files.
Porém já tentei mudar a variável de ambiente pra apontar para a pasta correta mas não adianta nada assim que executa o comando ele cai no mesmo erro.
Eu tentei:
$env:ProgramFiles = "C:\Arquivos de Programas"

Set-Variable -Name ProgramFiles -Value "C:\Arquivos de Programas"

Em ambos os casos se eu fizer echo $env:ProgramFiles ele imprime o valor que eu coloquei mas se eu executar o comando Get-ChocolateyVersion ele aponta novamente pra o caminho errado.
Answer: Confirme que existe uma variável de sistema chamada ChocolateyInstall e que o seu valor é o caminho correcto para a pasta onde o chocolatey está instalado.
Exemplo:
$env:ChocolateyInstall = "%ProgramData%\chocolatey"

Comment: fiz no meu ambiente aqui mais nao retornou nada, como eu sei que se encontra install?

Chocolatey no Windows Powershell


How do I enable apache modules from the command line in RedHat?

Question: How do I enable apache modules from the command line in RedHat?
On Debian/Ubuntu systems I use a2enmod to enable modules from the command line.
Is there an equivalent for RedHat/CentOS type systems?
Answer: There is no equivalent.
Debian/Ubuntu butcher the apache configuration into a large number of files, where directories of mods and sites enabled are symlinked to other snippets of configuration files. The a2enmod/a2ensite scripts just manipulate these symlinks.
debian$ ls /etc/apache2/mods-enabled
lrwxrwxrwx 1 root root 28 2009-03-12 18:02 alias.conf -> ../mods-available/alias.conf
lrwxrwxrwx 1 root root 28 2009-03-12 18:02 alias.load -> ../mods-available/alias.load
lrwxrwxrwx 1 root root 33 2009-03-12 18:02 auth_basic.load -> ../mods-available/auth_basic.load
lrwxrwxrwx 1 root root 33 2009-03-12 18:02 authn_file.load -> ../mods-available/authn_file.load
lrwxrwxrwx 1 root root 36 2009-03-12 18:02 authz_default.load -> ../mods-available/autoindex.load
lrwxrwxrwx 1 root root 26 2009-03-12 18:02 env.load -> ../mods-available/env.load
lrwxrwxrwx 1 root root 27 2009-03-12 18:02 mime.conf -> ../mods-available/mime.conf
lrwxrwxrwx 1 root root 27 2009-03-12 18:02 mime.load -> ../mods-available/mime.load
lrwxrwxrwx 1 root root 34 2009-03-12 18:02 negotiation.conf -> ../mods-available/negotiation.conf
lrwxrwxrwx 1 root root 34 2009-03-12 18:02 negotiation.load -> ../mods-available/negotiation.load
lrwxrwxrwx 1 root root 27 2009-06-16 21:47 php5.conf -> ../mods-available/php5.conf
lrwxrwxrwx 1 root root 27 2009-06-16 21:47 php5.load -> ../mods-available/php5.load

On redhat systems the apache configuration is by default held in one file /etc/httpd/conf/httpd.conf. All modules are loaded from this file, and can be disabled by commenting out the appropiate LoadModule statement.
...
LoadModule authz_default_module modules/mod_authz_default.so
LoadModule ldap_module modules/mod_ldap.so
LoadModule authnz_ldap_module modules/mod_authnz_ldap.so
LoadModule include_module modules/mod_include.so
LoadModule log_config_module modules/mod_log_config.so
LoadModule logio_module modules/mod_logio.so
LoadModule env_module modules/mod_env.so
LoadModule mime_module modules/mod_mime.so
LoadModule dav_module modules/mod_dav.so
...

What RedHat/CentOS are doing is giving you a pretty stock apache setup, while debian are adding their own "improvements". You could of course use the debian split config system as a template to make your own, and copy the scripts. However, the main argument for the debian setup is so that apache module packages can install their own config files, so without that it's significantly less useful

Edit: If you're looking for an equivalent way of scripting this then i suggest you use /etc/httpd/conf.d directory, any config files in here will be included. Depending on how complicated the script is it might make sense to directly write one line files into conf.d, or use symlinks for more complicated bits.
Comment: Ten years later comment, on RHEL/CentOS 7 at least, you need to check in `/etc/httpd/conf.modules.d`
Comment: I'm not sure why everyone is harshing on your answer; it correctly describes why one will not find the a2enmod scripts in Red Hat-alikes.  Personally, my plan is to use puppet to manage a similar layout on my RHEL boxes.
Comment: @womble - I think debian have taken the tiny files stuff too far, having an entire file for just setting what ports apache should listen on for example, and I think that shell scripts just to make a symlink are also a step too far - to the point where they confuse users who don't understand how their config files actually work. I wouldn't call that bitter.
Comment: So what do i do in my new server build scripts?

awk/sed craziness?  Create my own config files and copy them in to place?

None of these options sound appealing.
Answer: Command to enable multiple modules
sudo a2enmod headers http2 proxy_fcgi rewrite setenvif ssl ...

and command to disable multiple modules
sudo a2dismod headers http2 proxy_fcgi rewrite setenvif ssl ...

Comment: a2enmod and a2dismod commands are for Debian/Ubuntu systems.
Answer: yum list mod\*

install modules that you want
for example mod_perl
rpm -ql mod_perl.x86_64 | grep /etc/

/etc/httpd/conf.d/perl.conf
/etc/httpd/conf.modules.d/02-perl.conf

edit /etc/httpd/conf.d/perl.conf to enable it
By default, all mods are loaded when are installed, if you want not load someone
edit file in /etc/httpd/conf.modules.d/02-perl.confand comment Load line with hash sign (#)
Comment: This is the perfect answer to the Question. 'Enable' is different from 'LoadModule'.
Answer: Typically, on a Redhat system, you'll find a line that looks like this inside /etc/httpd/conf/httpd.conf:
Include conf.d/*.conf
When you copy a configuration file into /etc/httpd/conf.d, and it has a .conf file extension, then it'll be picked up and processed as apache starts. You'll typically find configuration files for extensions like mod_php and mod_svn, and applications that are integrated with the webserver like trac, inside this folder.
Side note: for apache modules like mod_php or mod_auth_mysql on other systems that use RPM, like OpenSuSE, there may be other configuration files (like /etc/sysconfig/apache2) that need to get edited in order for apache to pick up a new module. Some of this is dependent on the system management tool that is being used, i.e. yast2. Some of it's dependent on aftermarket products that can be installed, like plesk/cpanel. However, the above folder is the best place to start.
Comment: For anyone working with Fedora 21 (and possibly other versions or other RH family distros) the module loading has been moved to a new directory called /etc/httpd/conf.modules.d/. You will see the following line in your httpd.conf `Include conf.modules.d/*.conf` if that is the case.
Comment: And how do we enable modules here? For example for `mod_socache_shmcb` would I create a file in `/etc/httpd/conf.modules.d` like `00-socache_shmcb.so` and in that file write `LoadModule socache_shmcb_module modules/mod_ssl.so`??
Answer: 'Enable' Modules is different from "LoadModules" and Install

If already Installed and is offline, root user can service enable httpd
If modules and their conf files are not available then,  root user    can yum install -y <mod_name>
check the availability with yum list mod\*
If already enabled and installed, to load them to use draft it httpd.conf or *.conf files, as
LoadModule ldap_module modules/mod_ldap.so
To Verify, if Loaded correctly and ready in use, apachectl -M


Problema ao ler arquivo

Question: Estou escrevendo um código em C++ e preciso ler um arquivo de distâncias que foi calculado em um outro algoritmo feito em C.
Este arquivo é mais ou menos assim:
100\n (número natural)
0.0000 58.25646 7.1556 \n5.1564 0.0000 44.00000...   -> uma matriz de floats
Segue o código da parte que lê o arquivo:
int main(){
    srand(time(NULL));

    FILE *arv;
    arv = fopen("distancias_oliver30.txt", "r");

    fscanf(arv,"%d", &N_geracoes);

    float distancias[N_cidades][N_cidades];
    float feromonio[N_cidades][N_cidades];

    int i, j, k;
    for (i = 0; i < N_cidades; i++){
        for (j = 0; j < N_cidades; j++){
            fscanf(arv,"%d",&distancias[i][j]);

    }

    fclose(arv);
    ...

O problema é que o esse primeiro número natural ele lê corretamente, mas o nas distancias ele lê o primeiro elemento corretamente e o resto ele bota um número negativo esquisito (-107374176) ao invés de 58.25646, 5.1564...
Alguém sabe como resolver?
Answer: Assumindo esta declaração:
float distancias[N_cidades][N_cidades];

Isso está errado:
fscanf(arv,"%d",&distancias[i][j]); // ERRADO!

Este é o jeito certo de ler floats:
fscanf(arv,"%f",&distancias[i][j]); // CERTO :)

Comment: Puts... que erro idiota. Muito obrigado :))))))))))))))

Problema ao ler arquivo


How to remove one letter in Jlabel on button click?

Question: String k=jLabel2.getText();// getting text eg=abcd
int kl=k.length()-1;  // get k's length and remove one letter ,
I need to do this,
if jlabel.getText = ABCDE

and I want to remove E from ABCDE
eg=abcd to abc
Comment: please reformat this question and show us what you have tried. you will not be handed an answer
Comment: `jlabel.setText(k.subString(0,kl));`
Comment: what matt says and call revalidate on the frame ;)
Comment: @StimpsonCat I'm pretty sure setText takes care of repaint/validation.
Comment: Yes you are, i was not ;)
Answer: You need to get back the text, and then substring from the beginning to antepenultimate char :
String labeltext = jLabel2.getText();
jLabel2.setText(labeltext.substring(0, labeltext.length() - 1));

antepenultimate = the one before the last one
Comment: @Krishan I just want to remember you that a forum like this has people who wanted to answer to people like you because they got "thanks" from them with "accepting answers" or "vote up" and it seems that you did none one thme, so think about it please ;) If it helps :)


Ideas Surrounding the SIRS model

Question: We are working on the SIRS model in my physical analysis course, and I
want to prove that all solutions in the triangular region
$\Delta$ tend to the equilibrium point $(\tau,0)$ when the total
population doesn't exceed threshold level for the disease. I know
that when $\tau = \frac{v}{\beta},$ the two equilibria coalesce at
$(\tau,0).$ That being said, I am having some issues connecting
this idea to the behavior of $\Delta$ in the model. I think that
I may need some assistance on this problem. For reference, $\Delta$
is the region where $I,S \geq 0 \wedge S+I \leq \tau.$
Comment: I think you have to write the exact model and define all parameters. Also, what do you mean by "behaviour" of a region? Maybe you want to analyse bifurcations?
Answer: First notice that the $\Delta$ region is a positively invariant set. You can verify that analyzing the slope field at the boundary of $\Delta$. Expect to find no vector pointing outwards $\Delta$. So once a solution curve gets in $\Delta$ it never gets out.
You can better understand the behavior of the system near $(\tau, 0)$ by studying the linearized system around it. Therefore I suggest to linearize the system around $(\tau, 0)$ and rewrite it as a matrix differential equation.
Let A be the matrix of coefficients.
Consider the case when $\tau \lt \frac{v}{\beta}$.
Verify that A has two negative real eigenvalues. This means that the equilibrium point $(\tau, 0)$ for some neighborhood of itself behaves like a spiral sink (on a twisted fashion) and so it is asymptotically stable.
Now suppose that $\tau = \frac{v}{\beta}$.
Hence A no longer have a pair of negative real eigenvalues. Take a look at the direction field around the point $(\tau, 0)$. It no longer resembles any linear pattern we know. We would need a more refined technique solely to analyze this singularity.
Thus I will leave you with this question to reason:
What are the chances of finding an instance on the nature of the modeled phenomenon such that $\tau = \frac{v}{\beta}$ for all time?
(Bibliography: Hirsch, Smale, and Devaney, Differential Equations, Dynamical Systems, and an Introduction to Chaos (Edition: 2), Elsevier Science & Technology Books, 2004)

Ideas Surrounding the SIRS model


Monotouch.Dialog two tables

Question: I'm new to MonoTouch.
I need to display 2 tables and button between them in 1 view using monotouch.dialog.
It should looks like
---top of screen---
I BoolElement     I
I StringElement   I
I StringElement   I          <--- Yeah,yeah this is iPhone(in my Opinion)
I --empty space-- I
I button          I
I --empty space-- I
I StringElement   I
---End Of screen--

I have searched over an internet - But nothing similar to find. :(
The problem is to display last strigElement
Comment: Off-Topic: Nice ASCII-Phone, where can i buy it?
Answer: With MonoTouch.Dialog you can use something like:
    RootElement CreateRoot ()
    {
        var btn = new UIButton ();
        btn.TouchUpInside += delegate {
            Console.WriteLine ("touch'ed");
        };
        // TODO: customize button look to your liking
        // otherwise it will look like a text label
        btn.SetTitle ("button", UIControlState.Normal);
        Section s = new Section ();
        s.HeaderView = btn;
        return new RootElement (String.Empty) {
            new Section () {
                new BooleanElement ("bool", false),
                new StringElement ("s1"),
                new StringElement ("s2"),
                },
            new Section (),
            s,
            new Section () {
                new StringElement ("s3"),
            },
        };
    }

That will use a Section to add an UIButton inside the HeaderView. The same trick can be used to add any other kind of control.

Monotouch.Dialog two tables


How does one measure the interval between two pitches?

Question: What is the procedure for measuring the interval between two pitches?
How do I know if something is a fifth, sixth, or something else? Why, for instance, is C to D a second even though we only go up one note?
And how do I know if it the interval major, minor, or something else?
Lastly, I've heard people say that I shouldn't measure intervals by just counting half steps. Why is this a bad idea?
Comment: @ToddWilcox I was looking for a canonical answer to this question to refer to another user, but I couldn't find one. In chat I asked Dom if he knew of one, and he couldn't find a suitable one either. We thought that it would be helpful to have a thread dedicated to it that we could use at in the future as a reference.
Comment: Your previous activity on this stack makes me feel like you know this stuff already. Is that somehow not the case? Are you asking for someone else? Sorry to ask, I just find it odd.
Answer: First, I suggest looking this up in the Wikipedia but I'll go into it a bit.
Intervals are described using both endpoints, that is the notes spanned, like using "Ocho días" for "week" in Spanish. Thus the interval C-C is a unison; C-D is a second, C-E is a third, ... C-B is a seventh, and C-C (the next higher C) is an octave. It's a funny linguistic thing as the word unison (in most languages) refers to a single object. C-C contains 1 note. C-E can be considered as the C,D,E and thus is a third.
Second point, there are only 7 different letters used even though a chromatic scale has twelve notes.  C-D is a second though the note C# (or Db) is in between; E-F is also a second. The term "major" is used for a "nominal" second containing a two half steps; "minor" is used for a second containing a single half step. It's complicated because it grew over time and the various terms added gradually.
The rationale for having such a complicated nomenclature is that originally, the half and whole step intervals were not all equal. See the Wiki article on Temperament. The 8 nominal intervals spanning an octave have assigned ratios. In the table below, the ratio is of the second note to the first.
C-C is 1/1
C-D is 9/8
C-E is 5/4
C-F is 4/3
C-G is 3/2
C-A is 5/3
C-B is 15/8
C-C is 2/1
Unfortunately, these ratios cannot be extended exactly. There is a problem in that the ration of D to C is 9/8 but that of E to D is 10/9; these are close but not identical. Thus no consistent naming of intervals by frequency is possible with the above ratios. If one uses an equally tempered scale, then each half step has ratio of the twelfth root of 2. Many instruments (winds, strings, voices,...) do not naturally produce this equal temperament so the historical names of intervals and notes is still in use.
Comment: Yep.  Calling C to D a "second" rather than a "first", counting both endpoints as you say, is called "the fencepost problem", which comes up all the time in various guises.  If you have twelve lines spaced an inch apart, how far from the first to the last line?  Eleven inches.  We have the opposite problem in numbering harmonics- typically, the octave is called the "first harmonic", when it should really be the second- the fundamental is the first, because it's one times the starting frequency, the octave is two times, and so forth.  Conventions are not always logical.


reverse a data frame in R

Question: data<-read.csv(file="blabla.csv",row.names=1)
data<-t(data)
data<-as.data.frame(data)
sapply(data,class) #check the type of data

I have a big dataset and I want to transpose it. When I inverse it, it says that all the values are factors. So I can I handle this problem?
I tried to convert it in numerical:  matrix(as.numeric(unlist(data), nrow=nrow(data)).
After I transpose the data I want to add a column with the 2 classes as factor. So in the end I need to have a data set with numerical values and the last column with labels(classes).
Comment: Please add a [reproducible example](http://stackoverflow.com/help/mcve)
for people to work with. We don't all have "blabla.csv"!
Comment: As a coding question rather than a statistical one, this is really [off-topic](http://stats.stackexchange.com/help/on-topic)
 for this site.
Answer: The reason that's happening is because you have a factor in the data, so when you transpose it, the levels in that factor get spread to every column in the output.
R can only have one type per vector (column), and when it sees a mixed type it will coerce it all to be the same, in this case it makes all your columns factors.
You need to remove all non-numeric columns from data before transposing, then add your factors after.

reverse a data frame in R


Solving a 2nd order, nonlinear ODE involving trigonometric terms using FDM

Question: I'm rather new to solving ODEs/PDEs numerically and am trying to solve a 2nd order, nonlinear ODE involving trigonometric terms using finite-differences.
The ODE has the followign form:
$$
\frac{d^2y}{dx^2} = a \cdot \sin(y) + b \cdot \cos(y)
$$
I would like to numerically solve this in matrix operation form:
$$
A \cdot \vec{y} = \vec{b}
$$
Discretizing using the standard FDM-stencil:
$$
\frac{y_{i+1} - 2y_i + y_{i-1}}{\Delta x^2} = a \cdot \sin(y_i) + b \cdot \sin(y_i)
$$
But because of the trigonometric terms either $A$ or $\vec{b}$ must be dependent on $\vec{y}$. For example:
$$
\frac{1}{\Delta x^2}
\begin{pmatrix}
1 & -2 & 1 & 0 &\cdots \\
& \ddots & \ddots & \ddots & \\
\cdots & 0 & 1 & -2 & 1
\end{pmatrix}
\cdot
\begin{pmatrix}
y_{i-1} \\
y_i \\
y_{i+1} \\
\vdots
\end{pmatrix}
=
\begin{pmatrix}
a \cdot \sin(y_{i-1}) + b \cdot \sin(y_{i-1}) \\
a \cdot \sin(y_i) + b \cdot \sin(y_i) \\
a \cdot \sin(y_{i+1}) + b \cdot \sin(y_{i+1}) \\
\vdots
\end{pmatrix}
$$
The only solution I could think of is an iteration loop $j$, where I give a starting guess for $\vec{y}$ into $\vec{b}$ and then use $\vec{y}_j - \vec{y}_{j-1}$ as a residual to iterate.
What would be the best strategy to this problem? Is it possible to avoid iterating?
EDIT:
added the discretization I thought of
Comment: A few things. Is this an initial value problem? Finite-differences are best-suited to boundary value problems. An incorrect choice of boundary conditions can make this specific problem ill-posed. This is a nonlinear problem and the discretized system should reflect that. You should have a system of nonlinear equations for the coefficieint vector $\vec{y}$, whcih can be solved by Newton's method or something similar. Linearizing the problem is not what you want to do here.
Comment: @whpowell96 : It is indeed a BVP. Newtons Method would as well mean a outer iteration loop, but if the problem, as you said, cannot be properly solved using some form of linearization, it seems that i can't avoid iteration.
Comment: The problem is much simpler if you switch variables.
Comment: @ClaudeLeibovici Could you further elaborate what you mean by switching?
Comment: Iterative methods are standard in numerical ODEs and PDEs. It is very rare that one actually solves even the linear systems directly instead of with an iterative method in practice.
Comment: @whpowell96 naturally, but as I was able to solve simpler problems without iteration I thought it might be possible to do this one without as well
Answer: $$y'' = a \, \sin(y) + b \, \cos(y)$$ Switching variables
$$-\frac {x''}{[x']^3}= a \, \sin(y) + b \, \cos(y)$$ Reduction of order $p=x'$
$$ -\frac {p'}{p^3}= a \, \sin(y) + b \, \cos(y)$$
Integration
$$p=\pm \frac{1}{\sqrt{2 (b \sin (y)-a \cos (y))+c_1}}=x'$$
Integrate again and you have an explicit solution for $x(y)$ which is impossibel to inverse.
But, numerically, staying with $p=x'$, you face a first order equation.


Mysql - Query for records between months group by each month

Question: I have a table from where I need to retrieve data.
The table has a date field -tbl_date - what i need is, when I select 2010 Jan as from date and 2011 Feb as Todate, it should display all records between these two date, along with individual results for each month group by the month.
Like - The results should display as
2010 Jan
Record 1 values
Record 2 Values
2010 Feb
Record 1 Values
Record 2 Values
.........
2011 Feb
Record 1 Values
Record 2 Values
Can any one help me on this?
Thank You
Sathish
Answer: Nice question, here's an untested solution:
SELECT *,
       YEAR(date) as year,
       MONTHNAME(date) as month
FROM table
WHERE date BETWEEN date1 AND date2
ORDER BY date ASC

Comment: There are several things wrong with that. The `GROUP BY` won't have any effect, because you aren't using any aggregate functions (e.g. SUM). And `ORDER BY` will be slow, because the calculated values `year` and `monthNum` aren't indexed. If you order by tbl_date that can use an index to make the query faster.
Comment: @vincebowdren, must have misunderstood the OP with my `GROUP BY` clause - not that it wouldn't have done anything, it would still have grouped them, although that wasn't the requirement. the rest i have no good excuse for. updated!
Answer: The query is pretty simple:
SELECT field1, field2, field3 FROM myTable
 WHERE tbl_date BETWEEN @startdate AND @enddate;

That gets you the right data, fast (because it can use the index on the tbl_date field). The only tricky point is getting the right values into the @startdate and @enddate variables. For your example, they need to be 2010-01-01 and 2011-02-28 (i.e. the start of the first month and the end of the last month).
The other point is that the returned data will look like this:
Record 1 values from January 2010
Record 2 values from January 2010
Record 3 values from February 2010
Record 3 values from February 2010
Record 4 values from February 2010
Record 4 values from March 2010

It doesn't have the month heading rows saying '2010 Jan' and '2010 Feb', breaking up each section. SQL data queries are bad at returning that kind of data (where the main rows have 20 data fields, and these other rows have just one). I'd recommend using an app (e.g. php) to take the data and insert these headers in the display, rather than trying to get them included in the recordset returned from the database.
Comment: Thank You Vince - i was able to find a solution - thank you again!


How do I show $SO(n)$ is open and closed in $O(n)$?

Question: As title, how do I show $SO(n)$ is open and closed subset of $O(n)$?
Is the preimage of closed set under continuous map closed ?
Comment: Yes...in fact, that is one of two equivalent, very usual definitions of "continuous map" between topological spaces.
Comment: First of all, do you know how to give $O(n)$ a topology?
Comment: @John I don't know what open sets look like in $O(3)$ as I can't picture open ball using matrices.
Comment: As $O(n)$ is a subset of $M_n(\mathbb R)$ (the set of all $n \times n$ matrix$, and $M_n(\mathbb R)$ is identified as $\mathbb R^{n^2}$, then $O(n)$ is given the subspace topology.
Comment: So now I can define function $f:O(n) \rightarrow X$ ($X$ just some space) and use the theorem which link continuous function to open sets to say something about $SO(3)$ in $O(3)$?
Answer: You have the continuous map $\det:O(n)\to\lbrace -1,+1\rbrace$, and $SO(n)$ is the preimage of $\lbrace +1\rbrace$, which is both open and closed in $\lbrace -1,+1\rbrace$, hence $SO(n)$ is both open and closed in $O(n)$.

Here's another reasoning: $SO(n)$ is a connected component of $O(n)$, hence closed. But $O(n)$ is locally connected, because it's a manifold, hence $SO(n)$ is open aswell.
Comment: The first proof is nice. But for the second, if you assume already that $SO(n)$ is a connected component of $O(n)$, then there is nothing to proof (it's open and closed)
Comment: Thinks, one thing want to ask, how do I know $det$ is continuous ?
Comment: @SamC observe that $\det$ is just a polynomial in $n^2$ variables.
Answer: hint a):
$$
f:M_n(\mathbb{R}) \rightarrow M_n(\mathbb{R}) \qquad A \mapsto A^tA
$$
is continous and $O(n)$ is the preimage of a point.
hint b) $\det:M_n(\mathbb{R}) \rightarrow \mathbb{R}$ is continous
You only need to show "open": Fix an element of $O(n)\setminus SO(n)$, let's call it $R$. Then
$$
L_R:O(n) \rightarrow O(n) \qquad A \rightarrow RA
$$
is a homoemorphism: What is $L_R(SO(n)) \cup SO(n)$?


After restarting server Postgres does not start

Question: I am running Postgres 14 on a Windows Server 2022 Standard. While DB operations were running such as inserting, my server restarted, and, now the Postgres does not start. I looked at the config file and the last lines of that are as follows:
2023-04-23 01:43:36.913 PDT [123528] LOG:  could not receive data from client: An existing connection was forcibly closed by the remote host.

2023-04-23 01:52:04.222 PDT [105764] LOG:  could not receive data from client: An existing connection was forcibly closed by the remote host.

2023-04-23 01:52:04.223 PDT [118464] LOG:  could not receive data from client: An existing connection was forcibly closed by the remote host.

2023-04-23 01:54:38.568 PDT [121492] LOG:  could not receive data from client: An existing connection was forcibly closed by the remote host.

2023-04-23 01:54:38.569 PDT [123696] LOG:  could not receive data from client: An existing connection was forcibly closed by the remote host.

2023-04-23 01:59:51.982 PDT [124252] LOG:  could not receive data from client: An existing connection was forcibly closed by the remote host.

2023-04-23 01:59:51.983 PDT [122440] LOG:  could not receive data from client: An existing connection was forcibly closed by the remote host.

2023-04-23 01:59:51.983 PDT [116252] LOG:  could not receive data from client: An existing connection was forcibly closed by the remote host.

2023-04-23 02:00:52.468 PDT [4988] LOG:  received fast shutdown request
2023-04-23 02:00:52.572 PDT [4988] LOG:  aborting any active transactions
2023-04-23 02:00:52.611 PDT [6172] FATAL:  terminating connection due to administrator command
2023-04-23 02:00:52.683 PDT [5984] ERROR:  canceling statement due to user request
2023-04-23 02:00:52.716 PDT [4988] LOG:  background worker "logical replication launcher" (PID 5984) exited with exit code 1
2023-04-23 02:00:52.903 PDT [5916] LOG:  shutting down
2023-04-23 02:00:55.161 PDT [4988] LOG:  database system is shut down

Also, as suggested by others I check Event Viewer and see:
2023-04-23 03:33:39.610 PDT [5804] FATAL:  configuration file "C:/Program Files/PostgreSQL/14/data/postgresql.conf" contains errors

Since I am using psycopg to work with db, I am getting the following errors:
File "C:\Python310\lib\site-packages\psycopg2\__init__.py", line 122, in connect
    conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) connection to server at "localhost" (::1), port 5432 failed: Connection refused (0x0000274D/10061)
        Is the server running on that host and accepting TCP/IP connections?
connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused (0x0000274D/10061)
        Is the server running on that host and accepting TCP/IP connections?

config file
For size limitation, I removed all comments:
listen_addresses = '*'      # what IP address(es) to listen on;
port = 5432         # (change requires restart)
max_connections = 100           # (change requires restart)
shared_buffers = 4096MB         # min 128kB
work_mem = 2000MB               # min 64kB
maintenance_work_mem = 3000MB       # min 1MB
dynamic_shared_memory_type = windows    # the default is the first option
max_wal_size = 1GB
min_wal_size = 80MB
effective_cache_size = 4GB
log_destination = 'stderr'
logging_collector = on      # Enable capturing of stderr and csvlog
log_timezone = 'America/Los_Angeles'
datestyle = 'iso, mdy'
timezone = 'America/Los_Angeles'
lc_messages = 'English_United States.1252'          # locale for system error message
                    # strings
lc_monetary = 'English_United States.1252'          # locale for monetary formatting
lc_numeric = 'English_United States.1252'           # locale for number formatting
lc_time = 'English_United States.1252'              # locale for time formatting
default_text_search_config = 'pg_catalog.english'

I have not a recent DB backup. How should I conquer the problem?
Comment: Please attach it [into the question](https://serverfault.com/posts/1129471/edit). I think there might be people who are fine with walking several clicks away into obscure service to read the file, but here we want to have the question understandable without external resources. But it might be good to remove comments.
Comment: Perhaps it is better to guide instead down vote. Let me know what is the problem with my question.
Comment: Configuration file has a problem. Guess what to do? Hint: even if I wanted to help you to find an error in that file, I couldn't...
Comment: So, what should i do? My config file is almost as the original. I just changed some parameters for more memory. The changes were not placed recently, and every thing was working nice. I think the error is somehow misleading. Can, I find more information any where in the windows or logs?
Comment: Show the file. No one can help with this other way than evaluate. Also, notice that Postgres combines configuration data from several files; this might be not the file you remember you've edited.
Comment: Thanks, attached the config. The size of text is more than limit of questions. please look at the question.
Comment: Added to question.
Answer: Thanks to @Nikita Kipriyanov, Solved the problem by replacing a new config file from another installation.


Connect to mysql database with local Ip address - Codeigniter

Question: I want to connect to database with ip address instead of local host, but when I write IP Address (another PC in LAN), it shows me error of permission denied.My connection array is as follows:
$db['default']['hostname'] = '192.168.1.122';
$db['default']['username'] = 'root';
$db['default']['password'] = '123456';
$db['default']['database'] = 'test_db';
$db['default']['dbdriver'] = 'mysqli';

result is:

Message: mysqli::real_connect(): (HY000/2002): Permission denied
      Filename: mysqli/mysqli_driver.php

I am using CentOS 7 and tried connection with telnet and it is working fine there.
Comment: Are you allowed to access the MySQL port via Firewall? Seems like you have been blocked. Please check that you have access and control over the MySQL ports in your Firewall.
Comment: That IP is the number t your router. Maybe this is why it does not work.
Answer: Probably you haven't the permission to log as root from a host different from localhost. You can find info here.
You can grant permissions to root this way:
GRANT ALL ON *.* to root@'%' IDENTIFIED BY 'mysql root password';

Answer: I had the same issue and found the solution to be that Apache was not set to allow remote connections.
You can run this to check:
getsebool -a | grep httpd_can_network

I ran the following to fix the issue:
sudo setsebool -P httpd_can_network_connect 1
sudo setsebool -P httpd_can_network_connect_db 1

Source:

https://www.digitalocean.com/community/questions/centos-7-warning-mysqli_connect-hy000-2002-permission-denied-in
https://www.linuxquestions.org/questions/linux-newbie-8/error-mysqli_connect-hy000-2002-permission-denied-4175588599/


VLAN connecting to management vlan

Question: I have a 3com 4200g switch. I have created 2 vlans and have the default management vlan1.
How would i connect the 2 vlans that i have created to the management vlan.
I assum that i am going to need some form of ip routing.
Comment: Do you need two VLANs for any reason? Maybe you're just making things difficult for no benefit.
Comment: we currently use one big vlan and im looking to split the different departments into their own vlans for security and to reduce network traffic.
Comment: 1. For security? That's a pretty vague statement. What security? Some fuzzy idea that "VLAN's are for security so I need to have them". 2. How is having VLAN's going to reduce network traffic? Do the machines in one VLAN not need to communicate with machines in the other VLAN? If they don't need to communicate then that must mean that they're not communicating now so what traffic are you reducing? Don't just do things because you can or because you think you should or because someone said you should. Have specific goals and objectives and specific needs or problems that you're addressing.
Answer:
Take a router and connect it to both VLANs (either with physically separate ports or with trunking).
Give that router an IP address in each VLAN.
For each VLAN, either make that router the default router for hosts in that VLAN, configure each host in the VLAN to use that router to reach IP addresses in other VLANs, configure the existing default router for that VLAN to use this router to reach hosts in other VLANs, or use some kind of dynamic routing protocol such as OSPF between all your routers.

This is called inter-VLAN routing.
Update: Your switch has limited inter-VLAN routing capabilities. But here's an example of how to set it up. Say you want the switch to route between VLAN 2, 192.168.1.0/24 and VLAN 3, 192.168.2.0/24. The switch's address on VLAN 2 will be 192.168.1.250 and the switch's address on VLAN 3 will be 192.168.2.1. The configuration would be:
interface vlan-interface 2
  ip address 192.168.1.250 255.255.255.0
!
interface vlan-interface 3
  ip address 192.168.2.1 255.255.255.0
!

Again though, this will only work if traffic on VLAN 2 devices that need to go to VLAN 3 devices goes to 192.168.1.250 and if traffic on VLAN 3 devices that need to go to VLAN 2 devices goes to 192.168.2.1. The switch can't route traffic it doesn't get.
So, in my example, devices on VLAN 3 could have 192.168.2.1 set as their default gateway. And the default gateway on VLAN 2 could be a router that knows to route packets bound for 192.168.2.0/24 to 192.168.1.250.
Also note that this will not make Internet access work unless the router that does your NAT knows to NAT for the IPs on the other VLANs. This is a complex enough configuration that you may wish to hire a consultant.
Comment: Is there any way of doing using the switch as the router?
Comment: Yes. The 4200g has very limited inter-VLAN routing capabilities (8 IP interfaces, 32 static routes), but it may be sufficient for your application. For VLANs that don't already have a router in them, make the switch's IP in that VLAN their default gateway. For VLANs that do, you'll have to configure static routes in that other router to the IP ranges on the other VLANs (with the switch's IP in that VLAN as the next hop).
Comment: "This is called inter-VLAN routing" - or just, you know, **routing**. You're not talking about L3 switching here, after all.
Comment: @adaptr: I mean inter-VLAN routing as opposed to routing between distinct physical interfaces. The vast majority of routers don't use VLANs at all (except internally).
Comment: Nothing routes between interfaces - routing occurs between *networks*. In that sense, there is no logical difference (and indeed, there is no protocol difference) between routing across VLANs or actual LANs.
Comment: @adaptr: I think that's confusing terminology. Routers don't magically gather packets from networks. They get packets because they're transmitted on a specific interface that is connected to that router.

VLAN connecting to management vlan


Exercise III.2.1(b) Hartshorne: Isn't the restriction of a constant sheaf on a connected space to a connected subspace again constant?

Question: Consider Exercise III.2.1(b) in Hartshorne: Let $X=\mathbb{A}_k^n$ for $n\geq 2$ and an infinite field $k$, and let $Y\subseteq X$ be the union of $n+1$ hyperplanes in general position. Let $U=X\setminus Y$, and denote by $\underline{\mathbb{Z}}$ the constant sheaf on $X$, and also $\underline{\mathbb{Z}}_U:=j_{!}(j^{-1}\underline{\mathbb{Z}})$ as well as $\underline{\mathbb{Z}}_Y:=i_{*}(i^{-1}\underline{\mathbb{Z}})$, where $j:U\to X$ and $i:Y\to X$ are the inclusion maps. Then show that $H^n(X,\underline{\mathbb{Z}}_U)\neq 0$.
Now I'm confused: consider the sheaf $i^{-1}\underline{\mathbb{Z}}$ on $Y$. By definition, this is the sheaf associated to the presheaf $i^{-1,pre}\underline{\mathbb{Z}}$ defined by
$$
i^{-1,pre}\underline{\mathbb{Z}}(W)=\lim_{\substack{V\subseteq_{\text{open}} X \\ W\subseteq V}}\underline{\mathbb{Z}}(V).
$$
But now as $X$ is irreducible, we have $\underline{\mathbb{Z}}(V)=\mathbb{Z}$ for all non-empty $V$, and the restriction maps are just the identity, so $i^{-1,pre}\underline{\mathbb{Z}}(W)=\mathbb{Z}$ for all non-empty $W$. But now as $Y$ is connected for $n\geq 2$, this is in fact already a sheaf, namely the constant sheaf associated to $\mathbb{Z}$ on $Y$. But then this is flasque, so the higher cohomology groups vanish, which gives me $H^n(X,\underline{\mathbb{Z}}_U)=0$. Where am I going wrong?
Answer: I think the issue is that the answer to your question in the title is negative, since it's irreducibility that you're really interested in to argue that this sheaf is flasque. Explicitly, if you take the union of the $x$ and $y$ axes in the affine plane $Y=V(xy) \subseteq \mathbf{A}^2_k$ and the constant sheaf $\underline{\mathbf{Z}} \in \text{Sh}_{\text{Ab}}(Y)$ (which is the restriction of the constant sheaf $\underline{\mathbf{Z}}$ on $\mathbf{A}^2_k$ to $X$) then the global sections are given by $\Gamma(Y,\underline{\mathbf{Z}}) = \mathbf{Z}$ since $Y$ is connected, but $Y$ has the disconnected open subset $U = D(x) \cup D(y) \subseteq Y$. You can see $U$ is disconnected by the equality $$
   D(x) \cap D(y) = D(xy) = \emptyset
$$ or by just checking that $U$'s global sections are given by the equaliser $$
   \text{eq}(k[x,x^{-1}] \times k[y,y^{-1}] \rightrightarrows (0)) = k[x,x^{-1}] \times k[y,y^{-1}]
$$ which has precisely two non-trivial idempotents - this implies $\Gamma(U,\underline{\mathbf{Z}}) = \mathbf{Z} \oplus \mathbf{Z}$ and thus the restriction map $$
   \Gamma(Y,\underline{\mathbf{Z}}) \to \Gamma(U,\underline{\mathbf{Z}})
$$ can't be surjective.
Hope this helps :)
Comment: Ah yes of course, thanks :)


If $α , β$ be two arbitrary complex number then $| α +\sqrt{α^2-β^2 } |+| α - \sqrt{α^2-β^2}|$ is equal to?

Question: If $α$ , $β$ be two arbitrary complex number then $$| α +\sqrt{α^2-β^2 } |+| α - \sqrt{α^2-β^2}|$$ is equal to ?
Answer: \begin{align*}
&\;(|\alpha+\sqrt{\alpha^2-\beta^2}|+|\alpha-\sqrt{\alpha^2-\beta^2}|)^2\\
=&\;|\alpha+\sqrt{\alpha^2-\beta^2}|^2+2|\alpha+\sqrt{\alpha^2-\beta^2}||\alpha-\sqrt{\alpha^2-\beta^2}|+|\alpha-\sqrt{\alpha^2-\beta^2}|^2\\
=&\;|\alpha|^2+|\sqrt{\alpha^2-\beta^2}|^2+2\text{Re}(\alpha\sqrt{\alpha^2-\beta^2})+2|\alpha^2-(\alpha^2-\beta^2)|+|\alpha|^2+|\sqrt{\alpha^2-\beta^2}|^2-2\text{Re}(\alpha\sqrt{\alpha^2-\beta^2})\\
=&\;2|\alpha|^2+2|\sqrt{\alpha^2-\beta^2}|^2+2|\beta|^2\\
=&\;2|\alpha|^2+2|\alpha^2-\beta^2|+2|\beta|^2\\
\end{align*}


Need to find the Id which has different details in the detail table

Question: Here is my table cash_main:
"CASH_MAIN" table has TWO columns as shown below:
CASHID   Amount
7          1000
9          300

The Deatils  will be in "cash_detail" table:
cash_detailid cashID     agentid   Amount
 1             7          101       200
 2             7          102       200
 3             7          103       200
 4             7          104       200
 5             7          105       200
 6             9          106       300

I am trying to get the cashid  which has multiple agentid's linked in the detail table :
cashid
7

Here in the example cashid:7 has multiple agent id's which totals to 1000
but we shouldn't pick cashid:9 as it has only one single agentid and that has 300
I am trying to use this below query but it is not fetching me correct result:
WITH Duplicateaccounts
AS (
    SELECT CASHID
        ,count(*) AS rcount
    FROM cash_detail
    GROUP BY CASHID
    HAVING count(*) > 1
    )
SELECT CASHID
 FROM cash_detail  a
JOIN cash_MAIN b ON b.CASHID = a.CASHID
ORDER BY a.cashid

Answer: You can use group by and having:
select cd.cashID
from cash_detail cd
group by cd.cashID
having min(agentid) <> max(agentid);

Comment: Gordon, I've seen you and others giving this kind of answer many time and it always makes me wonder, why you always use `<>`? I mean is `<` not enough? Of course at the end of the day, there is no difference in results or performance between `<>` and `<`, but it's just a matter of code beauty :). I mean is it not silly to expect `MIN() > MAX()`? I know that all of you who use `<>` mean to say when they're not equal, which is the logic that the query tries to achieve, but then once written, it just feels silly :). Or perhaps I'm just too lazy to type or read one more unnecessary character :).
Comment: @RacilHilan . . . That is interesting.  In my case, it is just in case I type `max()` first.
Comment: Oh, that's wired in my hands nerves, so they will automatically switch it to `>`, no brain involved :P (just kidding of course).
Answer: COUNT(DISTINCT) can be used to identify where there are different values in a particular field.
SELECT cash_detail.cashID
FROM cash_detail
GROUP BY cash_detail.cashID
HAVING COUNT(DISTINCT cash_detail.agentid)>1;


Nonarchimedean convergent power series

Question: I would like to understand the second paragraph on the second page (marked page 320) of the article http://www.numdam.org/article/MSMF_1974__39-40__319_0.pdf on rigid analytic geometry by Michel Raynaud.
Let's take $K$ a complete nonarchimedean field and $R$ its valuation ring, and $a \in R$ a non-zero element of the unique maximal ideal of $R$ . Let $D:=\{z \in K \colon \vert z \vert \leq 1\}$ the closed unit disk. We can decompose $D$ into the smaller disk $D':=\{z \in K \colon \vert z \vert \leq \vert a \vert \}$ and the annulus $C:=\{z \in K \colon \vert a \vert \leq \vert z \vert \leq 1 \}$.

Then, the mentioned paragraph says that a power series converging on $D$ is the same as a pair consisting of a power series converging on $D'$ and a Laurent series converging on $C$ such that these two series agree on $C \cap D'$.

Now, I am aware that this follows from the Tate acyclicity theorem, but the article says it is immediate, so I would like to see how it is immediate.
I am also aware how the corresponding fact is true in complex analysis, but that doesn't seem to help because in the rigid nonarchimedean setting we don't have a notion of differentiability.
So we know that the Laurent series is a power series on the circle $C \cap D'$. Is there an identity-theorem-type of argument to conclude that the Laurent series is a power series on the whole annulus $C$? Or is it even simpler to conclude?
EDIT: For Lubin's proof below to go through, we need to
1) have our functions take values in the algebraic closure $\overline{K}$ of $K$ (i.e. $D=\{z \in \overline {K} \colon \vert z \vert \leq 1\}$), OR
2) impose the extra condition that $K$ has an infinite residue field.
I too prefer the first option, because the second is rather exclusive since it excludes local fields.
Comment: In what sense do we not have a notion of differentiability here?
Comment: My bad, we certainly do! I meant to say that we don't have a rewarding notion, because there is no link between differentiable and analytic functions here.
Comment: Ah, of course. So the good notion is analyticity, rather than differentiability; and all proofs should depend on the former, without mention of the latter, I suppose. Let me think about this. I might be able to hack up an ugly proof for you.
Comment: Thank you for taking the time to think about it, I appreciate it.
Answer: To clarify our ideas, let's see what the Laurent series look like that are convergent on $\{z:|z|=1\}$ — the skin, so to speak, of the closed unit disk. These are the series $\sum_{-\infty<n<\infty}c_nx^n$ for which $\lim_{|n|\to\infty}|c_n|=0$ . That is, we need $|c_n|\to0$ for positive $n$ and negative $n$.
A worthwhile example is $\sum_{n\ge0}p^n(x^{-n^2}+x^{n^2})$. Draw the Newton picture and you see what's going on: the points you draw are all $(\pm n^2,n)$. This is a series convergent only on the skin.
It's the same thing for series about which you nothing more than that they are convergent on the skin of $D'$, namely the series $\sum_{-\infty<n<\infty}\frac{c_n}{a^n}x^n$ for which $\lim_{|n|\to\infty}|c_n|=0$; or if you like, the series $\sum_{-\infty<n<\infty}\gamma_nx^n$ for which $\lim_{|n|\to\infty}|a^n\gamma_n|=0$.
But the series we're concerned with are power series, that is, of form $\sum_0^\infty\gamma_nx^n$; and since the series is convergent on the outer skin of $C$, even at $z=1$, so the coefficients $\gamma_n$ must have $|\gamma_n|\to0$. This is just the condition that our series converges on $D$.
EDIT:
Let's see whether I can give a satisfactory answer to your very valid objection. It depends on making a careful distinction between a series $G(x)$ and the $p$-adic function $g$ defined by $G$.
While we're at it, I want to change the coordinatization, sending a point $z$ to $z/a$, so that now our old set $D'$ is the closed unit disk $D$, and the original $D$ becomes what I'll call $D^+$, namely $\{z:|z|\le|1/a|\}$. Then the original $C$ becomes $\{z:1\le|z|\le|1/a|\}$. Our intersection-set is just the units $U$ of $K$, considered as an analytic space. All this just to make the typing easier for me.
Our four rings of power series now are $S^{[0,1]}\{\sum_0^\infty c_nx^n: c_n\to0\}$ for $D$, $S^{[0,1/|a|]}=\{\sum_0^\infty c_nx^n:c_n/a^n\to0\}$ for $D^+$, $S^{[1,1/|a|]}=\{\sum_{-\infty,\infty}c_nx^n:\lim_{n\to-\infty}c_n=0\text{ and }\lim_{n\to\infty}c_n/a^n=0\}$ for our new annulus $C$, and $S^{\{1\}}=\{\sum_{-\infty<n<\infty}c_nx^n:\lim_{|n|\to\infty}c_n=0\}$ for $U$.
My first task is to show that a nonzero series $G(x)\in S^{\{1\}}$, which you recall may be evaluated at any $z\in U$, to give a numerical value, must define a function which is not identically zero on $U$.
Well, without loss of generality, we may assume that all coefficients of $G$ are in $R$, and indeed some of them are in $R^\times$, the unit group of $R$. But only finitely many of them! Now, by multiplying by a monomial, we may assume that $G(x)$ reduces to the nonzero $\Gamma(x)\in(R/\mathfrak m)[x]$, for $\mathfrak m$ the maximal ideal of $R$, and even, if you like, that $\Gamma$ is monic. But even over an algebraically closed field containing $R/\mathfrak m$, $\Gamma$ has at most finitely many roots. Thus, we may find $\xi$ in either $R/\mathfrak m$ or an algebraic closure for which $\Gamma(\xi)\ne0$, and when we lift $\xi$ to $z_0$ in $R$ or a finite unramified extension, if necessary, we find that $G(z_0)\ne0$, so that the function $g$ defined on $U$ by the series $G$ is not identically zero.
That was the hard part, if any such there was. (I'm sure you can see the rest of the argument.) We now consider an analytic function $f$ on $D$, given by $F(x)\in S^{[0,1]}$ and analytic function $h$ on our annulus $C$, given by $H(x)\in S^{[1,1/|a|]}$, such that $f$ and $h$ agree on $U$. But we have set-theoretic inclusions of $S^{[0,1]}$ and $S^{[1,1/|a|]}$ into $S{\{1\}}$ and since $f$ and $h$ agree on the set $U$, their difference (an element of $S^{[1,1/|a|]}$) is identically zero on $U$, so that $G$ and $H$ are equal, coefficient by coefficient.
I believe that the earlier argument I tried to give now applies, to yield our result.
Comment: I think I have it. But it's late, and I'm fighting a cold. May have it for you by tomorrow afternoon.
Comment: On the other hand, because of the applications I have in mind, I like to take my functions to be defined over a finite extension of $\Bbb Q_p$ but to allow the coordinates of the points to be in $\Bbb Q_p^{\text{ac}}$. (you don't need to pass to the completion of the algebraic closure in this case). You really do need to have a clear idea of what the underlying set is, and its topology, while you're thinking about these things.
Comment: I understand what you wrote, but I am not sure whether it fully answers my question, let me state it more precisely: Let $f\colon D' \to K$ be a an analytic function (i.e. given by a power series $F$ converging on $D'$) and $g\colon C \to K$ a function given by a Laurent series $G$ converging on $C$, and suppose that $f$ and $g$ agree on $C \cap D'$. Obviously, we can define a function $h \colon D \to K$ by setting $h$ to be $f$ on $D'$ and $g$ on $C$. We now want to show that $h$ is given by a power series $H$ converging on $D$.  Continued in my next comment...
Comment: Now, you've shown that, if we know that the Laurent series $G$ is in fact a power series, we can use the fact that $G$ converges on the outer skin of $C$ to deduce that $G$ converges on $D$. So if we know that $G=F$ (as formal series), then we are done, we can set $H:=G$. But, we only know that $F(z)=G(z)$ for all $z \in C \cap D'$. Can we deduce $F=G$ from that?
Comment: Yes, I confess that issues of this kind tend to confuse me. I guess in this case, we need to know that restriction of analytic functions from $D'$ to the skin of $D'$ is an injection. Let me think further.
Comment: I hope the cold is not as nasty as these power series!
Comment: Yes, perfect! You said you might be able to hack up an ugly proof, but in the end it was very nice! One last thing: since $\xi$ might not be in $K$, we need to have all the disks and annuli consist of elements of an algebraic closure $\overline{K}$ of $K$, right?
Comment: I realized yesterday that all you need for finding $\xi$ is the knowledge that the residue field is infinite. But there is a real issue involved with what you have asked. What is a $p$-adic analytic space? The physicists seem to want to talk about analytic functions defined over $\Bbb Q_p$, and evaluate them only at $\Bbb Q_p$-points, and maybe even deal with the geometric reality as a topological space. But the safest thing by far is to allow functions' coefficients to be in $\Bbb C_p$ and naturally take the coordinates of such points in $\Bbb C_p$ again. (continued…)
Comment: This has been very insightful. Thanks again for tackling the problem.

Nonarchimedean convergent power series


I need to know when qmail is not running

Question: Obviously I can't send myself an email to tell myself that qmail is not working... at least not using qmail. How would you inform yourself about the fact, that qmail is not running?
Answer: Easiest way is probably an http post or wget to a secondary server that can send the email.
Obviously if your mailbox is on this server it wont work so you would need to use another email address.
For instance, run a cron job every minute to detect if the process qmail is running.  If it isn't running then wget http://secondserver/alert.php
cronjob bash script.
#!/bin/sh
SERVICE='qmail'

if ps ax | grep -v grep | grep $SERVICE > /dev/null
then
    echo "$SERVICE service running, everything is fine"
else
    echo "$SERVICE is not running"
    wget http://secondserver/alert.php
fi

alert.php
<?php

$to = 'firstname.lastname@example.com';

$subject = 'qmail not running';

$message = "qmail reported down";

$headers = "From: firstname.lastname@example.com\r\nReply-To: email@example.com";

$mail_sent = @mail( $to, $subject, $message, $headers );

echo $mail_sent ? "Mail sent" : "Mail failed";
?>

This solution is a poor mans way of doing it but the simplest.  I'd invest in a monitoring solution such as nagios.  With a proper monitoring tool you can setup a solution that can sms you when down.
This is also a popular monitoring service: http://www.bijk.com/
Comment: thanks pablo, we're implementing this for  the time being!
Comment: for the future we definitely have to look into monitoring services.
Answer: DJ Bernstein wrote qmail. I approve of the other answer, but I must comment:
Many people running qmail eventually bite the bullet and set up DJ Bernstein's other late jurassic period project to monitor services called daemontools. It will keep qmail working through almost anything, including zombie invasions, overheated processors and bad memory.
It works really, really well - I suspect that daemontools is the chuck norris of the daemon world.
[Daemons = original name for what we now call services]
Regardless of your OS or distribution, there will be a daemon service keepalive program, and you just have to add qmail to it. We don't trust anyone or anything, so we run emails through the mail server and then check to see if they arrived within a reasonable time period. This is THE ONLY WAY to really know if it's working correctly. Monitoring a service is only 50% of a proper health check.
It's worth reading about DJB. I always assumed he was really old, but not so much.
http://en.wikipedia.org/wiki/Daniel_J._Bernstein
Answer: Just to add an additional answer- you could test, from another server if the mail port is listening for mail (assuming this is open to this other server)- if it reports that it is blocked, then it could notify you of the fact.
Answer: One possible way could be to setup a monitoring service, like Nagios, and add qmail to be monitored.This way not only can you be notified about a failed qmail service, but, in fact, you can also be warned of an impending failure, so that you can take the necessary actions to prevent the failure from actually happening.
Answer: I like pablo's approach; I've used something similar to send IM-style messages tracking IP address movement of my home computer connected to work via a VPN (since it was assigned a different address every time):
import xmpp

xmpp_login  = 'user'
xmpp_domain = 'jabber.com'
xmpp_pwd    = 'content-purged'
xmpp_server = 'www.jabber.com'
xmpp_recp   = 'firstname.lastname@example.com'

conn = xmpp.Client(xmpp_domain)
conn.connect(server=(xmpp_server, 5222))
conn.auth(xmpp_login,xmpp_pwd)
conn.send(xmpp.Message(xmpp_recp, "message body"))

Obviously, this requires a XMPP (Jabber) account - you can post messages 'to yourself', so one is sufficient.


how to resubmit binary without reset the review queue

Question: Hi I have uploaded my app and it is waiting for review at the movement, i have found issues that i fixed after upload, now how can i reupload it without a reset? i can see reject binary button but that will trigger reset according to apple(Please note that if you reject a binary that is Waiting For Review or In Review, your review time will be reset and you will start over from the beginning once you submit a new binary. )
also how long does it take from waiting to review to review?
thanks
Comment: I'm voting to close this question as off-topic because it concerns the policies and procedures of app distribution services, rather than programming. Please refer to: [Are developer-centric questions about application stores on topic?](https://meta.stackoverflow.com/q/272165), [Why can't I ask customer service-related questions?(https://meta.stackoverflow.com/a/255746)
Answer: Apple specifically says that submitting a new binary always bumps you to the back of the queue, period. Otherwise people would try to game the system by submitting apps a week ahead of when they think they'll be done, and planning to swap in the final binary just in time.
If you found the issue, Apple likely will too, and they don't approve apps that crash during review. That'll bump you to the back of the line too, so might as well re-submit now.
It's been my experience that Apple usually gets to new submissions between a week and two, and minor updates are sometimes approved in a couple of days.
Answer: There is no way to upload a new binary without going to the end of the review queue, AFAIK or can find in any Apple documentation.


Find $19\Diamond 98$, given rules $(xy)\Diamond y=x(y\Diamond y)$, $(x\Diamond 1)\Diamond x=x\Diamond 1$, and $1\Diamond 1=1$

Question:
Given any two positive real numbers $x$ and $y$, then $x \, \Diamond \, y$ is a positive real number defined in terms of $x$ and $y$ by some fixed rule. Suppose the operation $x \, \Diamond \, y$ satisfies the equations $(xy) \, \Diamond \, y=x(y \, \Diamond \, y)$ and $(x \, \Diamond \, 1) \, \Diamond \, x = x \, \Diamond \, 1$ for all $x,y>0$.
Given that $1 \, \Diamond \, 1=1$, find $19 \, \Diamond \, 98$.

I have tried solving this where $x\diamond y = f(x,y)$, but I couldn't get anywhere with it. Can anyone help?
Thanks!
Answer: Hint: you should be able to show

$x \, \Diamond \, 1=x$ and
$x \, \Diamond \, x=x$ and
$(xy) \, \Diamond \, y = xy$ and
$x \, \Diamond \, y = x$ (using $y \not=0$)

and thus

$19 \, \Diamond \, 98 = 19$


UpdateById method in Spring Reactive Mongo Router Handler

Question: In Spring Reactive Java how can I write an updateById() method using the Router and Handler?
For example, the Router has this code:
RouterFunctions.route(RequestPredicates.PUT("/employees/{id}").and(RequestPredicates.accept(MediaType.APPLICATION_JSON))
    .and(RequestPredicates.contentType(MediaType.APPLICATION_JSON)),
        employeeHandler::updateEmployeeById);

My question is how to write the employeeHandler::updateEmployeeById() keeping the ID as same but changing the other members of the Employee object?
public Mono<ServerResponse> updateEmployeeById(ServerRequest serverRequest) {
    Mono<Employee> employeeMono = serverRequest.bodyToMono(Employee.class);

    <And now what??>

    return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(employeeMono, Employee.class);
}

The Employee class looks like this:
@Document
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Employee {

    @Id
    int id;
    double salary;

}

Thanks for any help.
Answer: First of all, you have to add ReactiveMongoRepository in your classpath. You can also read about it here.
    @Repository
    public interface EmployeeRepository extends ReactiveMongoRepository<Employee, Integer> {
        Mono<Employee> findById(Integer id);
    }

Then your updateEmployeeById method can have the following structure:
    public Mono<ServerResponse> updateEmployeeById(ServerRequest serverRequest) {
    return serverRequest
            .bodyToMono(Employee.class)
            .doOnSubscribe(e -> log.info("update employee request received"))
            .flatMap(employee -> {
                Integer id = Integer.parseInt(serverRequest.pathVariable("id"));
                return employeeRepository
                        .findById(id)
                        .switchIfEmpty(Mono.error(new NotFoundException("employee with " + id + " has not been found")))

                        // what you need to do is to update already found entity with
                        // new values. Usually map() function is used for that purpose
                        // because map is about 'transformation' what is setting new
                        // values in our case
                        .map(foundEmployee -> {
                            foundEmployee.setSalary(employee.getSalary());
                            return foundEmployee;
                        });
            })
            .flatMap(employeeRepository::save)
            .doOnError(error -> log.error("error while updating employee", error))
            .doOnSuccess(e -> log.info("employee [{}] has been updated", e.getId()))
            .flatMap(employee -> ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(BodyInserters.fromValue(employee), Employee.class));
}

UPDATE:
Based on Prana's answer, I have updated the code above merging our solutions in one. Logging with a help of Slf4j was added. And switchIfEmpty() functions for the case when the entity was not found.
I would also suggest your reading about global exception handling which will make your API even better. A part of it I can provide here:
/**
 * Returns routing function.
 *
 * @param errorAttributes errorAttributes
 * @return routing function
 */
@Override
protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
    return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
}

private HttpStatus getStatus(Throwable error) {
    HttpStatus status;
    if (error instanceof NotFoundException) {
        status = NOT_FOUND;
    } else if (error instanceof ValidationException) {
        status = BAD_REQUEST;
    } else {
        status = INTERNAL_SERVER_ERROR;
    }
    return status;
}

/**
 * Custom global error handler.
 *
 * @param request request
 * @return response
 */
private Mono<ServerResponse> renderErrorResponse(ServerRequest request) {

    Map<String, Object> errorPropertiesMap = getErrorAttributes(request, false);

    Throwable error = getError(request);
    HttpStatus errorStatus = getStatus(error);

    return ServerResponse
            .status(errorStatus)
            .contentType(APPLICATION_JSON)
            .body(BodyInserters.fromValue(errorPropertiesMap));
}

Comment: Thanks a lot for your answer. It's perfect. Could you please explain why map is used to assign the values from the new employee ? Regards.
Comment: Two things that I observed: (1) there should be no " ;" after the .flatMap(employeeRepository::save); and (2) when try to update, it updates the value but throws an java.lang.IllegalArgumentException: 'producer' type is unknown to ReactiveAdapterRegistry
 at org.springframework.util.Assert.notNull(Assert.java:198) ~[spring-core-5.2.2.RELEASE.jar:5.2.2.RELEASE].
Comment: I'm glad that it was helpful to you. I've also updated my answer and added a part related to exception handling. Please, have a look. Probably, it helps you as well.
Comment: Thanks a ton. It's really helpful.
Answer: A slightly different version of the above worked without any exceptions:
public Mono<ServerResponse> updateEmployeeById(ServerRequest serverRequest) {

        Mono<ServerResponse> notFound = ServerResponse.notFound().build();

        Mono<Employee> employeeMono = serverRequest.bodyToMono(Employee.class);
        Integer employeeId = Integer.parseInt(serverRequest.pathVariable("id"));

        employeeMono = employeeMono.flatMap(employee -> employeeRepository.findById(employeeId)
                .map(foundEmployee -> {
                    foundEmployee.setSalary(employee.getSalary());
                    return foundEmployee;
                })
                .flatMap(employeeRepository::save));

        return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(employeeMono, Employee.class).switchIfEmpty(notFound);
    }

Thanks to Stepan Tsybulski.


Step-by-step explanation of Likert scale/item statistical analysis?

Question: I am looking for resources (books, online, articles) which have a step-by-step explanation of how to test hypothesis using Likert scale/item data. So far, I've learnt that non-parametric methods are best (Kruskal-Wallis, Mann Whitney, ordinal regression, etc.) However, I cannot find any source which has a comprehensive step by step guide on how to do any of these tests. Can anyone point me in the right direction? or give me step-by-step example? I need to understand the reasoning behind each step of the process, not just the code to use in R/SPSS
Comment: Please clarify what type of hypothesis tests you are planning to conduct.  For example, comparing responses for different groups, providing distributions, looking for latent variable measures, etc.
Comment: Just like @Gregg H said, regarding the hypothesis - what problem drove you to survey? What questions are you trying to answer? There are many ways you *could* statistically analyze likert data, but how you determine which method or methods are appropriate is driven by a problem you're trying to solve, a question you're trying to answer, or a hypothesis you're trying to test.
Comment: my hypothesis is as follows: @GreggH
H0: There is no difference in the perceptions of the effectiveness of drills between military and civilian crews.
H1: There is a difference in the perceptions of the effectiveness of drills between military and civilian crews.

The questions used to collect data were 5-point Likert items, so there are multiple items. the survey was administered to both military and civilian crew members, my main aim is to compare responses for the two groups.
Answer: Based on the follow-up in the comments, I would suggest that the appropriate strategy to analyze the data to answer this research question is to use latent variable model to obtain a single measure form the Likert responses.  In brief, you will want to run a model that (1) estimates a single score for each individual from the survey item responses, and (2) compares the average of those latent scores.  This can be accomplished by a multi-group confirmatory factor analysis (CFA).
A very good reference for how to do this in R is Latent Variable Modeling Using R by Beaujean.  I have taught from this book, and students have shared that it is a great reference and is very accessible.  It does require a basic understanding of how R works.
Happy to share more if requested.


Bayesian inference: updating under uncertainty

Question: Bayes Theorem:
$$Pr(A|B) = \frac{Pr(A)Pr(B|A)}{Pr(B)} \tag{0}$$
Furthermore:
$$Pr(A) = Pr(A|B)Pr(B) + Pr(A|\neg B)Pr(|\neg B) \tag{1}$$
Scenario:
Suppose we are not given that an event $B$ has occurred. Assuming we are given a base Probability of $A$:  $(Pr(A_1)$ (this is our prior probability), subsequently, we are now given a $Pr(A|B_1)$, a $Pr(B_1)$, a $Pr(A|\neg B_1)$, and a $Pr(\neg B_1)$ as additional information. Assuming, that I now want to calculate a $Pr(A_2)$ that is the posterior probability in light of the new information.
From $(1)$:
$$Pr(A_2) = Pr(A|B_1) Pr(B_1) + Pr(A|\neg B_1) Pr(\neg B_1)\tag{2}$$
From $(0)$:
$$Pr(A|B_1) = \frac{Pr(A_1)Pr(B_1|A)}{Pr(B_1)} \qquad :\qquad Pr(A|\neg B_1) = \frac{Pr(A_1)Pr(\neg B_1|A)}{Pr(\neg B_1)} \tag{3}$$
Rewriting $(2)$ in light of $(3)$:
$$Pr(A_2) = \frac{Pr(A_1)Pr(B_1|A)}{Pr(B_1)} \times Pr(B_1) + \frac{Pr(A_1)Pr(\neg B_1|A)}{Pr(\neg B_1)} \times Pr(\neg B_1)$$
Which gives us:
$$Pr(A_2) = Pr(A_1)Pr(B_1|A) + Pr(A_1)Pr(\neg B_1|A)$$
Simplifying to:
$$Pr(A_2) = Pr(A_1)\left(Pr(B_1|A) +Pr(\neg B_1|A)\right)\tag{4}$$
Generalising from $(4)$:
$$Pr(A_{l+1}) = Pr(A_l)\left(Pr(B_l|A) +Pr(\neg B_l|A)\right)\tag{5}$$
My Question:

Is $(5)$ valid Bayesian inference?
If not, how do I perform valid inference in the specified scenario?
Comment: I don't understand: has $B_1$ occured or not? The notation $Pr(A_2)$ for the posterior probability is very confusing - the posterior is a probability conditioned to the data you acquired. What data did you acquire? Did $B_1$ occur or not? If you have no data, this is definitely invalid Bayesian inference.
Comment: $B1$ did not occur. We just received new information on $Pr(A|B_1)$ and $Pr(B_1|A)$.
Comment: Did I answer your question?
Answer: Your equations do not allow one to make any kind of inference (Bayesian or not):  they just state that (in your notation) $Pr(A_{l+1})=Pr(A_l)=Pr(A_1)$. Proof:
$$Pr(A_{l+1}) = Pr(A_l)\left(Pr(B_l|A) +Pr(\neg B_l|A)\right)\tag{5}$$
Now, conditional probabilities are probabilities, which means that they follow all the usual probability rules. In particular, since $B_l$ and $\neg B_l$ are mutually exclusive events, we have
$$Pr(B_l|A) +Pr(\neg B_l|A)=Pr(B_l \cup \neg B_l|A)=Pr(\Omega|A)=1$$
Thus
$$Pr(A_{l+1}) = Pr(A_l) \cdot 1 = Pr(A_l) = Pr(A_1) $$ Q.E.D.


Onde eu adiciono os calculos ".py" na página HTML?

Question: Fala galera! blz?
Eu estou começando na área e estou com várias dúvidas. Montei uma página básica de teste HTML e queria inserir um código python que criei (calculo de teste).
Onde e como eu faço esse link entre o HTML e o código .py?
Valeu pela ajuda.
Comment: Vc teria que usar um framework python pra web, sugiro começar com o [Flask](https://www.fullstackpython.com/flask.html) ou mesmo o [Django](https://docs.djangoproject.com/pt-br/3.0/)
Comment: Mais um webframework python que voce pode tentar é o [cherrypy](https://cherrypy.org/)
Answer: Scripts Python não rodam diretamente no "frontend" e mesmo que alguém diga que é possivel, não será de fato o que ocorreu, o que pode ser no máximo é que executou algo como da resposta do @utluiz:

https://pt.stackoverflow.com/a/5358/3635

Neste caso ele usou o https://brython.info/, mas isso nem chega a ser python de verdade, é apenas um "interpretador" que se aproxima bastante.
O que você precisa entender é que navegadores interpretam NATIVAMENTE apenas:

HTML
XML variados (SVG por exemplo, as vezes dependendo de algum plugin)
css
JavaScript
Tem codec para alguns formatos de imagens, vídeo e áudios
Alguns outros como "legendas"

E cada navegador tem o seu próprio interpretador de cada coisa
Se deseja usar Python de verdade e não coisas como Berry ou alguma implementação com XMLHttpRequest para simular o que precisa entender é aonde esta o seu navegador e aonde esta o seu servidor, resumindo precisa entender o mínimo do que é o HTTP e como seu navegador se comunica com isto, no começo (APENAS NO COMEÇO) desta resposta eu já fiz a introdução de como funciona a comunicação navegador e servidor:

https://pt.stackoverflow.com/a/168915/3635

Digo isto porque citaram nos comentários e na outra resposta coisas como Flask e Cherrypy, não adianta muito só citar eles, porque a maioria das pessoas nem entende HTTP direito, incrivelmente tem muita gente que acha que é só chegar e ler uma resposta ou artigo e acha que vai dominar o básico de um conceito, protocolo ou tecnologia, não é assim, na verdade muita coisa dependerá de pratica, o que leva tempo, e mesmo com a minha resposta aqui não vai dominar o básico de verdade, mas ao menos vai entender aonde está o seu navegador e aonde esta o servidor, que é o que importa PRA COMEÇAR.
Voltando ao Flask e Cherrypy e qualquer outro framework web, sem entender o que é HTTP ou aonde esta front-end e back-end então nem tem como prosseguir, se leu a resposta que linkei então provavelmente entendeu o básico, então vamos aos pontos, ao criar algo com Flask e "hostear", algo como:
from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello():
    return 'Hello'

Ao acessar o endereço local (em um teste localhost) vai ser efetuado um DOWNLOAD do conteudo para o seu computador, algo como:
HTTP/1.1 200 OK
Date: Mon, 17 Mar 2020 11:28:53 GMT
Content-Length: 12
Content-Type: text/html

Teste

Note que por padrão ele retornou Content-Type: text/html e o navegador vai ASSUMIR que tem que processar como HTML, isso se chama cabeçalho, e mesmo que o conteudo não correspondesse ao que foi dito no cabeçalho o navegador irá assumir conforme o que foi dito nele, para resumir o PYTHON gerou um HTML, ou seja o Python roda no back-end e o framework escolhido gera o conteudo.
Você poderia até gerar imagens, vídeos e outras coisas e devolver com Flask, isto seria baixado pelo seu navegador e se ele for capaz de processar no navegador ele irá exibir, você "não vê" o download ocorrendo diretamente, mas ele ocorre sempre, qualquer coisa que você acessa na internet é feito o download para o seu computador, fique ele na "memória" ou gravado em cache
Answer: Programas em Python não são, normalmente, adicionados diretamente a uma página HTML - eles podem Gerar páginas HTML ou dados que serão renderizados por código em javascript.
VOcê interage com seus programas em Python a partir do terminal, fazendo programas que criem uma interface gráfica, ou programas que geram o HTML completo - preenchendo valores com o uso de templates - você pode dar uma olhada no projeto "Flask" para alguns exemplos mais simples de como fazer isso.
Até é possível embutir código Python direto dentro de HTML, como é feito com Javascript, com o uso de projetos alternativos - um deles é o Brython (https://brython.info) - não é a forma que a maioria das pessoas estuda Python, mas pode funcionar se você está com isso em mente.
Mesmo indo pela via do Brython, é importante - vital - que você estude e entenda a relaçao normal de código Python com páginas web.


Does the chance of serious injury when road biking decrease with speed?

Question: When riding a road bike at high speed, for instance in the Tour de France, I have heard that the severity of injuries tend to be decreased as speed increases, as this allows the cyclist to "roll", and somehow this decreases the chance of breaking bones for example. This seems contrary to my basic knowledge of physics and momentum, so, is it true?
Comment: I, for one, would prefer to fall off a stationary bike than one traveling at 35mph.
Comment: @Criggie Haha, we think alike.
Comment: Do you have a source of what you have "heard?" This would be a very interesting read.
Comment: Well actually this was more of an argument with a friend who claimed to have heard it on Tour de France commentary frequently, and when I asked him for a source, the bottom paragraph of this article was the best he came up with: http://www.bikeradar.com/fitness/article/technique-crashing-for-dummies-24316/
Comment: I prefer not to fall off at all...
Comment: I, for one, prefer to not fall at all.
Answer:
Does the chance of serious injury when road biking decrease with speed?

No. Risk for serious injury increases with increasing speed. If a vehicle crashing at relatively low speed has a high risk of serious injury, I cannot imagine how increased speed would yield decreased risk of serious injury.

The reason slow crashes can sometimes hurt the most is that you don't have any momentum in your body to roll or spin out of it - instead, you hit the floor square on and your elbow and hip take all the impact..

Perhaps the cited technique gives you a chance (if any) to avoid serious injury. However, this does not mean that increased speed decreases risk of serious injury.


Erro 404 Not Found (nginx)

Question: Tenho um blog e de um dias para cá começou a dar o seguinte erro em algumas páginas.
<code>           404 Not Found  nginx/1.6.2 (Ubuntu)
</code>
O log de erro esta retornando:
<code>           2016/02/02 10:44:12 [error] 612#0: *553172 connect() to unix:/var/run/php5-fpm.sock failed
           (11: Resource temporarily unavailable) while connecting to upstream, client: xxx.xxx.x.xxx, server:
           www.blogdeti.com.br , request: "POST /xmlrpc.php HTTP/1.0",
           upstream: "fastcgi://unix:/var/run/php5-fpm.sock:", host: "xxx.xxx.xxx.xxx"
</code>
Minhas configurações do virtual host:
<code>            server {
    listen 80 default_server;
    listen [::]:80 ipv6only=on  default_server;

    root /var/www/html;

    index index.php index.html index.htm index.nginx-debian.html;

    server_name www.blogdeti.com.br;

    location / {
            try_files $uri $uri/ /index.php?q=$uri&args;
    }
    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
    root /var/www/html;
    }
           location ~ \.php$ {
    try_files $uri =404;
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    #fastcgi_pass 127.0.0.1:9000;
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
    }
 }
</code>
Minha hospedagem é a digital ocean e já tentei mandar um ticket de suporte, mas eles não conseguiram me ajudar.
Comment: Chegou a ver as configurações no `sites-enable`? parece que não esta encontrando a raiz do site
Comment: Sim, vou colocar as configurações do virtual host na pergunta.
Answer: Vejo o seu log e tenho a seguinte analise:
O arquivo ou o caminho para o mesmo está ...
Vamos analisar a tradução do erro

Vamos analisar a tradução do erro :::

<code>02/02/2016 10:44:12 [erro] 612 # 0: * 553172 conectar () ao unix: /var/run/php5-fpm.sock falhou
   (11: Recurso temporariamente indisponível) durante a conexão com o upstream, cliente: xxx.xxx.x.xxx, servidor:
   www.blogdeti.com.br, solicitação: "POST /xmlrpc.php HTTP / 1.0",
   upstream: "fastcgi: // unix: /var/run/php5-fpm.sock:", host: "xxx.xxx.xxx.xxx"
</code>
A solução do problema é o seguinte...
Verificar a porta
E se os dados... O nome de servidor esta faltado
a versão sem WWW.
www é um redirecionamento diferente nas configurações DNS
Acessando
<<< http://www.
ou https://blogdeti.com
Isso é a parte de reditrecionamento. E isso se define um padrao. Quando configura o SSL.
Os mais populares LtsC como tambem CloudFlare
Ao contrario de um nome de host...
host.dominio.com

Erro 404 Not Found (nginx)


About the hessian of a hamiltonian function of a hamiltonian torus action

Question: I am trying to understand several claims about the hessian of a hamiltonian function associated to a fundamental field, appearing in Lemma 5.54 of McDuff-Salamon's "Intro to symplectic topology".
(Summary of context: The torus $\mathbb{T}^m$ acts on a symplectic manifold $(M, \omega)$ and the action be hamiltonian (in the sense of McDuff - Salamon, i.e. the map sending elements in the Lie algebra of the torus to their corresponding Hamiltonian functions with the Poisson bracket is a Lie algebra homomorphism). Let $H$ be a hamiltonian function associated to some fixed $\theta \in \mathfrak{t} = Lie(\mathbb{T}^m)$ i.e. $dH = i_{X_H} \omega$, where $X_H$ is the fundamental vector field associated to $\theta$. Also, we have $J$ an almost complex structure compatible with $\omega$ and invariant under the action.)
If $x$ a fixed point of the action (so a critical point of $H$ (proven earlier)) they look at $d_x X_H:T_xM \rightarrow T_{X_H(x)} (T_xM)$ which they claim is $-J_x \nabla_x^2 H $. Not only can't I prove this calim, but it doesn't even make sense to me, because $-J_x \nabla_x^2 H \in End(T_xM) $, so an identification of $T_{X_H(x)}(T_xM)$ with $T_xM$ would be needed, but they don't specify a canonical one and I can't see one. Then, in what sense is $d_x X_H$ even a vector field, given that it doesn't associate to a point $v \in T_x M$ a vector in $T_v (T_x M)$ but in $T_{X_H(x)} (T_x M)$?
So, condensed, this is my main question:

What does it mean that $d_x X_H = - J_x \nabla_x^2 H$ and why is this so? (more on this one down below, in the paragraph about the Guillemin-Sternberg approach)

Furthermore, denoting the action as $\tau \cdot x =: \psi_{\tau}(x)$, they next claim

that the $1$-parameter group of $d_x X_H$ is $d_x \psi_{t \theta}$
that it is also $exp(-tJ_xS_x)$ (which I'm assuming is matrix exponentiation, not the geodesic exponential w.r.t. the induced metric).

Why do these hold?
Guillemin-Sternberg follow a similar path in Theorem 32.6 of "Symplectic techniques in physics", but there they don't really look at $d_x X_H$ but they firstly take $\phi_t$ the flow of $X_H$ and consider $L:= \frac{d}{dt} |_{t=0} (\phi_t(x)): T_xM \rightarrow T_xM$ (this again makes sense because $x$ is fixed). This eliminates the problem of the needed identification at least. Then they claim that $(H_{**}(x))(v, v) = \omega_x (Lv, v)$, $H_{**}$ being the hessian as a bilinear form. I can easily find that an $L$ satisfying this equality must be precisely $-J_x\nabla_x^2 H$, using the definition of $\nabla_x^2H$ via the invariant metric defined by $\omega$ and $J$. But why is the $L$ defined as before precisely the $L$ satisfying the last equality? I suspect a good expression of $H_{**}(x)(v,v)$ is needed. Of course, $H_{**}(x)(v,v)= v(i_{X_H} \omega (\tilde{v}))$, with $\tilde{v}$ a vector field extending $v$, but does this help in any way?
I also think this good expression is needed to see that $J_x \nabla_x^2 H = \nabla_x^2H J_x$, which is another point I'm unable to prove further on in the McDuff-Salamon lemma.
Answer: The notation in both of your sources is somewhat mysterious to me, but it seems clear that $d_xX_H$ is not referring to the differential of $X_H:M\to TM$. Instead, it is referring to the $(1,1)$ tensor $\nabla X_H(x)$. The two are only tenuously related, in that for $v\in T_xM$, $\nabla_vX_H$ can be identified with the vertical part of $d_xX_H(v)$ through various canonical maps. Note that $\nabla X_H(x)$ is independent of the choice of metric, at least, since $x$ is a zero of $X_H$.
Also, the Hessian  $\nabla^2H(x)$ is generally interpreted as a $(0,2)$ tensor rather than a $(1,1)$ tensor. It seems the notation $\nabla^2_xH$ is instead referring to the hessian with an index raised using the metric $g$. $\nabla^2H(x)$ is also independent of the choice of metric, since $x$ is a critical point of $H$.
To your second question, $\nabla X_H(x)$ is indeed the generator of the group action $d_x\psi_t:T_xM\to T_xM$. Since this is a linear $\mathbb{R}$-action, it suffices to show that $\nabla_vX_H=\frac{d}{dt}(d_x\varphi_t(v))_{t=0}$ for all $v\in T_xM$. To show this, we can define a vector field $V$ with $V(p)=v$ and use Lie derivatives:
$$\begin{align}
\frac{d}{dt}(d_x\varphi_t(v))_{t=0}=&-\frac{d}{dt}(d_x\varphi_{-t}(v)-v)_{t=0} \\
=&-\frac{d}{dt}(d_x\varphi_{-t}(V)-V)_{t=0}(x) \\
=&-(\mathcal{L}_{X_H}V)(x) \\
=&-[X_H,V](x) \\
=&-\nabla_{X_H}V(x)+\nabla_VX_H(x) \\
=&\nabla_vX_H
\end{align}$$
If you're familiar with abstract index notation, it might be useful in working with these tensor identities. For instance, the equality in the first question, as I've interpreted it, is $\nabla_bX_H^a=J^a{}_cg^{cd}\nabla_d\nabla_bH$. To show this, let $\omega^{ab}$ denote the inverse of $\omega_{ab}$, satisfying $\omega^{ab}\omega_{bc}=\delta^a_c$. We can rewrite the definition of the Hamiltonian vector field $X_H^a\omega_{ab}=\nabla_bH$ as $X_H^a=-\omega^{ab}\nabla_bH$ and rewrite the compatibility condition $g_{ab}=\omega_{ac}J^c{}_b$ as $\omega^{ab}=J^a{}_cg^{cb}$.
$$
X_H^a=-\omega^{ac}\nabla_cH \\
\implies\nabla_bX^H_a=-\omega^{ac}\nabla_b\nabla_cH-\nabla_b\omega^{ac}\nabla_cH \\
=-\omega^{ac}\nabla_c\nabla_bH-\nabla_b\omega^{ac}\nabla_cH \\
=-J^a{}_d(g^{dc}\nabla_c\nabla_bH)-\nabla_b\omega^{ac}\nabla_cH
$$
The first term gives the desired equality, since the second term vanishes at $x$.
Comment: Indeed the hessian is defined via $g(\nabla^2H(x)(v), w) = v(w(H))$ w/ $w$ extended to a v.f.

So in $dX_H(x) = \nabla X_H(x)$, is $\nabla$ the Levi-Civita connection assoc. to $g$?
If so, I can follow your computation for the second question, using that $\nabla$ is torsion free. But I still don't see why $\nabla_* X_H(x)= -J_x \nabla^2_x H (*)$, which is what I'm now understanding the first claim to be.
Comment: Yes, $\nabla$ is the Levy-Civita connection of $g$ throughout. I've added a bit more detail on showing the equality $\nabla X_H=-J\nabla_x^2H$.


Why I got different results using Proc Phreg with Counting process input style and regular input?

Question: I am new to survival analysis and now trying to learn counting process input style. I am using the same dataset, but when using proc phreg, the couting process input and regular input is very different. Here is my first several lines in the dataset:
The regular one:

Here is the counting process input style, these 2 are basically the same

here is the code:
Proc phreg data=ds;
class covar;
model followup*event(0)=covar / entry=delay_entry;
run;
proc phreg data=ds;
class covar;
model (start, end)*event(0)=covar;
run;
Why the results are so different?  Any idea would be appreciated. Thank you!
Comment: try ``proc phreg data=ds; class covar; model (delay_entry,followup)*event(0) =covar; run;``
Comment: Wow, that works! Thank you So much!!!Would you mind to explain to me why this is happening? the interval of (delay_entry,followup) and (Start, end) are the same, what's the story behind this issue?
Answer: In Cox proportional hazard model, there is unspecified baseline hazard function $\lambda_0(t)$. It is not constant and is the function of time. For subject id=11, the first table says the subject went through from $t_1 = 62$ to $t_2=243$. So the subject should has the hazard $\lambda_0(t)exp(X\beta)$, for $ t=62 \text{ to } 243$. From table 2, the subject has the hazard $\lambda_0(t)exp(X\beta)$, for $ t=0 \text{ to } 181$.
Because $\lambda_0(t)$ is not a constant, so in this case $\lambda_0(0) \ne \lambda_0(62)$.
Therefore, your two statements fit two different models.
In SAS, model t2*event(0)=X / entry=t1; and model (t1, t2)*event(0)=X are the exact same if you use them on the same dataset. If you replace the first model by Proc phreg data=ds; class covar; model end*event(0)=covar / entry=end; run;, you will get the same results generated by your second model.
Comment: Thank you So much. This is really helpful. I was shifting all the timelines by transforming data to the second table, and eventually create a different study. Thanks again!