Integral including an Incomplete Gamma function

Question: Does anyone have an idea of solving following integral
$$ I =\int_{0}^{\infty}\frac{x\Gamma \left(a,b x\right)}{(x^2+1)}\,dx\,,$$
where $a,b>0$ are positive real values?
Mathematica gives an answer, but I do not know how it can be derived by using integral tables.
\begin{align}
I=&\frac{1}{{2 a (a+1)}}\biggl(\pi  (a+1) b^a \csc \left(\frac{\pi  a}{2}\right) \, _1F_2\left(\frac{a}{2};\frac{1}{2},\frac{a}{2}+1;-\frac{b^2}{4}\right) \\ &+a b \left((a+1) b \Gamma (a-2) \, _2F_3\left(1,1;2,\frac{3}{2}-\frac{a}{2},2-\frac{a}{2};-\frac{b^2}{4}\right)-\pi  b^a \sec \left(\frac{\pi  a}{2}\right) \, _1F_2\left(\frac{a}{2}+\frac{1}{2};\frac{3}{2},\frac{a}{2}+\frac{3}{2};-\frac{b^2}{4}\right)\right)+2 \Gamma (a+2) (\psi ^{(0)}(a)-\log (b))\biggr)
\end{align}
Eq. 184.108.40.206 in Integrals and Series [Vol 2 - Spl Functions] - A. Prudnikov would be one of the closet answer, but I could not match parameters well.
Answer: Assuming that $a$ is a positive integer and $b>0$, considering
$$I_a =\int_{0}^{\infty}\frac{x}{x^2+1}\,\Gamma \left(a,b x\right)\,dx$$ there is only one which is simple
$$I_1=\frac{\pi}{2}   \sin (b)-(\text{Ci}(b) \cos (b)+\text{Si}(b) \sin (b))$$ where appear the since and cosine integral functions.
The problem is that, for $a>1$, it seems that the result can only be expressed in terms of the Meijer G function.
The case of $a=2$ is
$$I_2=\frac {1}{\sqrt \pi}\,G_{1,3}^{3,1}\left(\frac{b^2}{4}|
\begin{array}{c}
 0 \\
 0,0,\frac{3}{2}
\end{array}
\right)$$
For $a>2$, we have
$$I_a=\frac {2^{a-2}}{\sqrt \pi}\, G_{2,4}^{4,1}\left(\frac{b^2}{4}|
\begin{array}{c}
 0,1 \\
 0,0,\frac a 2,\frac{a+1}{2}
\end{array}
\right)$$
Edit
As written in comments, for rational values of $a$ we have quite nasty results. As an example, for $a=\frac 32$, the result given by a CAS is
$$2I_{\frac 32}=-\sqrt{\pi } \left(2 b^2 \,
   _2F_3\left(1,1;\frac{3}{4},\frac{5}{4},2;-\frac{b^2}{4}\right)+\log (4b)+\gamma
   -2\right)+\pi ^{3/2} \left(C\left( \sqrt{\frac{2b}{\pi
   }}\right)-S\left( \sqrt{\frac{2b}{\pi }}\right)\right)+ \pi \sqrt{2b}
    (\sin (b)-\cos (b))$$
Comment: 1. Transform $\frac{x}{1+x^2}$ to MeijerG -> MeijerGReduce
2. Transform $\Gamma \left(a,b x\right)$ -> MeijerGReduce
3. Reduce the quadratic Argument of the two MeijerG Funktions with
[Mathematical Functions Site](https://functions.wolfram.com/HypergeometricFunctions/MeijerG/17/02/03/0004/)
4. Solve the Integral with [Mathematical Functions Site](https://functions.wolfram.com/HypergeometricFunctions/MeijerG/21/02/03/01/)
H-Fox-Function for Mathematica on request.
Comment: @Frey: If you have problems with the derivation or you need the H-Fox-function for Mathematica, please let me know.
Comment: @stocha. I have written $1/(x^2+1)$ and $\Gamma(a,bx)$ by MeijerG and got the answer with H-Fox-function like $H_{3,2}^{1,3}(.)$. But I do not know how to implement it in MATLAB or Mathematica. There is no built-in function in software packages.
Comment: In my case, $a$ is not an integer :( sorry I could not mention it in the original post! But this solution maybe helpful for some applications.
Comment: @Frey. If $a$ is a retional number, probably hypergeometric functions plus a bunch of terms.
Comment: If $a\geq 1$ is an integer, you can use $$
\Gamma (a,bx) = \Gamma (a)\sum\limits_{k = 0}^{a - 1} {\frac{{(bx)^k }}{{k!}}e^{ - bx} }
$$ to obtain $$
 - \frac{{\Gamma (a)}}{2}\sum\limits_{k = 0}^{a - 1} {(k + 1)(ib)^k \left( {e^{ib} \Gamma ( - 1 - k,be^{\frac{\pi }{2}i} ) + ( - 1)^k e^{ - ib} \Gamma ( - 1 - k,be^{ - \frac{\pi }{2}i} )} \right)}
$$ for the integral ($\Re b >0$).
Comment: @Gary. Thank you for this (and so many other things !). I used Meijer functions since it is the most compact writing. Have you any idea for any $a$ (this seems to be the question). I tried with rational values and obtained results (not pleasant at all). Cheers :-)
Comment: @ClaudeLeibovici. Is it possible for you to share any results you got for any $a$?
Comment: @Frey. What do you mean by *share* ? Do  you want some numerical values (in this case, give me a value of $a$ and a range for $b$). Please, clarify. Cheers :-)
Comment: @ClaudeLeibovici. I thought you got some "I tried with rational values and obtained results (not pleasant at all)" :)
Comment: @Frey. Sorry ! I misunderstood. I shall put a few in the post.
Comment: I guess it should be a H - Fox function for any a. This is easily seen by the structure of the Meijer function
Comment: @stocha. Have you got any solution for any $a$? Can you please post?
Comment: @Frey: I have an implementation of the H-Fox-Function in Mathematica, using Mellin–Barnes type integral and  by Meijer G functions ( a = k/l, l,k integer) moreover there is also another  version available in the community of wolfram, I did not test jet. I may send you my version, it is up to you. Therefore I need an email adress. Moreover I suggest you to read  [Mathai](https://www.researchgate.net/profile/Hans_Haubold/publication/266566090_The_H-function_Theory_and_Applications/links/00b4952b1bf090889c000000/The-H-function-Theory-and-Applications.pdf?origin=publication_detail)
Comment: @Frey: Mathai is a great reference for properties of H-Fox-Function, because it is not out of the question, that a reduction formula or other special cases exsists.
Comment: @stocha. The H-function I got has a form of $$H_{3,2}^{1,3}\left(\frac{1}{b^2} \left|
\begin{array}{c}
 (0,1),(-1,2),(-1-a,2) \\
 (0,1),(-2,2) \\
\end{array}
\right.\right)$$ where $a>0$ is not an integer and $b>0$. Can you please check whether your code works for this? Can you please post your code here? I do not think that we can share email here :(
Comment: @Frey.: Please take a look at my post - the last one on the side: [Wolfram Community](https://community.wolfram.com/groups/-/m/t/2243766)
Comment: Is this the correct way to pass parameters to calculate above H function? $FoxH[\{\{\{0, 1\}, \{-1, 2\},\{-1 - a, 2\}\}, \{\{\} \}\}, \{\{\{0, 1\}\}, \{\{-2, 2\}\}\},1/b^2, ...,...,...]$. I did not get output :(
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/122988/discussion-between-stocha-and-frey).
Comment: @Frey, did you received my emails, just to know?


How to create shadow only left and right side, on a line?

Question: i have a line of width: 15px; and height of 2px;
my question is, how to create the shadow only on right and left side?
Comment: I've always done that with images; I'd be interested to see if it's even possible with CSS.
Comment: required field validation message: [this is done with the css](http://blogtrottr.com)
Answer: This fiddle has examples showing shadows only on:

Top and bottom
Left and right
Top

With that you should be able to do any kind of shadow.
http://jsfiddle.net/rafaelchiti/5jdHW/
The code:
div {
  margin-top: 20px;
  margin-left: 20px;
  width: 100px;
  height: 100px;
}

.horizontal {
  box-shadow: 0px 15px 10px -11px rgba(0, 0, 0, .1) inset,
              0px -15px 10px -11px rgba(0, 0, 0, .1) inset;
}

.vertical {
  box-shadow: 0px 15px 10px -11px rgba(0, 0, 0, .1) inset,
              0px -15px 10px -11px rgba(0, 0, 0, .1) inset;
}

.one-side {
  box-shadow: 0px 15px 10px -11px rgba(0, 0, 0, .1) inset;
}

Hope this help.
Answer: Try this (based on the link you gave in your comment above):
box-shadow: 2px 2px 5px 2px rgba(0, 0, 0, 1);
-webkit-box-shadow: 2px 2px 5px 2px rgba(0, 0, 0, 1);

You can tweak it to how you like it using the CSS3 Generator
Comment: No problems :) glad I could help
Answer: CSS Box Shadow
Add the following class to apply shadow. Check this jsfiddle example
.shadow {
  -moz-box-shadow:    3px 3px 10px 1px #000;
  -webkit-box-shadow: 3px 3px 10px 1px #000;
  box-shadow:         3px 3px 10px 1px #000;
}

The horizontal offset of the shadow, positive means the shadow will
be on the right of the box, a negative offset will put the shadow on
the left of the box.
The vertical offset of the shadow, a negative one means the
box-shadow will be above the box, a positive one means the shadow
will be below the box.
The blur radius (optional), if set to 0 the shadow will be sharp,
the higher the number, the more blurred it will be.
The spread radius (optional), positive values increase the size of
the shadow, negative values decrease the size. Default is 0 (the
shadow is same size as blur).
Color Hexadecimal color value.
Comment: Hi, the box shadow support -ve values also. So you can adjust the values for making it to the left. But you cannot directly put the shadow on the left and right only. Instead of that try making two boxes and apply shadow for that. [Example for doing that](http://jsfiddle.net/libinvbabu/krhG7/16/)
Comment: this link shows the shadow on right and bottom of div. i want only right and left shadow.
Answer:         .box {
            height: 150px;
            width: 300px;
            margin: 20px;
            border: 1px solid #ccc;
        }

        .top {
            box-shadow: 0 -5px 5px -5px #333;
        }

        .right {
            box-shadow: -5px 0 5px -5px #333;
        }

        .bottom {
            box-shadow: 0 5px 5px -5px #333;
        }

        .left {
            box-shadow: 5px 0 5px -5px #333;
        }

        .all {
            box-shadow: 0 0 5px #333;
        }

in the body put..


What is the point of diverging functions in Rust?

Question: I have read several answers on SO already, and gathered these use-cases:

When a function panic!s
When a function has an infinite loop in it

But it is still unclear to me why we need to define the function like this:
fn func() -> ! {
    panic!("Error!");
}

if it will work the same way as this (without the exclamation sign):
fn func() {
    panic!("Error!");
}

and at the same time, why do we need to use ! in functions with infinite loops? It look like this signature doesn't bring any real usage information.
Answer: The main difference between these signatures boils down to the fact that ! can coerce into any other type, and thus is compatible with any other type (since this code path is never taken, we can assume it to be of any type we need). It's important when we have multiple possible code paths, such as if-else or match.
For example, consider the following (probably contrived, but hopefully clear enough) code:
fn assert_positive(v: i32) -> u32 {
    match v.try_into() {
        Ok(v) => v,
        Err(_) => func(),
    }
}

When func is declared to return !, this function compiles successfully. If we drop the return type, func will be declared as returning (), and the compilation breaks:
error[E0308]: `match` arms have incompatible types
 --> src/main.rs:8:19
  |
6 | /     match v.try_into() {
7 | |         Ok(v) => v,
  | |                  - this is found to be of type `u32`
8 | |         Err(_) => func(),
  | |                   ^^^^^^ expected `u32`, found `()`
9 | |     }
  | |_____- `match` arms have incompatible types

You can also compare this with definition for Result::unwrap:
pub fn unwrap(self) -> T {
    match self {
        Ok(t) => t,
        Err(e) => unwrap_failed("called `Result::unwrap()` on an `Err` value", &e),
    }
}

Here, unwrap_failed is returning !, so it unifies with whatever type is returned in Ok case.
Comment: You're trying to do the opposite - coerce `i32` (the default integer type) into `!`. This obviously can't work. "Compatibility" here is one-directioned - "value" of type `!` (non-existant by definition) can be used wherever any other type is expected, not the other way around.
Comment: @AleksandrNovik: This has nothing to do with dynamic typing. `!` is a *bottom type*, not a dynamic type, i.e. it is a type which is a subtype of every other type.
Comment: The reason it doesn't work like dynamic typing is that "!" is a promise that the function will NEVER return. Because of that, we can pretend it would have returned whatever type we want; this will never cause a problem since it never returns. That's why your example isn't allowed. Because it's not _actually_ dynamic typing.
Comment: It seems to me like `!` lets us to achieve something like dynamic typing. But at the same time, this doesn't work: `fn func() -> ! { 123 }`, although you said that __! can coerce into any other type, and thus is compatible with any other type__
Answer: The compiler knows that anything that follows a diverging expression (w.r.t. evaluation order) is unreachable. It can use this information to avoid false negatives when it comes to deciding whether a local variable is initialized or not.
Consider the following example:
use rand; // 0.8.4

fn main() {
    let foo;
    if rand::random::<bool>() {
        foo = "Hello, world!";
    } else {
        diverge();
    }
    println!("{foo}");
}

fn diverge() {
    panic!("Crash!");
}

We declare a variable foo, but we only initialize it in one branch of the if expression. This fails to compile with the following error:
error[E0381]: borrow of possibly-uninitialized variable: `foo`
  --> src/main.rs:10:15
   |
10 |     println!("{foo}");
   |               ^^^^^ use of possibly-uninitialized `foo`

However, if we change the definition of our diverge function like this:
fn diverge() -> ! {
    panic!("Crash!");
}

then the code successfully compiles. The compiler knows that if the else branch is taken, it will never reach the println! because diverge() diverges. Therefore, it's not an error that the else branch doesn't initialize foo.


Sum of diagonal kth order matrix minors

Question: I am interested in computing the sum of all digonal kth order minors of a matrix.
By this I mean that I have an $n\times n$ matrix $A$, and I define the diagonal kth order minors as determinants of the matrices $A_{I,I}$ where $I$ is some ordered set of $n-k$ non-repeating integers between $1$ and $n$. I then want to compute
\begin{equation}
\sum_{I} \det A_{I,I},
\end{equation}
over all distinct integer sets $I$ with values between $1$ and $n$.
I can of course compute these minor determinants 1 by 1 and sum but I was wondering if this quantity reduces to some property of the full original matrix $A$, or whether it can be computed via matrix multiplication and traces, rather than computing a large number of determinants.
For some context: I am a physicist computing free-fermion correlators which can be computed via determinants. The expression I am trying to compute corresponds to tracing over all intial and final states with a fixed fermion filling.
Comment: Yes. The proof is simple. E.g. see the discussion in [Horn and Johnson](https://books.google.com/books?id=PlYQN0ypTwEC&pg=PA42&lpg=PA42&dq=sum+of+principal+minors+symmetric+function&source=bl&ots=uCnSbB0YyO&sig=kYblgx-at7BNEOeVqnOWZ9nzgPg&hl=zh-TW&sa=X&ved=0ahUKEwj-u5arqpHaAhXEEpQKHQ__CM44ChDoAQgpMAA#v=onepage&q=sum%20of%20principal%20minors%20symmetric%20function&f=false) after definition 1.2.9.
Comment: A lot of people would still call these principal minors, even if they're not $(n-1) \times (n - 1)$ minors. In case you didn't know, the sum $\sum_I \det A_{I,I}$ (where the sum is over subsets containing $n-k$ elements), is equal up to sign to the coefficient of $x^k$ in the characteristic polynomial of $A$.
Comment: This is not a duplicate question. I am not interested in principal minors. I am interested in kth order minors, that is, removing more than 1 row/column.
Comment: Have you read the answer in the duplicate?
Comment: OK, I think I understand. You're saying that what I'm looking for is exactly, $s_{n-k}$, the sum of products of eigenvalues? I will certainly look up this proof.
Comment: Yes I think I understand the terminology now. I think I was mixing things up. Thanks for the comments!
Answer: This answer was provided in the comments of Sum of principal minors as was kindly pointed out above.
The answer is:
The sum of all $k^\text{th}$ principal minors of a matrix $A$ is equal to the $k^\text{th}$ elementary symmetric polynomial of its eigenvalues.
More explicitly, a $k^\text{th}$ principal minor is the determinant of a $k\times k$ submatrix of $A$ formed by removing the same rows as columns. The elementary symmetric polynomials $e_k(\{\lambda_i\})$ are the sums of products of all disctint products of $\{\lambda_i\}$ of length $k$. As an example
\begin{equation}
e_2(\lambda_1, \lambda_2, \lambda_3,\lambda_4) = \lambda_1 \lambda_2 + \lambda_1 \lambda_3 + \lambda_1 \lambda_4 + \lambda_2 \lambda_3  + \lambda_2 \lambda_4 + \lambda_3 \lambda_4.
\end{equation}

Sum of diagonal kth order matrix minors


If a linear combination of vectors u and v produce vector b, are there also an infinite number of valid combinations?

Question: This problem comes from Strang's Introduction to Linear Algebra.
Question 29 from Strang Chapter 1
Official solution to Question 29 from Strang Chapter 1
It makes sense to me for three vectors if I solve them algebraically. However, it states that it works even if u = 0, which I interpret as essentially being only two vectors. How does this work? You can set up two row equations and only get back one value.
For example, taking v and w directly from the question:
$2x + y = 0$
$7x + 5y = 1$
$x = -1/3$ and $y = 2/3$
How could there be an infinite number of combinations here?
Comment: if u=0 then you can take 1*u+(linear combination of the other two) or 2*u+(lcotot) or 3*u+(lcotot), etc. thus resulting in infinitely many
Answer: Suppose $u = 0, v+w = b$.
Then $$u+v+w = 5u+v+w = -3u+v+w = b$$ and so on. The coefficient in front of $u$ can be anything you like, so there are infinitely many possibilities.
Also - the easiest example for why you won't always have infinitely many possible combinations is $u=v=w=0$. Then any linear combination will always be zero (and never $b$).


Read multiple CSVs with different headers into one single dataframe

Question: I have a few CSV files where some files might have some matching columns and some have altogether different columns.
For Example file 1 has the following columns:

['circuitId', 'circuitRef', 'name', 'location', 'country', 'lat', 'lng', 'alt', 'url']

and file2 has the following columns :

['raceId', 'year', 'round', 'circuitId', 'name', 'date', 'time', 'url']

I want to create a dataframe that will have all these columns. I wrote the following code hoping that mapping between pre-defined schema and CSV file headers will automatically take place, but it did not work out.
sch=StructType([StructField('circuitId',StringType(),True),
StructField('year',StringType(),True),
StructField('name',StringType(),True),
StructField('alt',StringType(),True),
StructField('url',StringType(),True),
StructField('round',StringType(),True),
StructField('lng',StringType(),True),
StructField('date',StringType(),True),
StructField('circuitRef',StringType(),True),
StructField('raceId',StringType(),True),
StructField('lat',StringType(),True),
StructField('location',StringType(),True),
StructField('country',StringType(),True),
StructField('time',StringType(),True)
])

df=spark.read \
        .option('header','true') \
        .schema(sch) \
        .csv('/FileStore/Udemy/Formula_One_Raw/*.csv')

with this code I am getting the following output :
Comment: Did you try creating two dataframes and then join them on circuitId column.
Comment: No, actually I want separate rows for each file,
Comment: Could you add a table of your desired output with some sample data in it?
Answer: The CSV format uses positions, not names, of the columns to resolve the schema, so if you have a file with 8 columns, like:
['raceId', 'year', 'round', 'circuitId', 'name', 'date', 'time', 'url']

and the first 8 fields of schema you are trying to apply are:
StructField('circuitId',StringType(),True),
StructField('year',StringType(),True),
StructField('name',StringType(),True),
StructField('alt',StringType(),True),
StructField('url',StringType(),True),
StructField('round',StringType(),True),
StructField('lng',StringType(),True),
StructField('date',StringType(),True)

then raceId will be inferred as circuitId, round as name and so on. You can do the following thing to resolve this:

Create separate schema for every distinct file, taking into account what columns are there, and add the ones that are not part of this particular schema at the end - this way they should be included in your DataFrame, and filled with NULL.

So for the example CSV schema at the top, you can declare the schema like so:
StructField('raceId',StringType(),True),
StructField('year',StringType(),True),
StructField('round',StringType(),True),
StructField('circuitId',StringType(),True),
StructField('name',StringType(),True),
StructField('date',StringType(),True),
StructField('time',StringType(),True),
StructField('url',StringType(),True),
StructField('alt',StringType(),True),
StructField('lng',StringType(),True),
StructField('circuitRef',StringType(),True),
StructField('lat',StringType(),True),
StructField('location',StringType(),True),
StructField('country',StringType(),True)

And your DataFrame should look like so:
+------+----+-----+---------+--------------------+----------+--------+--------------------+----+----+----------+----+--------+-------+
|raceId|year|round|circuitId|                name|      date|    time|                 url| alt| lng|circuitRef| lat|location|country|
+------+----+-----+---------+--------------------+----------+--------+--------------------+----+----+----------+----+--------+-------+
|     1|2009|    1|        1|Australian Grand ...|2009-03-29|06:00:00|http://en.wikiped...|null|null|      null|null|    null|   null|
+------+----+-----+---------+--------------------+----------+--------+--------------------+----+----+----------+----+--------+-------+

After all your data has been read to DataFrames, you will be able to union them using column names, if needed.


Como passar o valor de uma variável em PHP em um lugar fixo?

Question: Boa noite senhores estou me aventurando no mundo do PHP e me deparei com um problema que ainda não consegui resolver.
Fiz uma conexão em PHP que conecta em um servidor TELNET e me retorna os valores lidos em uma variavel dentro de um While, com isso eu uso um echo para imprimir a menssagem na tela para acompanhar o conteudo da mensagem.
   while ($line = fgets($socket,7170)){
    $line = trim($line);
    echo $line."
";
}

algo assim, porém o resultado é que ele gera uma linha nova com a resposta.
Eu gostaria de saber uma maneira de imprimir essa variável sempre no mesmo local.
Como se fosse um campo dizendo " STATUS: $VALOR DA VARIAVEL AQUI"
para que sempre que mudasse o valor atualizasse ali e não criar um novo echo.
Comment: Como isso é atualizado?
Answer: Existe duas maneiras de se fazer isso.
Primeiro você tirando a tag
 que assim evitaria que o seu loop fizesse que o valor pulasse de linha, porém, se você quer os valores todos na mesma variável tu poderia está fazendo da seguinte forma:
$line = "";
while ($line = fgets($socket,7170))
{
    $line .= trim($line);
}

echo $line;

Comment: a questão do .= eu entendi agora, obrigado por compartilhar comigo essa informação.

O ponto agora é que esse while executa constantemente recebendo o status do meu servidor.

só que ao colocar como está no código, não mostra informação nenhuma.

A minha ideia é que como se fosse um html tivesse um campo com status e ali mudasse sempre com o servidor.
Comment: não sei porque mas não imprimiu os valores nessa estrutura, se eu colocar o echo dentro do while, ele imprime sempre que muda porém, fica em sequência é como se ficasse $line$line$line$line$line$line$line$line$line$line$line$line$line$line$line(o valor da variável) na página. O que eu quero saber é como o valor sobrescrever o valor impresso anteriormente.
Comment: Se você utilizar ```=``` você reatribui o valor na variavel, porém, quando você utiliza ```.=``` você concatena o valor na varialve.
Comment: Eu entendi, mas a resposta foi a solução da sua pergunta? Se sim, por favor marque-a como a solução para ajudar outros usuários também.


Does every $C^1$ closed differential form differ from some $C^\infty$ closed form by an exact form?

Question: Question:
On a $C^\infty$ manifold, does every $C^1$ closed differential form differ from some $C^\infty$ closed form by an exact form?
Motivation:
This result holds for $C^1$ closed 1-forms on a $C^\infty$ manifold $M$ for which the first singular homology is finitely generated (e.g., all compact manifolds).
Proof:
Let $\omega$ be any $C^1$ closed form on $M$. Let $\sigma_1,\ldots,\sigma_k$ be a $C^\infty$ basis for $H_1(M;\mathbb{R})$ and $[\theta_1],\ldots,[\theta_k] \in H_{dR}^1(M)$ be the dual basis (identifying $H_{dR}^1(M)$ with $Hom(H_1(M;\mathbb{R}),\mathbb{R})$ via the de Rham theorem), where $\theta_1,\ldots,\theta_k$ are $C^\infty$ forms. For $1 \leq i \leq k$, define $c_i := \int_{\sigma_i} \omega$. Then the one-form $\alpha := \omega - c_1 \theta_1 \ldots - c_k \theta_k$ satisfies $\oint_\gamma \alpha = 0$ for any closed loop $\gamma$, since $\gamma$ is a cycle and is thus a finite $\mathbb{R}$-linear combination of the $\sigma_i$ and the integral of $\alpha$ over all $\sigma_i$ is zero.
It follows that given any two points $p,q \in M$, the integral of $\alpha$ over a path from $p$ to $q$ is independent of the path. For any points $p$ and $q$, denote this value by $\int_p^q \alpha$. Fix a basepoint $x_0 \in M$ and define $f:M\to \mathbb{R}$ by $f(p):= \int_{x_0}^p \alpha$. It is easy to show that $df = \alpha$. Hence $\omega - c_1 \theta_1 \ldots,c_k \theta_k = \alpha = df$, showing that $\omega = c_1 \theta_1 \ldots + c_k \theta_k + df$, as desired. This completes the proof.
Note that the proof works if $\omega$ is only differentiable, and in general $f$ is only as smooth as $\omega$.
Observation:
The result would follow for $k$-forms on compact manifolds if it were true that "If the integral of a $C^1$ closed $k$-form $\omega$ over every $k$-cycle was zero, then $\omega$ is exact." If $\omega$ was a $C^\infty$ closed form, then this property could be shown using the de Rham theorem. However, I haven't yet figured out from the de Rham theorem proof whether it would work with $C^1$ forms rather than $C^\infty$ forms.
Answer: Yes, this follows, for example, from the fact that we can smooth currents (e.g., differential forms with locally integrable coefficients) and get a chain homotopy formula
$$ST - T = d(AT) + A(dT),$$
where $S$ is the smoothing operator. Among other places, you can find this in deRham's classic or Federer's tome.
Comment: Thank you very much for the answer and the references.


Matplotlib surface plot unintuitive triangulation

Question: I have the following code that produces a surface plot, but it does not do what I would expect.
xx, yy = np.meshgrid(dealer_sums, player_sums)
    def getter(dealer_sum, player_sum):
        state = (dealer_sum, player_sum)
        return self.get_value(state)
    z = np.vectorize(getter)
    zz = z(xx,yy)

    fig = plt.figure()
    ax  = fig.add_subplot(111, projection='3d')
    ax.plot_wireframe(xx,yy, zz)

FYI, the shapes of xx, yy, and zz are all equal and 2D.
From looking at other posts about this (surface plots in matplotlib; Simplest way to plot 3d surface given 3d points) it looks like a common problem is that the x and y coordinates are irregular, but if I have understood correctly, I think mine are already regularised through the call to np.meshgrid?
I have provided a scatter plot below to show what the data looks like without surfaces:

and this is what the call to plot_wireframe looks like:

I have drawn over a few of the lines that I did not expect.  My question is, is it possible to get rid of those lines and create a surface that looks like this?
Thanks for your help.
EDIT: Here is a scatter plot of the XY grid, showing that it is regular:
Answer: Make sure dealer_sums and player_sums are sorted before calling meshgrid,
otherwise, the points connected in the wireframe will also be out of order:
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as axes3d

def z(xx, yy):
    return -xx + (yy-18)**2

dealer_sums = [1, 5, 9]
player_sums = [14, 17, 21, 14]

fig = plt.figure()
ax = fig.add_subplot(1, 2, 1, projection='3d')
ax2 = fig.add_subplot(1, 2, 2, projection='3d')

xx, yy = np.meshgrid(dealer_sums, player_sums)
zz = z(xx, yy)
ax.plot_wireframe(xx, yy, zz)

xx2, yy2 = np.meshgrid(np.unique(dealer_sums), np.unique(player_sums))
zz2 = z(xx2, yy2)

ax2.plot_wireframe(xx2, yy2, zz2)
plt.show()

On the left, the dealer_sums and player_sums were unsorted.
On the right, they were sorted.

np.unique returns the unique values in sorted order. Above, it is really the sorting which is most important, but there is no point in making the grid with duplicate coordinates, so uniqueness is an added benefit.

Note that meshgrid does not necessarily return a regular grid.
If dealer_sums and/or player_sums is irregular, than so will xx and/or yy be.
In [218]: xx, yy = np.meshgrid([0,2,1], [0, .5, 10])

In [219]: xx
Out[219]:
array([[0, 2, 1],
       [0, 2, 1],
       [0, 2, 1]])

In [220]: yy
Out[220]:
array([[  0. ,   0. ,   0. ],
       [  0.5,   0.5,   0.5],
       [ 10. ,  10. ,  10. ]])


Comparing multiple variances across 3 groups

Question: I have monthly data of sales for 3 firms (A, B and C) for 10 years (12*5=60 data points per firm). I want to test if the variance of sales in A is more than the variance in B which is more than the variance in C.
I calculated variances for each year. Thus, I had 10 values of variances for each firm. Then what? I am not comfortable with grouping in a year as it is clearly an arbitrary grouping.
How should I look at this problem? What is the ideal way to test? The average sale for the three firms is different, so, should COV be used instead of variance?
Comment: How come you have 60 data points? Did you mean 120?
Comment: did you look at repeated measures anova?
Answer: One approach would be to fit a regression model that equates the residual variance between the groups (which is the usual regression model assumption) and then compare this to a model that allows the residual variance to be unequal. When comparing these models using a likelihood ratio test, a statistically significant test statistic will indicate that the model with unequal variance is a better fit. This of course will only give you the omnibus test for differences, and not which specific groups differ. To get the pair-wise differences in variance you could take the same approach but constrain two of the three groups to have the same variance.
These types of regression models where heterogenous variance can be modeled are commonly found as options in a glm or mixed model.
Comment: Your approach sounded like a reasonable way of using some kind of weighted least squares until your last comments about a GLM or a mixed model.
Answer: It seems to me like you would like to know whether the variance in the "sales" variable is equal or not between the treatments "firm". There are a number of tests for heterogeneity of variances, the one to chose depends on the distribution of the variable "sales".
For count data, I personally used the Fligner-Killeen test. There are other, which are well described on this page : http://www.sthda.com/english/wiki/compare-multiple-sample-variances-in-r
There is no need to calculate the variance by yourself before using one of these tests.


firebase-core:12.0.1 not found

Question: I have created a firebase project and it says I have to modify the core version to 12 according to the picture

The default code is 9.6.1. So, I changed that number to 12.0.1
compile 'com.google.firebase:firebase-core:12.0.1'

However, the sync failed with the following error
Failed to resolve: com.google.firebase:firebase-core:12.0.1

What should I do?
Answer: Update the gms plugin:
classpath 'com.google.gms:google-services:4.0.0' // google-services plugin

and the firebase lib:
 implementation 'com.google.firebase:firebase-core:16.0.0'

Also add google maven to your build.gradle file:
allprojects {
    // ...
    repositories {
        // ...
        maven {
        url "https://maven.google.com" // Google's Maven repository
       }
        jcenter()
        maven { url "https://jitpack.io" }
    }
}

Comment: Should I also change `firebase-messaging` to 16?
Comment: messaging is in version 17 already, https://firebase.google.com/docs/android/setup
Comment: So, should I change both of them to 17?
Comment: each individual library has its own version, you should use 16 for core and 17 for messaging.
Comment: I get `Failed to resolve: com.google.firebase:firebase-core:16.0.0` and `Failed to resolve: com.google.firebase:firebase-messaging:17.0.0`
Comment: Did you update the gms pluging and used "implementation" instead of "compile"?
Comment: Not very professional. Can you update the answer to show how?
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/171705/discussion-between-levi-albuquerque-and-mahmood).
Comment: @mahmood try my answer it helps you?
Comment: sure, to update the plugin you need to change the classpath you have in your build.gradle file
Comment: in the picture you added, you've used "compile", but that is not in use any longer. You should use "implementation".
Comment: Finally, I've edited the answer to show how you should add the google maven repository to your (project) build.gradle file
Comment: Sorry for the delay. Now I get `Failed to resolve: com.github.ashqal:ChromeLikeSwipeLayout:0.4`. Lets start the chat
Comment: Check out this issue https://github.com/ashqal/ChromeLikeSwipeLayout/issues/11 you need to add the jitpack repository, see my edit
Comment: I am in the chat page. I am getting errors after the edit
Answer: com.google.firebase:firebase-core:12.0.1 is old version already.
You can try version 15.0.0 or as Levi Albuquerque said 16.0.0
However just to remind you that if you implement more than one same kind of library, they should be always in the same version to avoid any syncing error.
Example
implementation 'com.google.firebase:firebase-auth:15.0.0'
implementation 'com.google.firebase:firebase-storage:15.0.0'
implementation 'com.google.firebase:firebase-database:15.0.0'

All are same version 15.0.0
Comment: firebase libs now have independent versions number https://firebase.google.com/docs/android/setup
Answer: You need to add the google() maven inside your allProjects block in your project build.gradle like this:
buildscript {
    repositories {
        jcenter()
        mavenCentral()
    }
    dependencies {
        ...
    }
}

repositories {
    ...
}

// You need to add the google maven in this block.
allprojects {
    repositories {
        jcenter()
        google()
    }
}

Answer: For avoid further errors in grandle beacause of a bug try to use:
classpath 'com.google.gms:google-services:3.2.1'

And for firebase use what you need from below:
    implementation 'com.google.firebase:firebase-core:15.0.2'
    implementation 'com.google.firebase:firebase-ads:15.0.1'
    implementation 'com.google.firebase:firebase-analytics:15.0.2'
    implementation 'com.google.firebase:firebase-appindexing:15.0.1'
    implementation 'com.google.firebase:firebase-auth:15.1.0'
    implementation 'com.google.firebase:firebase-firestore:16.0.0'
    implementation 'com.google.firebase:firebase-functions:15.0.0'
    implementation 'com.google.firebase:firebase-messaging:15.0.2'
    implementation 'com.google.firebase:firebase-storage:15.0.2'
    implementation 'com.google.firebase:firebase-crash:15.0.2'
    implementation 'com.google.firebase:firebase-invites:15.0.1'
    implementation 'com.google.firebase:firebase-perf:15.2.0'
    implementation 'com.google.firebase:firebase-database:15.0.1'
    implementation 'com.google.firebase:firebase-config:15.0.2'

If you using gogle play-services in your grandle set version to 15.0.0 like below example:
implementation 'com.google.android.gms:play-services-location:15.0.0'
implementation 'com.google.android.gms:play-services-maps:15.0.0'
implementation 'com.google.android.gms:play-services-places:15.0.0'
implementation 'com.google.android.gms:play-services-gcm:15.0.0'

I hope this will help you =)
Comment: @mahmood i think this will help you with your problem, you can also use compile 'com.google.firebase:firebase-core:15.0.2' instead of implementation but it will be deprecated in he end of 2018.

firebase-core:12.0.1 not found


A permutation and combination question with too many cases

Question: I know I shouldn't be asking homework questions but I tried.
I am given 15 records (the kind you can play on a gramophone) which have one song on either side of the record (called the A and B sides). I wish to play this song in a loop (i.e. the starting song does not matter). How many different loops can I create if:
Every consecutive song must be from a different record?
There are too many cases to consider when I start picking the fourth song onwards. I can't think of an insertion method or a complement method. Is there an easy method for this?
Comment: It isn't 15! x 2^15. Thats the most common answer my friends gave me.
Comment: So you mean you will play each of the 15 records exactly once?
Comment: @MattiP. probably twice. Each of the 30 song should be played once. (I might be not interpreting correctly)
Comment: you must play 30 songs so technically is playing each record twice , once on each side.
Comment: In that case, one approach is to first put the records in order. There you get $15!$ cases. Then, for each record, you can choose one of two sides. So you get $2^{15}$ after that. For the second time around (the second round, 15 records) you know which side to play because you have already played the other side, but you can still reorder the records. In this case you get additional $15!$ cases. So I would guess the answer is $(15!)^2 \times 2^{15}$.
Comment: @MattiP. You failed to count the case where you play the A song from record 1, then the A song from record 2, then the B song from record 1.
Comment: So there are no restrictions to which song to play, as long as the song has not been played before? In that case, there are 30 songs, so $30!$ ...
Comment: @MattiP. No, the restriction is that the **record** cannot be consequitve. So, you cannot play song A and B from record 1 one after the other.
Comment: @MattiP. This condition is clearly written down by the OP, he said, I quote: "*Every consecutive song must be from a different record*"
Comment: For your first answer of the additional 15!. The problem with that is you aren't considering that it might be 1 A 1B 2A 2B which is included in that answer.
Answer: Update
This is a derangement problem. It is the same as the following: In how many ways can $15$ couples be seated at a round table (no strict $\ldots mfmfmfmf\ldots$ requirement) such that no couple sits next to each other? I'm afraid it has to be solved by setting up an inclusion/exclusion process.
Setting this process up (whereby loops differing only by a rotation are regarded as the same) leads to the formula
$$a(n)=\sum_{k=0}^n(-1)^k\> {n\choose k}2^k (2n-1-k)!\ ,$$
giving  the numbers
$$\bigl(a(n)\bigr)_{n\geq2}=(2, 32, 1488, 112512, 12771840, 2036229120, 434469611520,\ldots)\ .$$
This is sequence A129348 at OEIS. They say there the $a(n)$ count the Hamiltonian cycles of the cocktail party graph. At OEIS one may also find a recursion and asymptotics for the $a(n)$.


How to store and retrieve the data

Question: How to use getters and setters? Semi question: How to create structure to easily retrieve data?
After setting the data in setter I can't retrieve it from the getter.
The structure is as follows:
Interaction - parent class with getters and setters
Dictionary, CategoryInteraction, WordsInteraction - subclasses

Here is my code:
public class Dictionary extends Interaction {

    private String resource = "/home/kjlk/IdeaProjects/Jdf/src/fdf/res";
    private File resourceFile = new File(resource);
    private Scanner scanner;
    private LinkedHashMap<Integer, String> categories;

    public void getCategoriesFromDictionary() {
        Interaction interaction = new Interaction();
        try {
            scanner = new Scanner(resourceFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        categories = new LinkedHashMap<>();
        int categoriesCount = 1;
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            if (line.startsWith("_")) {
                categories.put(categoriesCount, line);
                categoriesCount++;
            }
        }
        scanner.close();
        setCategories(categories);
    }
}

public class Interaction {

    private LinkedHashMap<Integer, String> categories;

    public LinkedHashMap<Integer, String> getCategories() {
        return categories;
    }

    public void setCategories(LinkedHashMap<Integer, String> categories) {
        this.categories = categories;
    }
}

public class CategoryInteraction extends Interaction {

    public void printCategories() {
        LinkedHashMap<Integer, String> categories = getCategories();
        for (Integer key : categories.keySet()) {
            System.out.println(key + ": " + categories.get(key));
        }
        System.out.println();
    }
}

I'm getting NullPointerException for:
LinkedHashMap<Integer, String> categories = getCategories();

Thank you in advance! Please do not refer me to answers for NPE! The idea points to the working structure.
Comment: ...extends Interaction - is not a same object in both classes
Comment: You should create an object to get the values you set
Answer: You need to initialize the categories.
By default it has value null.
That is the reason for your exception.

How to store and retrieve the data


AngularJS: How to validate date in US format?

Question: I have the following form code that allows input of a date using AngularUI (date is required and should match US date format e.g.: MM/DD/YY):
<form name="form" ng-submit="createShipment()">

    <input name="shipmentDate"
          ng-pattern='/^[0,1]?\d{1}\/(([0-2]?\d{1})|([3][0,1]{1}))\/(([1]{1}[9]{1}[9]{1}\d{1})|([2-9]{1}\d{3}))$/'
          ui-date="{ dateFormat: 'mm/dd/y' }" required ng-model="shipment.ShipmentDate" type="text">
    Date Required!
    Incorrect Format, should be MM/DD/YY!

    <input class="btn-primary" ng-hide="!form.$valid" type="submit" value="Create">
</form>

Validation for required field works fine, but date format is not being validated correctly and always shows 'Incorrect Format...' message.
I tried several different Regular Expressions that worked fine elsewhere, but it is still not working. Also I tried AngularUI validation and it doesn't work either. Thanks in advance!
UPDATE:
I figured that validation was conflicting with AngularUI datepicker I used, but datepicker autocorrects date anyway, so if datepicker is not used, than validation works as long as regular expression works, and if datepicker is used, there is not much need for other validation.
Comment: ng-pattern is part of Angular, but not well known.  See http://docs.angularjs.org/cookbook/form for an example.  It is also mentioned on the "input" API pages, e.g., http://docs.angularjs.org/api/ng.directive:input
Comment: ng-pattern? Is this your own implementation? Or from angular-ui?
Answer: Your ng-pattern worked in a fiddle I created, but it allows for some incorrect dates, such as 0/9/1993 and 19/2/1993.
Here's a better pattern: (note, it was updated to match @WillSadler's answer)
^(0?[1-9]|1[012])\/(0?[1-9]|[12][0-9]|3[01])\/((19\d{2})|([2-9]\d{3}))$

Fiddle.
Comment: **Warning: This regex does not allow dates before 1/1/1990.** That might be fine for the OP but not for a general use case. Good answer, I just think the question is misleading.
Comment: I believe the pattern above needs a slight tweek - an additional () around the year part so that it becomes:

/^(0?[1-9]|1[012])\/(0?[1-9]|[12][0-9]|3[01])\/((199\d)|([2-9]\d{3}))$/
Comment: @Rob, the pattern worked (because the alternation at the end doesn't have to be enclosed in parenthesis), but I do see your point, so I made the pattern more consistent -- the alternate year patterns are now enclosed in one set of parenthesis like the the month and day.
Comment: There is form.$invalid, just sayin
Comment: Thanks @Keith, updated to match WillSadler's answer.
Answer: The accepted answer doesn't work for me.  I changed to:
^(0?[1-9]|1[012])\/(0?[1-9]|[12][0-9]|3[01])\/((19\d{2})|([2-9]\d{3}))$

Otherwise only people born after 1990 need apply!
Answer: Check with leap year validate: Date format:dd-mm-yyyy
Regex pattern: ^(0?[1-9]|1\d|2[0-8]|29(?=[-]\d?\d[-](?!1[01345789]00|2[1235679]00)\d\d(?:[02468][048]|[13579][26]))|30(?![-]0?2)|31(?=[-]0?[13578]|[-]1[02]))[-](0?[1-9]|1[0-2])[-]([12]\d{3})$
Demo
another demo
Comment: CAREFULL ! This pattern does not work. No dates after the 28th are accepted. Try for instance the 29/03/1963. https://regex101.com/r/bO6rY5/1


Como subir e configurar um projeto com Laravel no servidor

Question: Estou iniciando com Laravel 5.3 e aprendendo a explorar todos os seus recursos. Mas estou com uma dúvida. Como ficaria esse meu projeto no servidor (em produção). Hoje meus projetos estão dentro de uma pasta com o arquivo index.php na raiz. O que mudaria em um projeto utilizando Laravel?
Comment: Servidor dedicado ou compartilhado?
Answer: Quando você sobe um projeto Laravel para o servidor, você deve configurar o Virtual Host  para apontar para a pasta public do seu projeto, pois como o nome da pasta diz, essa é a pasta que deverá ser pública.
Pensando no caso do Apache2 , você poderia configurá-lo da seguinte forma:
<VirtualHost *:80>
    DocumentRoot /var/www/nome-do-projeto/public
    ServerName www.nome-do-projeto.com.br
    ErrorLog /tmp/nome-do-projeto_apache.log
</VirtualHost>

Também é necessário remover o arquivo .env, uma vez que o mesmo só deve ser usado em ambiente de desenvolvimento.
O arquivo .env afeta diretamente as configurações dos arquivos na pasta config. Por exemplo, o arquivo config/database.php deverá conter no segundo parâmetro da função env o valor referente às conexões em produção, pois o primeiro parâmetro tratar-se-á dos parâmetros definidos no arquivo .env. Na falta deste arquivo, o segundo parâmetro da função env será considerada para sua configuração.
Exemplo:
'host' => env('DB_HOST', 'url-do-banco-em-producao.com')

No arquivo .env
DB_HOST=localhost

Ou seja, você precisa apenas enviar os arquivos da sua aplicação para  a pasta específica no servidor, com exceção do arquivo .env.
Answer: Além do cuidado com o arquivo .env, conforme já respondido acima, caso vc não tenha acesso/controle para configurar um virtualhost, vc pode fazer o seguinte:
Supondo que seu document-root seja a pasta 'www' ou 'public_html':

Copiar apenas o conteúdo da pasta 'public' do seu projeto para o
document-root;
Editar o arquivo 'index.php' para referenciar os
diretórios existentes no arquivo corretamente;
Editar o arquivo 'server.php' que fica na raiz do seu projeto para apontar para o 'index.php' do document-root.


Conditional distribution of $(X_i)_i$ given $\sum\limits_i X_i$ when $(X_i)_i$ is i.i.d.

Question:
Suppose $X_1,X_2,\ldots, X_n$ are i.i.d. random variables. Is there some way to determine the distribution of $(X_1,\ldots,X_n)$ given $S_n := X_1+\ldots+X_n$?

In the discrete case it is easy just using the definition of conditional expected value, but what about in the continuous case?
Comment: When every $X_i$ has PDF $f$, their sum $$S=\sum_i X_i$$ has PDF $g=f^{\ast n}$ the convolution of $f$ with itself $n$ times, and the distribution of $X=(X_i)_i$ conditional on $S$ has conditional PDF $$f_{X\mid S}(x\mid s)=g(s)^{-1}\prod_i f(x_i)$$ with the notation $x=(x_i)_i$, on the set $$s=\sum_i x_i$$ Since your post also mentions "conditional expected value(s)", let me add that these are much simpler, since, for every $i$, $$E(X_i\mid S)=\frac1nS$$
Comment: @Did the part that is tripping me up is that the set $s=\sum_i x_i$ has Lebesgue measure zero. Presumably I should be able to calculate $P(X\in A|S=s) = \int_A f_{X|S}(x|s)\,dx$, but this just gives $0$ since the support of $f_{X|S}$ has measure zero. Should I be integrating with respect to a different measure? Also if you know of a reference that handles these subtleties carefully I would appreciate it.
Comment: @LordSharktheUnknown I don't think that helps. Although the $X_i$ will be identically distributed given $S_n$, they will not be independent.
Comment: You could take the $n$-th root of the characteristic function of $S_n$.
Comment: You could define $X=(X_1, ..., X_n)$, $x=(x_1, ..., x_n)$, define the event $A_x = \{X \leq x\}$, and then  $$ P[X \leq (x_1, ..., x_n)| Y=y] = \frac{f_{Y|A_x}(y|A_x)P[X_1\leq x_1]...P[X_n\leq x_n]}{f_Y(y)}$$ Then you can take partial derivatives with respect to $x_i$ if you like.  I think your $S_n$ morphed into my $Y$, although you could use the above in more general situations when $Y$ is not necessarily the sum.
Comment: @Did : You may want to qualify/modify your above comment since, as nulluser notes, in this situation that density would integrate to 0 (though it may work with some "impulse-like" integration).
Comment: @Michael No need to. The function $f_{X\mid S}(\ \mid s)$ in my comment is the density of the conditional distribution of $X$ conditionally on $S=s$ with respect to the ($(n-1)$-dimensional) Lebesgue measure on the hyperplane of equation $x_1+\cdots+x_n=s$. Of course, the integral of any function whose support is a hyperplane, with respect to the ambient ($n$-dimensional) Lebesgue measure, is zero, but this (true) fact is rather unrelated to what I wrote.
Comment: @Did : Your qualification about using a different measure is the kind of thing I had in mind, it seemed an important thing to state.
Comment: @Did, in this case the $(n-1)$-dimensional Lebesgue measure seems to be the obvious choice of what to integrate with respect to, but how do we know? If instead of $S$ being the sum, for instance, if $S$ were the product of the $X_i$ or some other function, and the surface $\prod x_i = s$ is not just a plane, then how would I determine what measure to integrate with respect to? I'de be interested to have a reference that treats these more general conditional situations carefully if you could recommend one.
Answer: Expanding on my first comment...
General formula
Let $S$ be a random variable with PDF $f_S(s)$ for $s \in \mathbb{R}$. Let $A$ be an event with $P[A>0]$. Then:
$$ P[A|S=s] = \frac{f_{S|A}(s|A)P[A]}{f_S(s)} $$
For intuition about this formula, it is easy to verify that for any interval $[a,b]$:
\begin{align}
\int_{s=-\infty}^{\infty} P[A|S=s]f_S(s)ds &= P[A] \\
\int_{s \in [a,b]} P[A|S=s] f_S(s) &= P[A \cap \{ S \in [a,b]\}]
\end{align}
Application to your problem
Let $\{X_i\}_{i=1}^n$ be i.i.d., let $S=\sum_{i=1}^n X_i$.  We want to find $P[(X_1, \ldots, X_n) \leq (x_1, ..., x_n) | S=s]$ for all relevant values of $s \in \mathbb{R}$.  For notational simplicity define $X=(X_1, ..., X_n)$, $x=(x_1, ..., x_n)$, $A_x = \{X\leq x\}$.  Note that:
$$P[A_x] = P[X\leq x] = P[X_1\leq x_1]\cdots P[X_n\leq x_n] $$
 Assume $S$ has PDF $f_S(s)$. We want to compute $P[A_x|S=s]$.  Applying the above formula gives:
\begin{align*}
P[A_x | S=s] &= \frac{f_{S|A_x}(s|A_x)P[A_x]}{f_S(s)} \\
&= \frac{f_{S|A_x}(s|A_x)P[X_1\leq x_1]\cdots P[X_n\leq x_n]}{f_S(s)}
\end{align*}
You can find $f_S(s)$ by $n$-fold convolution of the PDFs of $f_X(s)$ (assuming such exist).  You can find $f_{S|A_x}(s|A_x)$ by:
\begin{align}
f_{S|A_x}(s|A_x) &= \frac{d}{ds} P[S \leq s| A_x] \\
&=  \frac{1}{P[A_x]}\frac{d}{ds}P[\{S\leq s \} \cap A_x]\\
&= \frac{\frac{d}{ds} P[X_1\leq x_1, ..., X_n \leq x_n, X_1+...+X_n\leq s]}{P[X_1\leq x_1]\cdots P[X_n\leq x_n]}
\end{align}
Computing probabilities with the conditional CDF
Notice that the above gives the conditional cumulative distribution function  (CDF) rather than the conditional PDF.  Conditional PDFs given  $X_1 + ... +X_n=s$ are hard to define since, as you note, this restricts $(X_1, ..., X_n)$ to a multidimensional set of measure zero in $\mathbb{R}^n$.  So real-valued functions defined over that measure-zero set would integrate to 0, not to 1. One would need to use PDFs with multidimensional impulses, which are tricky.  However, there is no need to use impulses:  Working with the conditional CDF gives all you need.
For example, suppose $n=2$ and let $B$ be the line segment in $\mathbb{R}^2$ between the points $(0,1)$ and $(1,0)$.  How do we compute $P[(X_1, X_2) \in B | S=1]$?  We just observe:
$$P[(X_1, X_2) \in B | S=1] = P[\underbrace{X_1 \leq 1, X_2 \leq 1}_{A_{(1,1)}} | S=1] $$
A 2-d picture to illustrate the above equation would be great, but I do not know how to post a picture on stackexchange.


UIPickerView does not always show values in 3g

Question: I have a really strange error, the application in this application uses the pattern-view-controller, in the view I use a UIPickerView to display names. Values should be shown in RisorseUmaneUIPicker! The strange thing is that everything works while when you text the application on mobile devices in 3g sometimes, the UIPickerView remains empty. How can I solve this?
I checked the json request with postman and it is always correct
View:
class RisorseUmaneViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITableViewDelegate, UITableViewDataSource {

    //Dichiarazione Oggetti
    //L'array User contiene le informazione su tutti gli utenti presenti nel database
    private var UserLoad: [UserStruct] = []
    private var RisorseUmaneUIPicker: UIPickerView = UIPickerView()
    private let datePicker: UIDatePicker = UIDatePicker()
    private let StartPicker: UIDatePicker = UIDatePicker()
    private let EndPicker: UIDatePicker = UIDatePicker()
    private let PausaPicker: UIDatePicker = UIDatePicker()
    private var textView: UITextView = UITextView()
    private var RisoseUmaneTableView: UITableView!
    private var RisorseUmaneLoad: [RisorsaUmanaStruct] = []
    private var SwitchRapportino: UISwitch = UISwitch()
    //L'oggetto RisorsaUmana Rappresenta la risorsa che verrà inserita
    public var Cantiere: Cantiere
    private var RisorsaSelezionata: RisorsaUmana?
    private var Extensioni: Extend = Extend()
    public var Stato: String = "Inserimento"
    private var RisorsaRapportino: Bool = false;

    init(CantiereInterno: Cantiere) {
        self.Cantiere = CantiereInterno
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        hideKeyboardWhenTappedAround()
        self.view.backgroundColor = UIColor.white
        self.navigationController?.setNavigationBarHidden(false, animated: true)
        self.navigationItem.title = "Risorse Umane"
        InitRisorseUmaneViewController();
        //Modifica UiPickerView delle Risorse con l'utente che ha effettuato il login
        print("Login di : \(UserLoginDefault.Username)")
        selectPicker(withText: UserLoginDefault.Username)

    }

    //Funzione di Configurazione Iniziale della View
    private func InitRisorseUmaneViewController() {

        //inizializzo il Cantiere
        let displayWidth: CGFloat = self.view.frame.width
        //Carico le Risorse
        CaricaRisorse()
        //Configurazione Label Risorsa
        let label = UILabel(frame: CGRect(x: (self.view.frame.width / 2) - 150, y: 65, width: 90, height: 24))
        label.font = UIFont(name: "HelveticaNeue-Bold", size: 16.0)
        label.textAlignment = .center
        label.text = "Risorsa: "
        self.view.addSubview(label)
        //Configurazione :impostazioni picker view
        self.RisorseUmaneUIPicker = UIPickerView(frame: CGRect(x: (self.view.frame.width / 2) - 70, y: 50, width: 200, height: 50))
        self.RisorseUmaneUIPicker.delegate = self
        self.RisorseUmaneUIPicker.dataSource = self
        self.RisorseUmaneUIPicker.backgroundColor = UIColor.white
        self.view.addSubview(RisorseUmaneUIPicker)
        //Configuro il DataTime Picker per la data
        self.datePicker.frame = CGRect(x: 10, y: 100, width: self.view.frame.width, height: 80)
        self.datePicker.timeZone = NSTimeZone.local
        self.datePicker.backgroundColor = UIColor.white
        self.datePicker.datePickerMode = UIDatePickerMode.date;
        //Aggiunto un evento quando viene modificato il valore del datePicker
        self.datePicker.addTarget(self, action: #selector(RisorseUmaneViewController.datePickerValueChanged(_:)), for: .valueChanged)
        self.view.addSubview(datePicker)
        //Congiurazione Ore di Inizio e Fine
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "HH:mm"
        let dateStart = dateFormatter.date(from: "08:00")
        let dateEnd = dateFormatter.date(from: "17:30")
        let datePausa = dateFormatter.date(from: "01:30")
        //Configuro il DataPicker di Start
        self.StartPicker.frame = CGRect(x: (self.view.frame.width / 2) - 90, y: 190, width: 100, height: 40)
        self.StartPicker.timeZone = NSTimeZone.local
        self.StartPicker.backgroundColor = UIColor.white
        self.StartPicker.datePickerMode = UIDatePickerMode.time
        self.StartPicker.date = dateStart!
        self.StartPicker.addTarget(self, action: #selector(RisorseUmaneViewController.SetDataInizio(sender:)), for: .valueChanged)
        self.StartPicker.minuteInterval = 30
        self.view.addSubview(StartPicker)
        //Configuro il DataPicker di End
        self.EndPicker.frame = CGRect(x: (self.view.frame.width / 2) + 60, y: 190, width: 100, height: 40)
        self.EndPicker.timeZone = NSTimeZone.local
        self.EndPicker.backgroundColor = UIColor.white
        self.EndPicker.datePickerMode = UIDatePickerMode.time
        self.EndPicker.date = dateEnd!
        self.EndPicker.addTarget(self, action: #selector(RisorseUmaneViewController.SetDataFine(sender:)), for: .valueChanged)
        self.EndPicker.minuteInterval = 30
        self.view.addSubview(EndPicker)
        //Configuro il DataPicker di Pausa
        self.PausaPicker.frame = CGRect(x: (self.view.frame.width / 2) - 30, y: 250, width: 100, height: 40)
        self.PausaPicker.timeZone = NSTimeZone.local
        self.PausaPicker.backgroundColor = UIColor.white
        self.PausaPicker.datePickerMode = UIDatePickerMode.time
        self.PausaPicker.date = datePausa!
        self.PausaPicker.addTarget(self, action: #selector(RisorseUmaneViewController.SetPausa(sender:)), for: .valueChanged)
        self.PausaPicker.minuteInterval = 30
        self.view.addSubview(PausaPicker)
        //Configurazione Testo TextView
        self.textView = UITextView(frame: CGRect(x: 0, y: 300, width: displayWidth, height: 85))
        self.automaticallyAdjustsScrollViewInsets = false
        textView.font = UIFont(name: "HelveticaNeue-Bold", size: 18.0)
        textView.textAlignment = NSTextAlignment.justified
        textView.textColor = UIColor.blue
        textView.backgroundColor = UIColor.lightGray
        self.view.addSubview(textView)
        //Bottone per inserimento:
        let ImageInserisci = UIImage(named: "inserisci.png") as UIImage?
        let ButtonInserisciRisorsaUmana = UIButton()
        ButtonInserisciRisorsaUmana.frame = CGRect(x: (self.view.frame.width / 2) - 180, y: 395, width: 80, height: 80)
        ButtonInserisciRisorsaUmana.setImage(ImageInserisci, for: .normal)
        ButtonInserisciRisorsaUmana.setTitleColor(UIColor.black, for: .normal)
        ButtonInserisciRisorsaUmana.set(image: ImageInserisci, attributedTitle: NSAttributedString(string: "Inserisci"), at: UIButton.Position(rawValue: 1)!, width: 30, state: UIControlState.normal)
        ButtonInserisciRisorsaUmana.addTarget(self, action: #selector(InserisciRisorsaButtonAction), for: .touchUpInside)
        self.view.addSubview(ButtonInserisciRisorsaUmana)
        //Bottone per tornare a schermata principale
        let ImageReturn = UIImage(named: "return.png") as UIImage?
        let buttonReturn = UIButton()
        buttonReturn.frame = CGRect(x: (self.view.frame.width / 2) - 30, y: 395, width: 80, height: 80)
        buttonReturn.backgroundColor = UIColor.white
        buttonReturn.setImage(ImageReturn, for: .normal)
        buttonReturn.setTitle("Go Home", for: .normal)
        buttonReturn.addTarget(self, action: #selector(Return), for: .touchUpInside)
        self.view.addSubview(buttonReturn)
        //Configuro lo UISwitch per l'inserimento delle risorse nel cantiere
        let labelRapportino = UILabel(frame: CGRect(x: (self.view.frame.width / 2) + 80, y: 395, width: 130, height: 21))
        labelRapportino.text = "Rapportino?"
        labelRapportino.font = UIFont(name: "HelveticaNeue-Bold", size: 16.0)
        self.view.addSubview(labelRapportino)
        SwitchRapportino = UISwitch(frame: CGRect(x: (self.view.frame.width / 2) + 100, y: 430, width: 0, height: 0))
        SwitchRapportino.setOn(false, animated: true)
        SwitchRapportino.addTarget(self, action: #selector(RisorseUmaneViewController.switchValueDidChange(sender:)), for: .valueChanged)
        self.view.addSubview(SwitchRapportino)

        //Stato Inserimento: l'utente sta inserendo delle risorse dentro una cantier
        if(Stato == "Inserimento") {
            RisorsaSelezionata = RisorsaUmana(CantiereInterno: Cantiere)
            //Configurazione table view
            RisoseUmaneTableView = UITableView(frame: CGRect(x: 0, y: 500, width: displayWidth, height: self.view.frame.height - 500))
            RisoseUmaneTableView.register(CustomTableViewCellArticolo.self, forCellReuseIdentifier: "MyCell")
            RisoseUmaneTableView.dataSource = self
            RisoseUmaneTableView.delegate = self
            RisoseUmaneTableView.tableFooterView = UIView()
            RisoseUmaneTableView.rowHeight = 60
            RisoseUmaneTableView.layer.borderWidth = 2.0
            self.view.addSubview(RisoseUmaneTableView)
            //Carica Le risorse Umane e chiamo i Metodi di configurazione
            CaricaRisorseCantiere()
        }
        SetPausa(sender: PausaPicker)
        SetDataInizio(sender: StartPicker)
        SetDataFine(sender: EndPicker)
        datePickerValueChanged(datePicker)
        SwitchRapportino.isHidden = false
        labelRapportino.isHidden = false
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    func selectPicker(withText text: String) {
        print("Testo: \(text)")
        if let index = self.UserLoad.index(where: { $0.Username == text }) {
            print("Indice di riga: \(index)")
            RisorseUmaneUIPicker.selectRow(index, inComponent: 0, animated: true)
            self.RisorseUmaneUIPicker.reloadAllComponents()
        }
        else {
            print("text not found")
        }
    }

    //Funzione per il caricamento delle risorse Umane
    func CaricaRisorse() {
        DispatchQueue.global(qos: .userInteractive).async {
            let rtemp = User()
            rtemp.CaricaUtenti(completion: { result in
                self.UserLoad = result
                self.RisorseUmaneUIPicker.reloadAllComponents()
            });
        }
    }

    @objc func SetPausa(sender: UIDatePicker) {
        RisorsaSelezionata?.SetOrePausa(Pausa: Extensioni.CastFromDateToString_SqlServer_Pausa(mydate: PausaPicker.date))
    }

    @objc func SetDataFine(sender: UIDatePicker) {
        RisorsaSelezionata?.SetOreFine(OreFine: Extensioni.CastFromDateToString_SqlServer_DateTime(mydate: EndPicker.date))
    }

    @objc func SetDataInizio(sender: UIDatePicker) {
        RisorsaSelezionata?.SetOreInizio(OreInizio: Extensioni.CastFromDateToString_SqlServer_DateTime(mydate: StartPicker.date))
    }

    @objc func InserisciRisorsaButtonAction(sender: UIButton!) {
        print("\n Id Risorsa: \(String(describing: RisorsaSelezionata?.GetIdUtente()))")
        if(textView.text.isEmpty || RisorsaSelezionata?.GetIdUtente() == 0) {
            let alertController = UIAlertController(title: title, message: "Attenzione non hai compilato tutti i campi", preferredStyle: .alert)
            let OKAction = UIAlertAction(title: "OK", style: .default, handler: nil)
            alertController.addAction(OKAction)
            self.present(alertController, animated: true, completion: nil)
        }
        else {
            RisorsaSelezionata?.SetDescrizione(Descrizione: textView.text)
                RisorsaSelezionata?.SetRisorsaRapporto(RisorsaRapportino: RisorsaRapportino)
            if(Stato == "Inserimento") {
                RisorsaSelezionata?.InserisciRisorsa(completion: { result in

                if(result == true) {
                    self.CaricaRisorseCantiere()
                }
                else {
                    let alertController = UIAlertController(title: "Errore", message: "Non sono riuscito ad inserire la risorsa!", preferredStyle: .alert)
                    let OKAction = UIAlertAction(title: "OK", style: .default, handler: nil)
                    alertController.addAction(OKAction)
                    self.present(alertController, animated: true, completion: nil)
                }
            })
        }
    }

}

    @objc func Return(sender: UIButton!) {
        //self.performSegueToReturnBack()
        let CantiereSelezionato = GestioneCantieriViewController(CantiereSet: self.Cantiere)
        self.present(CantiereSelezionato, animated: true, completion: nil)
    }

    //Metodo delegato che ritorna il numero di righe
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return UserLoad.count
    }

    // Metodo delegato che ritorna il valore mostrato nella riga
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        RisorsaSelezionata?.SetIdUtente(IdUtente: UserLoad[row].IdUtente)
        return UserLoad[row].Username
    }

    // Metodo Delato Chiamao quando viene selezionata unarigha
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        print("\n UserLoad[row].IdUtente \(UserLoad[row].IdUtente!)")
        RisorsaSelezionata?.SetIdUtente(IdUtente: UserLoad[row].IdUtente!)
        print("\n ID Risorsa \(String(describing: RisorsaSelezionata?.GetIdUtente()))")
    }

    //Number of Columns into UIPickerView
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    //this func get select Date from UIDatePicker
    @objc func datePickerValueChanged(_ sender: UIDatePicker) {
        RisorsaSelezionata?.SetData(Data: Extensioni.CastFromDateToString_SqlServer_DateTime(mydate: sender.date))
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return RisorseUmaneLoad.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        RisoseUmaneTableView.beginUpdates()
        let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath) as! CustomTableViewCellArticolo
        cell.layer.cornerRadius = 10
        cell.layer.borderWidth = 1.0
        cell.layer.borderColor = UIColor.gray.cgColor
        cell.layer.masksToBounds = true
        cell.labCodArt.text = RisorseUmaneLoad[indexPath.row].Risorsa
        cell.labDescrizione.text = RisorseUmaneLoad[indexPath.row].Descrizione
        cell.labPrezzo.text = ""
        RisoseUmaneTableView.endUpdates()
        return cell
    }

    func CaricaRisorseCantiere() {
        if(Stato == "Inserimento") {
            let rtemp = RisorsaUmana(CantiereInterno: Cantiere)
            rtemp.CaricaRisorseUmaneCantiere(completion: { result in

            self.RisorseUmaneLoad.removeAll()
            self.RisorseUmaneLoad = result
            DispatchQueue.main.async {
                self.RisoseUmaneTableView.reloadData()
            }
        });
    }
}
......

Controller:
func CaricaUtenti(completion: @escaping ([UserStruct]) -> Void) {
    DispatchQueue.global(qos: .userInteractive).async {
        let rtemp = UserModel()
        rtemp.CaricaRisorse(completion: { result in
            completion(result)
        })
    }
}

Model:
func CaricaRisorse(completion: @escaping ([UserStruct]) -> ()) {
    DispatchQueue.global(qos: .userInteractive).async {
        let jsonrequest = JSON()
        let jsonarray: [String: Any] = ["Default": "0"]
        jsonrequest.GetArray(Tipo: "User", Router: "/RisorseUmane/CaricaRisorse", ValueArray: jsonarray, completion: { result in
            completion(result as! [UserStruct])
        })
    }
}

func GetArray(Tipo: String, Router: String, ValueArray: [String: Any], completion: @escaping (_ ret: Codable) -> ()) {
    let semaphore = DispatchSemaphore(value: 1)
    semaphore.wait()
    let db = Database()
    let json: [String: Any] = ValueArray
    let jsonData = try? JSONSerialization.data(withJSONObject: json)
    var request = URLRequest(url: URL(string: db.GetServerURL() + Router)!)
    request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
    request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept")
    request.httpMethod = "POST"
    request.httpBody = jsonData
    URLSession.shared.dataTask(with: request) { (data, response, error) in
        if error != nil {
            print(error!.localizedDescription)
        }
    guard let data = data else { return }
    do {
        if(Tipo == "User") {
            let value = try JSONDecoder().decode([UserStruct].self, from: data)
            completion(value)
        }
    } catch let error {
         print("Error JSON: ", error)
     }
    }.resume()
    semaphore.signal()
}

Answer: You can install "Network Link Conditioner" from Xcode menu: Open Developers Tools > More Developers Tools. This tool allows you to test under different network conditions.
Handler passed to URLSesssion.dataTask should probably pass information about success or failure back to caller. It now simply returns if there has been an error if data is nil. Consider adding extra value besides data to handler. For example, _ success: Bool could be passed false in case of error if data is missing.
... completion: @escaping (_ success: Bool, _ ret: Codable) -> ()


Receiving an error when uninstall

Question: I am getting a WSOD after attempting to uninstall the Drupal Commerce module on Drupal 8.1.1 Has anyone seen this error before, and possibly point me a direction? Lost trying to fix this.

Drupal\Component\Plugin\Exception\PluginNotFoundException: The "commerce_product" entity type does not exist. in Drupal\Core\Entity\EntityTypeManager->getDefinition() (line 125 of core/lib/Drupal/Core/Entity/EntityTypeManager.php).
Comment: Did you remove the module directory before running the uninstall command?
Answer: Commerce for Drupal 8 must be considered unusable at this stage and very unstable as it is still in alpha version.
No stable version has been released yet, therefore it is advised not to try to build anything yet with it, and installation shall be considered for development purpose only.

Receiving an error when uninstall


If $a,b,c$ are positive, then $(a+b+c)(1/a+1/b+1/c)\ge 9$

Question: The question asks to prove that if  "$x_1,x_2,x_3$ are positive numbers show that:
$$(x_1+x_2+x_3) \left(\frac{1}{x_1}+\frac{1}{x_2}+\frac{1}{x_3} \right)\ge 9$$
I've tried to use the fact that the arithmetic mean is greater than the harmonic mean since it looks like it's kind of in that form but it doesn't seem to work. I tried expanding it too and simplifying a little to get:
$$ x_1^2(x_2+x_3)+x_2^2(x_1+x_3)+x_3^2(x_1+x_2)\ge 6 x_1x_2x_3$$
but I can't seem to see anyway to further get it into a form that easily proves the required inequality. Any hints as to a way to do this?
Comment: Direct by Cauchy Schwarz...
Comment: Use AM-GM, AM-HM or tchebychef's inequality
Comment: It is actually the AM-HM part of AM-GM-HM, and as a part of RMS-AM-GM-HM...
Comment: @Macavity how might you do it?
Answer: The Arithmetic-harmonic mean inequality is actually the usual way of doing this.
We have $ \frac{x_1+\cdots+x_n}{n}\geq \frac{n}{\frac{1}{x_1}+\cdots+\frac{1}{x_n}} $ in general. Write it out for $n=3$, and stare at it for a bit - it's a very simple manipulation.
Comment: I see what I've done now, I for some reason thought that the harmonic mean was $\frac{1}{n}\sum \frac{1}{x_i}$ and not the reciprocal. It's completely obvious and ridiculously easy now when its't the right way round! Thanks
Comment: @Jay I thought maybe you'd done that!
Comment: @Jay if the answer was helpful, accepting it is a useful way of marking that for others viewing the topic
Comment: yeah, I'm trying too but it isn't letting me until there's been a certain amount of time, I don't remember there being a minimum time before you could accept an answer to a question but I suppose it makes some sense.
Comment: It does make sense, no worries.
Answer: Let $u=\langle\sqrt{a},\sqrt{b},\sqrt{c}\rangle$ and $v=\langle\frac{1}{\sqrt{a}},\frac{1}{\sqrt{b}},\frac{1}{\sqrt{c}}\rangle$.
By the Cauchy-Schwarz inequality,
$(u\cdot v)^2\le|u|^2|v|^2$ so $\displaystyle9\le(a+b+c)\left(\frac{1}{a}+\frac{1}{b}+\frac{1}{c}\right)$.
Answer: You use the Cauchy inequality, $x+y+z\ge 3\sqrt[3]{xyz}$ for all $x,y,z\ge 0$, to prove the statement.
Solve: We have
$$a+b+c\ge 3\sqrt[3]{abc},$$
$$\frac{1}{a}+\frac{1}{b}+\frac{1}{c}\ge 3\sqrt[3]{{\frac{1}{a}.\frac{1}{b}.\frac{1}{c}}} = \frac{3}{{\sqrt[3]{{abc}}}}.$$
So, we have
$$\left( {a + b + c} \right)\left( {\frac{1}{a} + \frac{1}{b} + \frac{1}{c}} \right) \geqslant 3\sqrt[3]{{abc}}.\frac{3}{{\sqrt[3]{{abc}}}} = 9.$$
The inequality is proved.
Comment: actually isn't that the AM-GM inequality again? Isn't [this](http://en.wikipedia.org/wiki/Cauchy–Schwarz_inequality) the Cauchy Inequality. Even so it's still a nice way to do it.
Comment: I was just thinking how to use the Cauchy inequality to do this. Thanks!
Answer: As $x\to 1/x$ is convex on $(0,\infty)$:
$$
1/\left[
\frac 13 \left(
x+y+z\right)\right]
\le
\frac 13 \left(
1/x+1/y+1/z\right)
\\
1\le
\frac 13 \left(
1/x+1/y+1/z\right)\frac 13 \left(
x+y+z\right)
\\
9\le
\left(
1/x+1/y+1/z\right)\left(
x+y+z\right)
$$


Why replace() is not working for '$' symbol?

Question: I want to replace all the '$' in a string, I am using simple replace() function. It is working for other substring but not for '$' symbol. Any reason why?

var mystring = "this,is,a,test"
console.log(mystring.replace(/,/g , ":"));

var mystring2 = "this$is$a$test"
console.log(mystring2.replace(/$/g , ":"));
Comment: Please comment if you down vote the question.
Answer: $ has special meaning in a regular expression, it matches the end of the string. You need to escape it to use it literally.

var mystring = "this,is,a,test"
console.log(mystring.replace(/,/g , ":"));

var mystring2 = "this$is$a$test"
console.log(mystring2.replace(/\$/g , ":"));

You should read an regular expression tutorial, like the one at regular-expressions.info
Answer: Because $ is a special identifier in regular expressions and should be escaped
var mystring2 = "this$is$a$test"
console.log(mystring2.replace(/\$/g , ":"));


Detecting increases in twitter list activity

Question: I'm trying to find more information on how to measure and detect increases in activity in twitter list activity. I have access to all the tweets produced by a list of users. The idea is to try to predict or detect when there is some breaking news that everyone is talking about.
A sensible thing is to plot number of tweets over time, and proportion of active users in a list (if 10 out of 30 users in a list tweet, proportion of active users = 0.33)
The problem with this is that it is difficult to spot spikes in activity due to daily rhythm - people tend to sleep, and only tweet during the day... who knew?
A quick and dirty example: (Cycle plot?)
http://savedbythegoog.appspot.com/?id=6708dc9a2c90f9f937755542900a1b1957f20f3a
Looking at a month of data is slightly better - but not really informative:
http://savedbythegoog.appspot.com/?id=014b2246ba3d762b5201f0048812cd0675d5721a
Those peaks could be annotated with the top hashtags to give some meaning to them.
That's what I got so far.
Are there any specific things i could read up on to get a better measure or make things more interpretable? Any other approaches or ideas more than welcome!
Answer: I would try modeling the "expected" behavior (like time-of-day fluctuations) with some model such as regression or exponential smoothing. Then, since you are interested in detection, I'd monitor the forecast errors using a statistical control chart. The control chart is based on putting threshold(s) on the forecast error, such that an extreme forecast will trigger an alert.


Como extrair o texto entre parênteses com regex em php

Question: Tenho o texto:
As expressões regulares (muitas vezes abreviado para "regex") são uma linguagem declarativa utilizada para correspondência.
Como faço para pegar o conteúdo incluído entre os parênteses?
Tentei:
$texto = "As expressões regulares (muitas vezes abreviado para "regex") são uma linguagem declarativa utilizada para correspondência." ;
preg_match("/\(*\)/", $texto, $testando);
var_dump($testando) ;

A saída é:
array (size=1)
   0 => string ')' (length=1)

Answer: Faltou especificar qual caracter quer casa na sua regex, no caso o ponto .. Ou seja vai pegar um parentese seguido de qualquer coisa .* seguido de um fechamento de parentese.
$texto = "As expressões regulares (muitas vezes abreviado para 'regex') são uma linguagem declarativa utilizada para correspondência." ;
preg_match("/\(.*\)/", $texto, $testando);
var_dump($testando) ;

Ou para pegar o contúdo dentro dos dois parênteses, use a função preg_match_all(), mude a regex para combinar letras e números (\w), caracteres como espaço, tab e outros (\s) e aspa simples (')
$texto = "As expressões regulares (muitas vezes abreviado para 'regex') são uma linguagem (declarativa utilizada) para correspondência";
preg_match_all("#\([\w\s']+\)#i", $texto, $testando);
var_dump($testando) ;

Comment: No caso em: $texto = "As expressões regulares (muitas vezes abreviado para 'regex') são uma linguagem (declarativa utilizada) para correspondência." Conseguiria trazer os 2 trechos entre parênteses separadamente?
Comment: @Taisbevalle, obrigado!
Funcionou direitinho.
A resposta agora foi **(muitas vezes abreviado para 'regex')**
Comment: Resta resolver o problema citado pelo @GivanildoR.deOliveira. Quando há duas sequências "654321(GGG) blá (HSH)123456"  o retorno é "(GGG) BLÁ (HSH)" enquanto o desejável seria "(GGG)" e "(HSH)"
Comment: @GivanildoR.deOliveira editei a resposta.
Comment: Fantástico @rray.


AWS IoT core pubsub.py example how to save messages to a variable

Question: I am very new to python as well as to AWS IoT. I am using a raspberry pi zero in conjunction to publish and receive messages from my AWS IoT topic. I can send messages just fine and I can also receive messages and now I'm trying to figure out a way to save these messages as a string. Specifically, I am trying to save the color I send from the topic.
print(color)
Expected output: blue
The function I am working with is the "on_message_received" function in the pubsub.py file found here: https://github.com/aws/aws-iot-device-sdk-python-v2/blob/main/samples/pubsub.py
# Callback when the subscribed topic receives a message
def on_message_received(topic, payload, dup, qos, retain, **kwargs):
print("Received message from topic '{}': {}".format(topic, payload))
global received_count
received_count += 1
if received_count == cmdUtils.get_command("count"):
    received_all_event.set()

I changed it to save the message I am receiving to the variable "color".
# Callback when the subscribed topic receives a message
def on_message_received(topic, payload, dup, qos, retain, **kwargs):
print("Received message from topic '{}': {}".format(topic, payload))
global received_count
received_count += 1
if received_count == cmdUtils.get_command("count"):
    received_all_event.set()
color = json.loads(payload.decode())['message']
print(color)

This is the format of the message I am sending from the topic
{
  "message": "blue"
}

This allows me to save the received message to color and just prints blue
However, I also get this error message TypeError: string indices must be integers
And I know this is because there is supposed to be an integer in the brackets instead of the word 'message'
but when I place either a 0 or a 1 the output, I get is either: A or 1
I also tried changing the function and just having color = json.loads(payload)
But when I do this the output is {'message': 'blue'}
Is there a way to still get the output of print(color) as blue without getting the error message: TypeError: string indices must be integers?
Answer: I figured out a way to fix my problem.
# Callback when the subscribed topic receives a message
def on_message_received(topic, payload, dup, qos, retain, **kwargs):
global received_count
print("Received message from topic '{}': {}".format(topic, payload))
if topic.endswith('/pi'):
    rawData = (payload.decode())
    data = json.loads(rawData)
    Validate = rawData.split()
    check1 = (Validate[1])
    if check1 == check1:
        print(rawData)
        for person in data['message']:
            name = (person['name'])
            color = (person['color'])
            print(name)
            print(color)
received_count += 1
if received_count == cmdUtils.get_command("count"):
    received_all_event.set()


Maximal inequality for the Itō integral

Question: Let $W$ be a Brownian motion and $X$ be a predictable process with $$\operatorname E\left[\int_0^t|X_s|^2\:{\rm d}s\right]<\infty\;\;\;\text{for all }t\ge0.$$ Now, let $p\ge2$.

How can we show that $$\operatorname E\left[\sup_{s\in[0,\:t]}\left|\int_0^sX_r\:{\rm d}W_r\right|^p\right]\le C\operatorname E\left[\left|\int_0^t\left|X_s\right|^2\:{\rm d}s\right|^{\frac p2}\right]\tag1$$ for some $C\ge0$.

Let $$q:=\frac p{p-1}.$$ Clearly, we somehow need to apply Doob's inequality and the Itō formula. Doob's inequality yields $$\operatorname E\left[\sup_{s\in[0,\:t]}\left|\int_0^sX_r\:{\rm d}W_r\right|^p\right]\le q^p\operatorname E\left[\left(\left|\int_0^tX_s\:{\rm d}W_s\right|^2\right)^{\frac p2}\right]\tag2.$$ How do we need to proceed from here?
Answer: If $p=2$ then the assertion is a direct consequence of Itô's isometry. From now on I will assume that $p>2$. Moreover, by using a standard stopping technique, we may assume without loss of generality that $$M_t := \int_0^t X_s \, dW_s$$ and its quadratic variation $$\langle M \rangle_t = \int_0^t X_s^2 \, ds$$ are bounded processes. As $p > 2$ the mapping $x \mapsto |x|^p$ is twice continuously differentiable, and therefore an application of Itô's formula gives
$$|M_t|^p = p \int_0^t |M_s|^{p-1} dM_s + \frac{p(p-1)}{2} \int_0^t |M_s|^{p-2} \, d\langle M \rangle_s.$$
Since $M$ is bounded, the first term on the right-hand side is a martingale; thus
$$\mathbb{E}\left( \sup_{s \leq t} |M_s|^p \right) \leq q^p \mathbb{E}(|M_t|^p) = q^p \frac{p (p-1)}{2} \mathbb{E} \int_0^t |M_s|^{p-2} \, d\langle M \rangle_s$$
and so
$$\mathbb{E}\left( \sup_{s \leq t} |M_s|^p \right) \leq q^p \frac{p(p-1)}{2} \mathbb{E} \left( \langle M \rangle_t \sup_{s \leq t} |M_s|^{p-2} \right).$$
Now an application of Hölder's inequality yields
$$\mathbb{E}\left( \sup_{s \leq t} |M_s|^p \right) \leq q^p \frac{p(p-1)}{2}\left( \mathbb{E} \left[ \sup_{s \leq t} |M_s|^p \right] \right)^{1-2/p} (\mathbb{E}[\langle M \rangle_t^{p/2}]^{2/p}.$$
Hence,
$$\left(\mathbb{E}\left[ \sup_{s \leq t} |M_s|^p \right] \right)^{2/p}\leq q^p \frac{p(p-1)}{2}  (\mathbb{E}[\langle M \rangle_t^{p/2}]^{2/p}$$
and this proves the assertion.
Remark: The Burkholder-Davis-Gundy inequality states that $$\mathbb{E} \left( \sup_{s \leq t} \left| \int_0^s X_s \, dW_s \right|^p \right)$$ is comparable with $$\mathbb{E} \left( \left| \int_0^t X_s^2 \, ds \right|^{p/2} \right),$$
see e.g. Brownian Motion - An Introduction to Stochastic Processes by Schilling & Partzsch for a proof.

Maximal inequality for the Itō integral


How to find which MPIO path is being used for IO?

Question: We were experimenting MPIO with our Storage array. We saw the Get-Iscsisession and Get-Iscsiconnection cmdlet to find the paths created. But during IO ,i would like to know which path has been used. Is it possible? Which tool can be used to check that? I am using Windows 2016 as Operating system. We connect to our storage via Iscsi initiator.
Answer: The pathes can be checked in iSCSI GUI (even in the gui-less version of Windows) by using iscsicpl command and then by choosing needed target click "Devices" and "MPIO".
To check the path utilization use Performance Monitor (Listset: ISCSI connection / iSCSI Session) or in powershell smth like:
<code>(get-counter -listset "iSCSI Connections")
Get-Counter -Counter "\iSCSI Connections(*)\Bytes Received"
</code>


Spring Batch (Boot) - Using custom app data directory for application configuration - App uses previous run data and not current

Question: I have a Spring Boot / Batch app. I want to use an "app data directory" (not the same as a properties file) versus a db based datastore (ie: SQL/Mongo).
The data stored in the app data directory is aggregated from several webservices and stored as XML. Each Step within the Job will fetch data and write locally, then the next Step in the chain will pick up the created Files and process for the next step (and so on).
The problem here, is each Step will only fetch previous app run data. For example, the data at app start time and not directly after the Step execution.
I understand what is happening here, that Spring is checking for any resources at launch and using them as-is before the Step actually is run.
Is there a magic trick to requesting Spring to stop loading specified resources/Files at app launch?
Note: Using Java Config, not XML and the latest Spring/Boot/Batch versions, also tried @StepScope for all reader/writers
Repo: https://github.com/RJPalombo/salesforceobjectreplicator
Thanks in advance!
Comment: Please, add your configuration classes.  It could help to understand what you are up for. What kind of job parameter do you pass when launching your job?
Comment: I just added the repo to Github. Link is in post. Thanks!
Answer: No, there is no magic :-)
Firstly, your code is very well structured and easy to understand.
The first thing, that pops in my eyes is: Why aren't you using the standard readers and writers from springbatch (FlatFileItemReader/Writer, StaxReader/Writer). There is no need to implement this logic by yourself.
As far as I see, the problem is that you load the whole data in the constructor of the readers.
The whole job-structure (together with step, reader, writer, and processor instances) is created when the spring context is loaded, way before the job actually is executed.
Therefore, the reader just read empty files.
The simplest fix you could make is to implement the "ItemStream" interface for all your readers and writers.
And then reading the data in the open method, instead of the constructur. The open method is called, just before the steps get executed.
But that is only a quick fix and only helps to understand the behaviour of springbatch. The problem with this approach is, that all data is loaded at once, which means, that the memory usage will increase with the amount of data; hence, the memory would blow up when reading lots of data. Something we don't want to have when doing batch processing.
So, I'll recommend that you have a look at the standard readers and writers. Have a look how they work, debug into them. See when the open/close methods are called; check what happens when the read method is called and what it does.
It is not that complicated and having a look at your code, I'm sure that you are able to understand this very fast.


How to change File and Folder permissions on Windows 7 using Command Line (CLI)?

Question: I am trying to use chmod utility on windows command line but it does not work. I am looking for the command to change the files and folder permission on windows.
Comment: Just found the "icacls" command for windows. To find more information of the command just type "c:\icacls /?". The "icacls" command helps to change the file permission on windows.
Answer: The following commands will help to take the ownership of the directory and files:
  D:\>takeown /f D:\path\to\directory /r /d y
  D:\>icacls D:\path\to\directory /grant administrators:F /t


Convolution of two dependent distributions in MATLAB

Question: Assume that I have two discrete random variables $X$ and $Y$.
$X ∈ \{1,3,3,5,7,7,7,9,9,9,9,9\}$
and
$Y ∈ \{5,5,9,9,10,12,13\}$
Where their empirical CDFs are given as:
$F_x(1) = 0.0833, F_x(3) = 0.25, F_x(5) = 0.33, F_x(7) = 0.5833 and F_x(9) = 1 $
and
$F_y(5) = 0.2857, F_y(9) = 0.5714, F_y(10) = 0.7143, F_y(12) = 0.8571 and F_y(13) = 1 $
Assuming their joint distribution is
$H(x,y) = F_x(x)F_y(y)$
which is actually the "assumption" of $X$ and $Y$ are independent.
How can i calculate the $Z = X + Y$ and $F(z)$ in MATLAB ?
Note: I gave the $H(x,y)$ as a simple product function for the simplicity, but it can be anything in reality which actually models the dependency between $X$ and $Y$.
Edit 1: Ok, based on @gunes's answer. What i "actually" do is to calculate the distribution of Frechet Lower Bound of $Z$.
From the definition $H_l(u,v) = max(u + v - 1, 0)$ where $u = F_{x}(x)$ and $v = F_{y}(y)$ and $F_{x}$, $F_{y}$ corresponds to the CDFs of $X$ and $Y$.
Assuming $H(x,y) = H_l(u,v)$ where $x = F_{x}^{-1}(u)$ and $y = F_{y}^{-1}(v)$
So if I want to find $P(18)$, I can select ($9$ from $X$ and $9$ from $Y$) and ($5$ from $X$ and $13$ from $Y$).
So, $H(9,9) = max(F_{x}(9) + F_{y}(9) - 1, 0) = max(1 + 0.5714 - 1) = 0.5714$
and
$H(5,13) = max(F_{x}(5) + F_{y}(13) - 1, 0) = max(0.33 + 1 - 1) = 0.33$
So, if i understood correctly I now have $H(9,9)$ and $H(5,13)$, but what am i supposed to do with those values ?
I think in some point i misunderstood something, but what?
Answer: To be precise, you must be using $*$ sign for multiplication, and $H(x,y)$ is the joint CDF, i.e. $$H(x,y)=P(X\leq x, Y\leq y)=P(X\leq x)P(Y\leq y)=F_X(x)F_Y(y)$$
I just felt obliged to verify it since your title and keyword mention convolution, which is quite commonly shown with the operator $*$.
Apart from this, you've your empirical CDFs and therefore PMFs. The PMF of $Z=X+Y$ is the convolutions of the PMFs of $X$ and $Y$, when they're independent. This can be done via conv(fx,fy) command, where fx and fy are your empirical PMFs, i.e. fx = [0.0833,0,0.1667,0,0.0833, 0, ...], fy = [0,0,0,0,0.2857,...]. You can start fy from 5 and then append four 0 in the end, it doesn't matter. You just need to respect the indices. After you've found the PMF, it's just cumsum operation to reach the CDF.
For the dependent case, all you need is the joint distribution, and we can't use convolution any more. You've have a table of values for $H(x,y)$, which actually means $P(X\leq x, Y\leq y)$. A straightforward method would be first obtaining the joint PMF by differencing the joint CDF, because in the end, we'll need the probability $P(X+Y\leq z)$. If we had the joint PMF, we'd obtain joint CDF by cumsuming in each coordinate direction which means we need to take difference in each direction to get the joint PMF.
When you have the joint PMF, the coding depends on how you constructed your table (i.e. matrix). If you've one entry for each integer, then $X+Y=Z$ corresponds to sweeping an oblique line throughout your matrix, and summing the probability masses below the line for each possible $z\in [\min (X)+\min (Y), \max (X)+\max (Y)]$.
Alternative: w/o going back to joint PMF, it seems like we can calculate (assuming integer steps) $$P(X+Y\leq z)=\sum_{x+y=z} H(x,y)-\sum_{x+y=z-1} H(x,y)$$ Think about a simple $3\times 3$  joint PMF matrix, and the values of $x,y\in \{0,1,2\}.$ $P(X+Y\leq 2)$ is actually the sum of the joint PMF values at coordinates $(0,0),(0,1),(1,0),(0,2),(2,0)$, i.e. below (and including) the diagonal, $x+y=2$. The summation of $H(1,1), H(0,2), H(2,0)$ includes the squares in $x+y=2$ once, $x+y=1$ twice and $x+y=0$ three times. Similarly, the summation of $H(1,0)$  and $H(0,1)$ includes the squares $(0,1),(1,0)$ once and $(0,0)$ twice. When we subtract the latter from the first we'll obtain a sum where each square in joint PMF is represented exactly once in the summation.
Comment: Thank you very much. This has clarified a lot for me. For the "*" sign, you are right i used that on the purpose of multiplication operation.
I have one more thing that i do not understand. Consider that X and Y are dependent and I want to find F_z(18). Both H(5, 13) and H(9,9) gives the Z=18. What i did not understand is that what am i supposed to do with H(5,13) and H(9,9) based on my example, do i need to sum the results of H(9,9) and H(5,13) which i think its not true. Assume that H(x,y) = F_x(x) + F_y(y) in this case.
Comment: $H(x,y)$ is the area under the rectangle $X\leq x$, $Y\leq y$; but we actually need $X+Y\leq z$. So, a straightforward way to compute it is to go back to joint PMF and calculate the area/probability mass under the sweeping line.
Comment: @LeventBekdemir I've also added an alternative approach using the CDF directly.
Comment: thanks i edited my question and added my "real" purpose if you can help i would be very appreaciated


Making data sent from a mobile phone client to a Java EE web app via web service wait for confirmation before being saved in a database

Question: What is the best approach for making data wait for administrator confirmation before saving it in a database in Java EE web application after getting it (the data) from an mobile phone client through a REST web service?
I think it's not a good idea to save the data in the application scope as it can use a lot of memory and it can take a lot of time for the administrator to confirm the storage of the data in the database which with a eventually huge amount of data can decrease the performance of the web app in the meanwhile.
What do you think?
Thanks in advance for your suggestions.
Answer: Create a table (T1) to hold the temporary data. Once your admin starts viewing, show him the data from this T1 table. Once approved, copy into your actual table, and once done, delete from T1 table.


Imprimir variáveis de dois foreach numa tabela em diferentes colunas - codeigniter

Question: Estou a tentar imprimir uma tabela que aceda a base de dados e que insira os diferentes valores de cada array em cada coluna. O problema consiste em não imprimir corretamente os valores..
Controller:
 private function mostrar_resultados() {

    //vai buscar o resultado da pesquisa
    $query = $this->Oportunidades_model->busca_oportunidade();
    $query1 = $this->Oportunidades_model->busca_funcao();

    //obtem o resultado em forma de array bidimensional
    $data['resultados_pesquisa'] = $query->result_array();
    $data['resultados_funcao']=$query1->result_array();

    //passa as variáveis anteriores para a view
    $this->load->view('verOportunidades', $data);

  }

Model:
class Oportunidades_model extends CI_Model {
  //fazer echo
  //edita um voluntario;
  function busca_oportunidade()
  {
    $interrogacaoVol_sql = "SELECT id_oport, descricao_oport FROM oportunidade";
    $query = $this->db->query($interrogacaoVol_sql);
    return $query;
  }

  function busca_funcao()
  {
    $interrogacaoVol_sql = "SELECT id_fun, descricao_fun FROM funcao";
    $query = $this->db->query($interrogacaoVol_sql);
    return $query;
  }
}

View:

    Descricao
    Função

  <?php
  foreach ($resultados_pesquisa as $linha)
  {
    $descricao = $linha["DESCRICAO_OPORT"];

    foreach ($resultados_funcao as $key) {
      $funcao = $key["DESCRICAO_FUN"];
      echo "
$descricao	$funcao
";
    }
  }
  ?>

Output com 2 oportunidades registadas:
 Descricao  Função
    teste1      resultado1
    teste1      resultado2
    teste2      resultado1
    teste2      resultado2

Desejado:
  Descricao Função
    teste1      resultado1
    teste2      resultado2

Comment: Conseguiu ajustar?
Answer:
NOTA: estou me atendo ao que você colocou em "desejado" na pergunta. Olhando o resto do seu código, me parece que não está tendo uma maneira segura de se fazer a coluna da esquerda se relacionar com a da direita, mas para resolver isso, não dá só com o que foi perguntado.

Supondo que $resultados_pesquisa e $resultados_funcao tenham o mesmo tamanho, basta isso:
<?php
   $count = count( $resultados_pesquisa );
   for( $i = 0; $i < $count; $i++ )
   {
      echo '
';
      echo ''.$resultados_pesquisa[$i]['DESCRICAO_OPORT'].'	';
      echo ''.$resultados_funcao[$i]['DESCRICAO_FUN'].'	';
      echo '
';
   }
?>

Por segurança, pode fazer o $count pelo valor com menos dados:
   $count = min( count( $resultados_pesquisa ), count( $resultados_funcao) );

Se os dados não estiverem em HTML, é fundamental usar htmlentities:
   echo ''.htmlentities($resultados_pesquisa[$i]['DESCRICAO_OPORT']).'	';

(mesma coisa para a linha seguinte).
Comment: Funcionou, obrigado!
Comment: Se no caso de não terem o mesmo tamanho como poderia fazer?
Comment: @Rafael tá na resposta, a linha com o "min" faz a tabela pegar o tamanho menor. se precisar do maior e deixar em branco o resto, basta trocar o min por max, e colocar um if para cada echo para não pegar índices inexistentes.