How find this integral $I=\int_{0}^{1}\sqrt{1-W^2(x)}dx$

Question: How find this nice integral

$$I=\int_{0}^{1}\sqrt{1-W^2(x)}dx$$

where, $W(x)$ is  Lambert W function
My try: let $$\sqrt{1-W^2(x)}=u\Longrightarrow W(x)=\sqrt{1-u^2}$$
and since $x=W(x)e^{W(x)}$
so

$$x=W^{-1}(\sqrt{1-u^2})=\sqrt{1-u^2}e^{\sqrt{1-u^2}}?$$
  so
  $$dx=-ue^{1-u^2}\dfrac{1+\sqrt{1-u^2}}{\sqrt{1-u^2}}du$$
  so
  $$I=\int_{1}^{a}-u^2e^{1-u^2}\dfrac{1+\sqrt{1-u^2}}{\sqrt{1-u^2}}du$$

where $a$ such

$$\sqrt{1-a^2}e^{\sqrt{1-a^2}}=1(a>0)$$

then I can't,Thank you very much .
Comment: What's the origin of the question? Are you sure there's a closed form solution in terms of some kind?
Comment: It would make more sense if the upper integration limit were *e* instead of $1$, since $W(e)=1$. But even so, a closed form solution is unlikely.
Comment: @Lucian: At this time all double summation terms will be cancelled and related to modified bessel function of the first kind.
Answer: $\int_0^1\sqrt{1-W^2(x)}~dx$
$=\int_0^\Omega\sqrt{1-x^2}~d(xe^x)$
$=\int_0^\Omega e^xx\sqrt{1-x^2}~dx+\int_0^\Omega e^x\sqrt{1-x^2}~dx$
$=\int_0^{\sin^{-1}\Omega}e^{\sin x}(\sin x)\sqrt{1-\sin^2x}~d(\sin x)+\int_0^{\sin^{-1}\Omega}e^{\sin x}\sqrt{1-\sin^2x}~d(\sin x)$
$=\int_0^{\sin^{-1}\Omega}e^{\sin x}\sin x\cos^2x~dx+\int_0^{\sin^{-1}\Omega}e^{\sin x}\cos^2x~dx$
$=\int_0^{\sin^{-1}\Omega}e^{\sin x}\sin x(1-\sin^2x)~dx+\int_0^{\sin^{-1}\Omega}e^{\sin x}(1-\sin^2x)~dx$
$=\int_0^{\sin^{-1}\Omega}e^{\sin x}~dx+\int_0^{\sin^{-1}\Omega}e^{\sin x}\sin x~dx-\int_0^{\sin^{-1}\Omega}e^{\sin x}\sin^2x~dx-\int_0^{\sin^{-1}\Omega}e^{\sin x}\sin^3x~dx$
$=\int_0^{\sin^{-1}\Omega}\sum\limits_{n=0}^\infty\dfrac{\sin^{2n}x}{(2n)!}dx+\int_0^{\sin^{-1}\Omega}\sum\limits_{n=0}^\infty\dfrac{\sin^{2n+1}x}{(2n+1)!}dx+\int_0^{\sin^{-1}\Omega}\sum\limits_{n=0}^\infty\dfrac{\sin^{2n+1}x}{(2n)!}dx+\int_0^{\sin^{-1}\Omega}\sum\limits_{n=0}^\infty\dfrac{\sin^{2n+2}x}{(2n+1)!}dx-\int_0^{\sin^{-1}\Omega}\sum\limits_{n=0}^\infty\dfrac{\sin^{2n+2}x}{(2n)!}dx-\int_0^{\sin^{-1}\Omega}\sum\limits_{n=0}^\infty\dfrac{\sin^{2n+3}x}{(2n+1)!}dx-\int_0^{\sin^{-1}\Omega}\sum\limits_{n=0}^\infty\dfrac{\sin^{2n+3}x}{(2n)!}dx-\int_0^{\sin^{-1}\Omega}\sum\limits_{n=0}^\infty\dfrac{\sin^{2n+4}x}{(2n+1)!}dx$
$=\int_0^{\sin^{-1}\Omega}\left(1+\sum\limits_{n=1}^\infty\dfrac{\sin^{2n}x}{(2n)!}\right)dx+\int_0^{\sin^{-1}\Omega}\sum\limits_{n=0}^\infty\dfrac{2(n+1)\sin^{2n+1}x}{(2n+1)!}dx-\int_0^{\sin^{-1}\Omega}\sum\limits_{n=1}^\infty\dfrac{2n\sin^{2n+2}x}{(2n+1)!}dx-\int_0^{\sin^{-1}\Omega}\sum\limits_{n=0}^\infty\dfrac{2(n+1)\sin^{2n+3}x}{(2n+1)!}dx-\int_0^{\sin^{-1}\Omega}\sum\limits_{n=0}^\infty\dfrac{\sin^{2n+4}x}{(2n+1)!}dx$
For $n$ is any natural number,
$\int\sin^{2n}x~dx=\dfrac{(2n)!x}{4^n(n!)^2}-\sum\limits_{k=1}^n\dfrac{(2n)!((k-1)!)^2\sin^{2k-1}x\cos x}{4^{n-k+1}(n!)^2(2k-1)!}+C$
This result can be done by successive integration by parts.
Similarly, for $n$ is any non-negative integer,
$\int\sin^{2n+2}x~dx=\dfrac{(2n+2)!x}{4^{n+1}((n+1)!)^2}-\sum\limits_{k=0}^n\dfrac{(2n+2)!(k!)^2\sin^{2k+1}x\cos x}{4^{n-k+1}((n+1)!)^2(2k+1)!}+C$ and $\int\sin^{2n+4}x~dx=\dfrac{(2n+4)!x}{4^{n+2}((n+2)!)^2}-\sum\limits_{k=0}^{n+1}\dfrac{(2n+4)!(k!)^2\sin^{2k+1}x\cos x}{4^{n-k+2}((n+2)!)^2(2k+1)!}+C$
$\int\sin^{2n+1}x~dx$
$=-\int\sin^{2n}x~d(\cos x)$
$=-\int(1-\cos^2x)^n~d(\cos x)$
$=-\int\sum\limits_{k=0}^nC_k^n(-1)^k\cos^{2k}x~d(\cos x)$
$=\sum\limits_{k=0}^n\dfrac{(-1)^{k+1}n!\cos^{2k+1}x}{k!(n-k)!(2k+1)}+C$
Similarly, $\int\sin^{2n+3}x~dx=\sum\limits_{k=0}^{n+1}\dfrac{(-1)^{k+1}(n+1)!\cos^{2k+1}x}{k!(n-k+1)!(2k+1)}+C$
$\therefore\int_0^{\sin^{-1}\Omega}\left(1+\sum\limits_{n=1}^\infty\dfrac{\sin^{2n}x}{(2n)!}\right)dx+\int_0^{\sin^{-1}\Omega}\sum\limits_{n=0}^\infty\dfrac{2(n+1)\sin^{2n+1}x}{(2n+1)!}dx-\int_0^{\sin^{-1}\Omega}\sum\limits_{n=1}^\infty\dfrac{2n\sin^{2n+2}x}{(2n+1)!}dx-\int_0^{\sin^{-1}\Omega}\sum\limits_{n=0}^\infty\dfrac{2(n+1)\sin^{2n+3}x}{(2n+1)!}dx-\int_0^{\sin^{-1}\Omega}\sum\limits_{n=0}^\infty\dfrac{\sin^{2n+4}x}{(2n+1)!}dx$
$=\left[x+\sum\limits_{n=1}^\infty\dfrac{x}{4^n(n!)^2}-\sum\limits_{n=1}^\infty\sum\limits_{k=1}^n\dfrac{((k-1)!)^2\sin^{2k-1}x\cos x}{4^{n-k+1}(n!)^2(2k-1)!}\right]_0^{\sin^{-1}\Omega}+\left[\sum\limits_{n=0}^\infty\sum\limits_{k=0}^n\dfrac{2(-1)^{k+1}(n+1)!\cos^{2k+1}x}{(2n+1)!k!(n-k)!(2k+1)}\right]_0^{\sin^{-1}\Omega}-\left[\sum\limits_{n=1}^\infty\dfrac{x}{4^n(n-1)!(n+1)!}-\sum\limits_{n=1}^\infty\sum\limits_{k=0}^n\dfrac{(k!)^2\sin^{2k+1}x\cos x}{4^{n-k}(n-1)!(n+1)!(2k+1)!}\right]_0^{\sin^{-1}\Omega}-\left[\sum\limits_{n=0}^\infty\sum\limits_{k=0}^{n+1}\dfrac{2(-1)^{k+1}(n+1)!(n+1)\cos^{2k+1}x}{(2n+1)!k!(n-k+1)!(2k+1)}\right]_0^{\sin^{-1}\Omega}-\left[\sum\limits_{n=0}^\infty\dfrac{(2n+3)x}{4^{n+1}n!(n+2)!}-\sum\limits_{n=0}^\infty\sum\limits_{k=0}^{n+1}\dfrac{(2n+3)(k!)^2\sin^{2k+1}x\cos x}{4^{n-k+1}n!(n+2)!(2k+1)!}\right]_0^{\sin^{-1}\Omega}$
$=\sum\limits_{n=0}^\infty\dfrac{\sin^{-1}\Omega}{4^n(n!)^2}-\sum\limits_{n=1}^\infty\sum\limits_{k=1}^n\dfrac{((k-1)!)^2\Omega^{2k-1}\sqrt{1-\Omega^2}}{4^{n-k+1}(n!)^2(2k-1)!}-\sum\limits_{n=0}^\infty\sum\limits_{k=0}^n\dfrac{2(-1)^k(n+1)!(1-\Omega^2)^{k+\frac{1}{2}}}{(2n+1)!k!(n-k)!(2k+1)}-\sum\limits_{n=1}^\infty\dfrac{\sin^{-1}\Omega}{4^n(n-1)!(n+1)!}+\sum\limits_{n=1}^\infty\sum\limits_{k=0}^n\dfrac{(k!)^2\Omega^{2k+1}\sqrt{1-\Omega^2}}{4^{n-k}(n-1)!(n+1)!(2k+1)!}+\sum\limits_{n=0}^\infty\sum\limits_{k=0}^{n+1}\dfrac{2(-1)^k(n+1)!(n+1)(1-\Omega^2)^{k+\frac{1}{2}}}{(2n+1)!k!(n-k+1)!(2k+1)}-\sum\limits_{n=0}^\infty\dfrac{(2n+3)\sin^{-1}\Omega}{4^{n+1}n!(n+2)!}+\sum\limits_{n=0}^\infty\sum\limits_{k=0}^{n+1}\dfrac{(2n+3)(k!)^2\Omega^{2k+1}\sqrt{1-\Omega^2}}{4^{n-k+1}n!(n+2)!(2k+1)!}$
Comment: Quick question regarding your notation since I'm unfamiliar with the Lambert-W. Your work seems to imply $\Omega:=W(1)$. Is that correct, and is this standard usage?
Comment: At least http://en.wikipedia.org/wiki/Omega_constant and http://mathworld.wolfram.com/OmegaConstant.html claim that it is the standard notation.
Answer: I would make the substitution $u=W(x)$, so $x=ue^u$ and $dx=(u+1)e^u du$, yielding
$$
I=\int_{0}^{\Omega}(u+1)\sqrt{1-u^2}\cdot e^udu;
$$
here $\Omega=W(1)\approx0.573$.  Now expand the square root in powers of $u$:
$$
I=\int_{0}^{\Omega}(u+1)\left(\sum_{k=0}^{\infty}c_ku^{2k}\right)e^u du=\sum_{k=0}^{\infty}c_k\int_{0}^{\Omega}(u^{2k}+u^{2k+1})e^u du =\sum_{k=0}^{\infty}c_k u^{2k+1}\left(\Gamma(2k+1,-u)-\Gamma(2k+2,-u)\right)\big\vert_{0}^{\Omega}=\sum_{k=0}^{\infty}c_k\left(\Omega^{2k+1}\Gamma(2k+1,-\Omega)-\Omega^{2k+2}\Gamma(2k+2,-\Omega)\right)=\sum_{k=1}^{\infty}d_k\Omega^{k},
$$
where
$$
c_k=\frac{1}{k!}\frac{d^k}{dx^k}\sqrt{1-x}=(-1)^k\left(\frac{3}{2}-k\right)_{k}
$$
and
$$
d_k=(-1)^{k-1} c_{\lfloor{(k-1)/2}\rfloor}\Gamma(k,-\Omega).
$$
Putting these together,
$$
I=\sum_{k=1}^{\infty}(-1)^{k-1+\lfloor{(k-1)/2}\rfloor}\left(\frac{3}{2}-\left\lfloor{\frac{k-1}{2}}\right\rfloor\right)_{\lfloor{(k-1)/2}\rfloor}\Gamma(k,-\Omega)\Omega^{k}.
$$


Bayes network, what is the purpose of it?

Question: I really don't understand what is the purpose of the Bayes network, actually how to implement it into a useful application.
It all starts with the data. Let's assume I observe some universe and I have three random variables $A,B,C$. From there I can create a joint distribution table (see table below). As far as I understand it, this is my solid base, from there on I can use some probability laws and infer everything that I would like and I am done.

And now let's go to a problem. If I understand correctly Bayes networks are based on assumption. Therefore one can say (according to a data above), we can make the following model:

$P(A,B,C) = P(C|A,B) \cdot P(B|A) \cdot P(A)$
following conditional independence:
$P(A,B,C) = P(C|A,B) \cdot P(B) \cdot P(A)$
if we would infer $P(B|C,A) = P(C|A,B) \cdot P(B) / P(C|A)$
But just look the joint probability table above. Plug the data to formula and you would see how wrong this assumption is.
Just looking at the table: $P(B=1|C=1,A=1) = 0.31$
Using Bayes network:
$P(B=1| C= 1, A=1) = P(C=1|A=1,B=1) \cdot P(B=1) / P(C=1|A=1)$ results
in 0.42
So my point is:

If you use joint probability table only, you get result from data, which is accurate and you don't have to assume anything. Computing gets more difficult if you have more random variables, but o.k...
To use Bayes network and create a graph, you need to make a very expensive assumption of your model. As more random variables you have, it's more likely you fail with assumption. I have presented you assumption on conditional independence can give you totally wrong result and it's a simple 3 random variable model. Now think if size would increase.

But, I know I fail to see something very important and I would appreciate if you could help me understand this better. Thank you.
Comment: For clarification: how did you get $P(B=1 | C=1, A=1) = 0.31$? Because there are two rows where both $A$ and $C$ equal 1, and for these $B=1$ in one row. Am I missing something here?
Comment: Yes, two rows where A and C are 1. I summed this two rows, which is 0,0889... and then I divided first row with 0,0889, and you get 0,31 approx.
Comment: Ah, I overlooked the last columns. So it is basically just 18/(18+40) in that case. Got it.
Comment: @horseoftheyear yes, that would be right. and thank you for edit:)
Answer: Bayes Nets saves you from needing to estimate and store a large number of parameters. If you have $V$ variables with $D$ possible values each, to create the joint distribution table you would need to estimate and store $O(D^V)$ different parameters. In real problems with 100s of variables with many possible values each, this is clearly impractical. You'll never have enough data to create the table (and likely run out of computational resources as well).
By using the conditional Independence relations you can get away with estimating a much smaller number of parameters. But of course, as your example shows, you need to ensure that you have the conditional independence structure right - otherwise you will not get correct answers.
But at the same time in a real problem, you have limited amount of data, and your computing resources are not unbounded. So even if you get the structure wrong, Bayes net type approach may still be the only viable option. And of course, there  are also methods to actually estimate the conditional independence structure - but learning the structure is generally considered difficult.
Edited to add: the wikipedia article seems quite good.


Not returning value on output

Question: ****Aim**:** Simply to return a value based on a stored procedure search, this is based on a stored procedure that works with a datagrid but in this instance I only want one value.
****Error**:** Nothing is returned!
Notes: Stripped down version
****Code**:**
.ASPX
 <asp:Label ID="lblLocationsOutput" runat="server" Text="--" CssClass="lblLocationsOutput" />

.ASPX.VB
 Dim connection As SqlConnection
        Dim command As New SqlCommand
        'Dim ds As New DataSet
        Dim ConnectionString As String = System.Configuration.ConfigurationManager.ConnectionStrings("mySQL").ToString()
        connection = New SqlConnection(ConnectionString)
        Dim vLocationNumber As Integer
        connection.Open()
        With command
            .Connection = connection
            .CommandText = "spSearchLocation" 'include audit names
            .CommandType = CommandType.StoredProcedure
            .Parameters.Clear()
            .Parameters.Add("@LocationsNumber", SqlDbType.Int)
            .Parameters("@LocationsNumber").Direction = ParameterDirection.Output
            .Parameters.AddWithValue("@sUPRN", sUPRN.Text & " ")
            .ExecuteNonQuery()

            If .Parameters("@LocationsNumber").Value.ToString = "" Then
                vLocationNumber = "0"
            End If
        End With

        lblLocationsOutput.Text = vLocationNumber

Stored Procedure:
USE DATABASE
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
ALTER PROCEDURE dbo.spSearchLocation

@sUPRN varchar(20),
-- Add the parameters for the stored procedure here
@LocationsNumber Int OUTPUT

AS
BEGIN

--Main SQL
DECLARE @SQLSTRING AS VARCHAR(MAX)

IF LTRIM(RTRIM(@sUPRN)) <> ''
SET @SQLSTRING = @SQLSTRING + 'or UPRN LIKE ''%''' + QUOTENAME(LTRIM(RTRIM(@sUPRN))) + '''%'''

EXECUTE(@SQLSTRING)

END

SET @LocationsNumber = @SQLSTRING

Looked at references such as: enter link description here
Hopefully a simple error. Does not work even when searching say just a UPRN that I know is correct.
Answer: Add a
   Select  @LocationsNumber at the end of the Stored Procedure
Comment: Tried directly after and then before 'END' and after SET LocationsNumber = @SQLSTRING

Not returning value on output


Music sheet for piano, with two clefs, whats the reason for additional chord symbols?

Question: In some music sheets, I see two clefs for both hands, but also chord symbols on top, example:

What is the reason for it? Are this chords just for reference?
Is it enough to just play notes as is on the clefs, or should I use the chords for additional arrangement?
I don't think it's for a second instrument, it's supposed to be arrnaged ofr piano.
Comment: For those who are interested in this song, this is "Summer" by Joe Hisaishi ([YouTube video](https://www.youtube.com/watch?v=J7or0noYfMA))
Comment: @AndrewT. And for those who are interested even further, it's the main theme from the movie [Kikujiro](https://en.wikipedia.org/wiki/Kikujiro).
Comment: And for those who are insterested even further I made an arrangement for guitar. And it includes the chords :-) http://hjg.com.ar/ghibli/musica/kikujiro/ https://www.youtube.com/watch?v=u6gXfOR2Lrk
Answer: The chords are for reference, for the sake of other instruments or improvisations.  As a piano player, playing the score is already meeting your quota of notes.  If you want to diverge, the chord symbols may help with that.
Comment: Also, some pianists might want to use the chord names to play a simplified version of the part.
Answer: The chord symbols are there mainly for guitarists. They are the names of the chords in each bar, and most guitarists are used to reading the chord symbols when playing along with the piano part.
They are also an opportunity for the piano player to put his own interpretation to the harmonies that the symbols show. Sometimes, I may read exactly what the dots show, others, I'll go by the chord symbols and play different inversions (or extensions) of those chords.
Answer: If it's an instructional piece, intended to be played meticulously by a pianist, I don't really know why the chords are there either!
But the written LH part is pretty generic. Plenty of scope to 'do your own thing'. And maybe a guitar or ukelele  might strum along.  Maybe it might be played on a 'home keyboard' where you play the melody with the right hand and hold down a chord shape in the left, letting an 'auto-accompaniment' feature do its stuff.   The chord symbols enable all of this, and more.
Comment: If it's an instructional piece, I still see instructional value in showing the chords so the student knows he's not just playing random notes.


Choosing two sets of values with the least difference between the averages of the sets

Question: This is probably a simple Combination problem but I can't think of how to solve it in LibreOffice. I run multiplayer games along with seven of my friends, on two teams of 4 players each, for a total of eight players. Each player is assigned a skill score. How do I "balance the teams" by calculating the correct team combination that will result in the lowest possible difference in average skill score between the two teams?
I think the correct approach is to calculate every possible permutation of the teams, calculate the permutation with the lowest average difference, and then return that team roster.
I'm not sure if this is a very well-known problem whose solution is obvious to spreadsheet programmers or whether I'd need to write some code to solve this problem.
Answer: This looks like an optimization variant of the partition problem; essentially, I think you do need to calculate all possible permutations.
Let the sum of all scores be $S$; for each four person subset (of which there are $8\cdot7\cdot6\cdot5/4! = 70$ possibilities) compute the sum $k$ hence the average $k/4$; then compute the complement four players' average as $(S-k)/4$.
Even this approach double counts; so really there are only $35$ possibilities to check.
You could do this by hand!
Comment: This describes the problem perfectly. Now all I have to do is write some code to make it more automated...
Comment: @user334918 To avoid the double counting, you could pick only four person subsets that contain yourself, and then compute the corresponding average and the complement average. As described above, the number of possibilities now becomes $7\cdot6\cdot5/3! = 35$; equivalently, counting the complement sets (where you are excluded) gives $7\cdot6\cdot5\cdot4/4! = 35$. Either way, you really could do this by hand...


Find the Rejection Region

Question: A drug claims to lower the blood pressure (by at least 10 mmHg) in 30% of all patients. A random sample taken shows a significant drop in blood pressure for only 20% of patients (n =35). Test the original claim using a one-sided test at the 1% significance level.
I was attempting a past paper and this question came up, so i would proceed by stating the null and alternate hypothesis,
Null Hypothesis -> Blood pressure decreases by 30%
Alternate Hypothesis -> Blood Pressure decreases by 20%
For the rejection region,
significance level  = P(Reject Null| Null true)
.01 = P(X > c|Null True)
so c would be 1.28 by looking at the Z table
so the rejection region would be X > 1.28
Im not just to sure about what the conclusion would be?
Comment: I assume you've computed the quotient of the likelihoods? What do you obtain for $c$?
Comment: @Siron so LR = .3/.2 = 1.5 Integrating that from 0 to c, we would get 1.5c = 0.01; c = 2/3. Is that right?
Comment: $20\%$ is the observation, not the alternative hypothesis (or rather, $7$ out of $35$ is the observation)
Comment: @Henry what would my alternate hypothesis be then?
Comment: From the question I would guess the alternative hypothesis is that fewer than $30\%$ of patients see a significant drop in blood pressure
Answer: You need to find the probability that with a binomial distribution with parameters $n=35, p=0.3$, you observe $0.2\times 35=7$ or fewer successes.
This probability is about $0.13$ (though you might get about $0.1$ if you use a normal approximation without continuity correction), which is rather greater than $0.01$, so you should not reject the null hypothesis.
In R, the calculations might be
<code>> pbinom(7, size=35, prob=0.3)                  # exact binomial
[1] 0.1326467
>
> pnorm(7.5/35, mean=0.3, sd=sqrt(0.3*0.7/35))  # normal with continuity correction
[1] 0.1342407
>
> pnorm(7/35, mean=0.3, sd=sqrt(0.3*0.7/35))    # normal without continuity correction
[1] 0.0983528
</code>
Comment: Ahh I get it, i made a mistake reading the question.
So now we find the probability by P(X=1) + P(X=2) .... + P(X=7) = 0.13 > 0.01, hence we don't reject it. Is that correct?
Comment: Yes, though you should also include $P(X=0)$
Comment: Oh right, Thanks!
Comment: Incidentally, this is the answer to what the conclusion would be.  The rejection region would be $4$ successes or fewer out of $35$: calculate $P(X=0)+P(X=1)+P(X=2)+P(X=3)+P(X=4)$ and see that adding $P(X=5$ would be too much
Comment: I'm sorry, i don't quite understand what you're trying to say?
Comment: I am saying that the *rejection region* is those observations which would have led you to rejecting the null hypothesis.  This is $0,1,2,3,4$ out of $35$, so does not include $7$ out of $35$

Find the Rejection Region


Como confirma o UPDATE com PDO

Question: Tem alguma função no PDO que permite verificar se o UPDATE concorreu com sucesso? Igual ao método 'lestInsertId()' é que usado para verificar se foi gerado uma nova ID em um tabela com auto incremento depois de um INSERT.
Answer: Você pode usar o rowCount:
$stmt->rowCount();

Quando você faz um SELECT, ele retorna a quantidade de resultados, mas quando faz UPDATE, DELETE etc ele retorna o número de linhas afetadas.
if( $stmt->rowCount() > 0 ) {
   echo 'ocorreram alterações na tabela';
} else {
   echo 'nada foi alterado';
}

Notar que isto não tem nada a ver com testar se a query funcionou ou não por causa de erros. Para erros, você tem os métodos tradicionais.
A resposta é basicamente como confirmar se houve update ou não, os outros erros devem ser verificados sempre, de qualquer forma.
Manual:

http://php.net/manual/pt_BR/pdostatement.rowcount.php

Se estiver usando MySQL, tem uma opção ao inicializar o PDO que muda o comportamento do retorno de forma ao rowCount retornar valores mesmo se o UPDATE localizou as linhas, mas não alterou pelo valor ser igual:
$pdo = new PDO($dsn, $u, $p, array(PDO::MYSQL_ATTR_FOUND_ROWS => true));

Originalmente se voce faz um UPDATE tabela SET valor = 0 WHERE id = 0;, e o valor já era zero na tabela, isto não é contado como atualização, mesmo existindo id igual a zero. A propriedade PDO::MYSQL_ATTR_FOUND_ROWS serve para mudar o comportamento, retornando o número localizado pelo WHERE, e não os valores efetivamente alterados.

Como confirma o UPDATE com PDO


e possivel usar varios AddScoped?

Question: Estou fazendo uma conexão com MySql usando .net 6 no asp.net mvc. Estou usando Interface e a Model no AddScoped em program.cs, mas é possível eu usar varios AddScoped com interfaces e models diferentes?
builder.Services.AddDbContext<BancoContext>(options => options.UseMySql("server=localhost;database=contatosdb;uid=root;pwd=", ServerVersion.Parse("8.0.30-mysql")));
builder.Services.AddScoped<IContatoRepositorio, ContatoRepositorio>();

Comment: Veja a orientação em [Diretrizes de injeção de dependência](https://docs.microsoft.com/pt-br/dotnet/core/extensions/dependency-injection-guidelines).*...Se uma classe tiver muitas dependências injetadas, isso poderá ser um sinal de que a classe tem muitas responsabilidades e violará o SRP (princípio de responsabilidade única). Tente refatorar a classe movendo algumas das responsabilidades para uma nova classe...*.
Comment: Relacionado a [Quais são as diferenças entre os métodos AddTransient, AddScoped e AddSingleton para injeção de serviços de depedencias?](https://pt.stackoverflow.com/q/528196/137387) e [O que é e como se usa o SRP?](https://pt.stackoverflow.com/q/100516/137387)
Answer: Sim é possível. O método AddScoped() é um método do container de injeção de dependências do .Net, este método é apenas 1 de 3 métodos disponíveis, nele a sua dependência existe durante o escopo definido pelo container de injeção de dependência, você pode adicionar Implementações (sua Model) para a mesma interface ou adicionar outras interfaces com outras implementações. Vou deixar um link da documentação oficial caso você queira saber mais sobre!
Injeção de Dependência - Microsoft Doc

e possivel usar varios AddScoped?


imagem de fundo não esta aparecendo no ionic viewe e nem no app compilado

Question: Imagem de fundo não esta aparecendo no ionic viewe e nem no app compilado.
Quando eu coloquei para aparecer direto no hmtl desse jeito:
style="background-image:url(../img/santa-filomena3.jpg); background-size: cover;
     background-position: center;"

apareceu a imagem de fundo no browser, mas no ionic view e no app compilado não apareceu.
Alguém já teve esse problema?
Como não estava funcionando no browser criei ele no css, mas não consegui fazer funcionar ainda.
Style.css
.ion-content teste{
     background-image: url(.../img/fundo.jpg);
     background-size: cover;
     background-position: center;
}

principal.html
<ion-view view-title="Home">
  <ion-content class="padding"
               id="teste">

                  Missa

                  Doação

                  Confissão

                 Santa Filomena

                 Fale Conosco

                  Site

    </ion-content>
</ion-view>

Alguem poderia me ajudar?
Answer: Consegui arrumar ja.
css
.principal-custom {
     background-color: #FF4500;
     background-image: url(../img/fundo.jpg);
     background-size: cover;
     background-position: center;
}

principal.html
<ion-view view-title="Home">
  <ion-content class="principal-custom">

                  Missa

                  Doação

                  Confissão

                 Santa Filomena

                 Fale Conosco

                  Site

    </ion-content>
</ion-view>


Why can't I use multiplication rule to calculate probability here?

Question: This is a fairly straight forward problem:
"Two design teams, A and B, are both asked to design a working prototype. Based on past experience

the probability that team A is successful is 2/3;
the probability that team B is successful is 1/2;
the probability that at least one team is successful is 3/4;

What's the probability that team A fails and team B succeeds?"
The solution is 1/12, with explanation below:

P(at least one team is successful) = P(A=1,B=1)+P(A=0,B=1)+P(A=1,B=0) = 3/4
P(team A is successful) = P(A=1,B=1)+P(A=1,B=0) = 2/3
P(team A fails and team B succeeds) = P(A=0,B=1) = P(A=1,B=1)+P(A=0,B=1)+P(A=1,B=0)-(P(A=1,B=1)+P(A=1,B=0)) = 3/4-2/3 = 1/12

So my question is, why can't I simply use the multiplication rule here (since A fails and B succeeds are independent) and say
P(A=0,B=1) = P(A=0)*P(B=1) = (1-2/3)*(1/2) = 1/6     ???
Comment: Because A fails and B succeeds aren't independent?
Comment: now I see that they aren't independent...so does the product `P(A=0)*P(B=1)=1/6` still mean anything?
Comment: No, no immediate meaning.
Answer: Because they AREN'T independent, as given by "the probability that at least one team is successful is 3/4".
Comment: could u plz elaborate more on why "the probability that at least one team is successful is 3/4" reveals dependence in this case?
Comment: If the two were independent, you would get a different probability.
Comment: which would be 5/6 in that case?
Comment: Something like that. If independent, it's $(2/3)*(1/2)+(2/3)*(1/2)+(1/3)*(1/2)=5/6$. So yup, you're correct.


SVN:Externals equivalent for Git

Question:
Possible Duplicate:
SVN external in GIT

Is there an equivalent way to include other repository locations in a Git Branch, like how SVN:Externals works?
Comment: http://stackoverflow.com/questions/571232/svn-external-in-git
Answer: Git submodules and to an extent Git subtree merge.

SVN:Externals equivalent for Git


Does Laravel 6 disable observers in factories / tests?

Question: Ive just written an observer thats sends an e-mail whenever a user is created.
class UserObserver
{
    public function created(User $user)
    {
         Mail::to($user)->send(new UserAccountCreated(
            app('auth.password.broker')->createToken($user),
            $user
        ));
    }
}

I ran phpunit to test if my observer works, and it passed. However I was expecting to get an email for each time my tests create a user.
For example:
/** @test */
    public function an_admin_can_view_all_clients()
    {
        $user = factory(User::class)->create(['is_admin' => true]);
        $client = factory(Client::class)->create();
        $client2 = factory(Client::class)->create();

        $this->actingAs($user)->get(route('clients.index'))
            ->assertSuccessful()
            ->assertSee($client->name)
            ->assertSee($client2->name);
    }

I would expect an email to be sent when that factory creates the user. But I don't receive one in Mailtrap.
Just wondering if and where laravel disables my observer being triggered when my factory creates that user.
Answer: No you have to disable it yourself by using Model::withoutEvents()
For example:
$user = User::first();
User::withoutEvents(function () use ($user) {
    $user->delete();
});

Also in this specific case you can also use the Mail fake system provided by Laravel itself
Comment: I don't have that line anywhere, and didn't receive any emails in mailtrap when I ran phpunit.
Comment: do you have a .env.testing file or a different .env file when you run your tests?
Comment: I only have one env.
In phpunit.xml I set 'APP_ENV' to testing and make an sqlite in memory database.
Comment: What happen if you `dd` inside the `created` method during that specific test? Can you it it?
Comment: added dd("hello") to the observer.

phpunit --filter an_admin_can_view_all_clients

returns "hello"
No email in mailtrap
Comment: So the even is dispatched the problem is that something inside your testing configuration is preventing the mail to be sent out. I suggest to check if you have something like "mail.pretend" or different configuration for your testing environments.
Comment: Hmm, not that I can see. And even if it is there somewhere, I didn't write anything like that. So, must be in the core somewhere?
Comment: I've a lot of tests and if I switch my `env.testing` to mailtrap i get those emails so it's something on your codebase
Comment: Ok, I guess I'll look into it. Thanks.


XAML- creating an instance of a class

Question: I am trying to create an instance of a C# class from within the XAML markup of my application.
I am trying to use the instance of the C# class inside a <StackPanel></StackPanel> tag, inside a <TabItem></TabItem> tag that I have nested in the <TabControl></TabControl> tag where I have declared the namespace that the C# class belongs to:
<TabControl xmlns:agent="RAgent">
    <TabItem Header="R">
        <StackPanel>
            ...
        </StackPanel>
    </TabItem>
    <TabItem Header = "BClass">
        <StackPanel>
            <agent:BClass />
        </StackPanel>
    </TabItem>
</TabControl>

The C# class BClass is defined with:
namespace RAgent{
    public partial class BClass : UserControl{
        public BClass(){
            ...
        }
        ...
    }
}

I know that the C# code compiles and runs correctly, as I have previously run this separate to the rest of the application. However, when I currently try to build my code, I get a compile error in the XAML, on the line:
<agent:BClass />

which says:

The name "BClass" does not exist in the namespace "RAgent"

But BClass clearly does exist in the namespace RAgent, as I have declared the namespace at the top of the BClass.cs file with namespace RAgent{...
What am I doing wrong here? Am I trying to instantiate BClass incorrectly from within the XAML file? How should I do this?
Edit
Ok, so I've edited my .xaml file a bit based on the answer at How to create instance of class in XAML?, and on other bits of information I've picked up from various places.
I've added the line:
xmlns:local="clr-namespace:RAgent">

to the top of the file, and then removing the use of xmlns in the <TabControl> tag, and trying to create an instance of the class through local:
<TabControl>
    ...
    <TabItem Header="BClass">
        <StackPanel>
            <local:BClass x:Name="BClass" />
        </StackPanel>
    </TabItem>
</TabControl>

However, I now get a compile error on the line where I'm trying to instantiate the BClass:
<local:BClass x:Name="BClass" />

which says:

A value of type 'BClass' cannot be added to a collection or dictionary of type 'UIElementCollection'.

I tried removing the <StackPanel></StackPanel> tags, and although this removed the above compile error, it left me with one that says:

The name "BClass" does not exist in the namespace "clr-namespace:RAgent"- which it clearly does, as shown by the definition of BClass...

Anyone know how I can resolve this?
Comment: Did you tried to add `x:Key` for this declaration? So the code should look like this ``. Or maybe there is problem with `partial` keyword.
Comment: I've just given this a go, but still get the same compile error, and now also get one that says `A value of type 'BClass' cannot be added to a collection or dictionary of type 'UIElementCollection'`
Comment: xmlns:agent="`clr-namespace`:RAgent" maybe?
Comment: That's what I have... ``, and then inside ``, I have put ``, with the closing tags following: ``
Comment: I've edited my OP to show how I've tried to resolve this issue, and the issues I'm now getting with trying to create an instance of `BClass`...
Answer: I suggest you creating the TabControlin your MainApp and then each TabItemas a UserControl in your project. Then, you can easily instantiate your classes in the corresponding tab by doing
<local:BClass x:Name="BClass"/>
Check Tabs in different XAML views and How to create and use an instance of a class in XAML for a better understanding

XAML- creating an instance of a class


Cannot gitignore codeception.yml file in Laravel 5?

Question: I am working with codeception in Laravel 5 and I have a codeception.yml file sitting in my base project directory which I want to ignore because it has database credentials which vary across machines.
.gitignore file:
/.phpstorm.meta.php
/_ide_helper.php
/vendor
/node_modules
Homestead.yaml
Homestead.json
.env
.env.testing
codeception.yml

I thought this should do it. But git is still tracking the file. What am I doing wrong?
Comment: Have you already committed that file to git in the past?
Comment: Oh yes, I think I would have to remove it too somehow.
Answer: If you have committed the file in the past you will need to remove it from the cache try
git rm --cached codeception.yml

Even if you add a file/directory to the .gitignore file if it has been added to the repo in the past then git will remember it.

it has database credentials which vary across machines.

If you have accidentally committed sensitive data you may want to follow the advice Github give here.
Update
To prevent link rot here are the summarised instructions from the above link on removing secure data from a repo. If you wish, there is also a simpler version by using the BFG Repo-Cleaner package.

In a terminal cd to the local clone of the repo in question.
Run the follow (Be careful! This will overwrite your existing tags.):
git filter-branch --force --index-filter \
'git rm --cached --ignore-unmatch codeception.yml' \
--prune-empty --tag-name-filter cat -- --all

Add the codeception.yml file to your .gitignore and commit.
After checking the state of your repo git push origin --force --all
If you need to remove the sensitive data from your tags you will also need to run git push origin --force --tags
Tell your collaborators to rebase, not merge. Merging will reintroduce the files.
After some time has passed and you're confident that git filter-branch had no unintended side effects, you can force all objects in your local repository to be dereferenced and garbage collected with the following commands (using Git 1.8.5 or newer):
git for-each-ref --format='delete %(refname)' refs/original | git update-ref --stdin

Then
git reflog expire --expire=now --all

Then
git gc --prune=now

Comment: Glad it worked, if you need to remove the file from the repo history completely follow the github link posted. I will updated the answer later with full instructions to prevent link rot.
Answer: You might have already added codeception.yml file to the git index before adding it to .gitignore. That's why it is being tracked by git.
You can use the following command to remove it from git index so that it won't be tracked any more. But keep in mind, this will remove the codeception.yml file from all other locations where you take pull after pushing these changes, except your local copy.
git rm --cached codeception.yml


Copy data of Email in registration to the username not showing in the registration page

Question: I want to copy the value of email to the username, which is not showing in the registration page, but it is showing in the /user/edit page as Display Name, which is randomly generated such that my username is my email, giving more flexibility to the user.
Comment: Are you ok with writing your own module or are you looking for already done solution?
Comment: I am a novice sir. So i dont know to write a module.
Comment: In that case I'm sorry because I won't be able to help you.
Comment: What do you mean by "randomly generated such that my username is my email"? If your username is your email address, that is not random.
To clarify, you want to use the email address as the username?
Comment: @Petrroll sir can you just show me direction, what to do.
Comment: @faerysteel Till now I am using Email Registration module, What this module does is that it give access to login with email and change your username as display name, which is uniquely randomly generated by the module. So, I want that the value of email is copied to display name.
Answer: The Email Registration module will allow for using the email address as the username.
The LoginToboggan module will allow the user to create a username, and allow them to login with either the username OR email address.
Email Registration also provides a hook which will allow a custom module to set the account name to whatever you want it to be.  That does require writing a module, however, it doesn't have to be very complicated.
The only thing you would need to include in your module file is the hook.
Example adapted from http://www.grasmash.com/article/using-your-email-address-your-drupal-username#sthash.uZkOo6j6.dpuf
<code><?php
/*
* Implements hook_email_registration_name().
*/
function grasmash_email_registration_name($edit, $account) {
  return $account->mail;
}
</code>
Comment: But this is not the solution because there are some drawbacks of using Email Registration module.
Comment: Then you need to provide more information in your question, and will probably have to write a more complex module to accomplish it.


Catch event if user have already liked any facebook page

Question: I am using following to code to catch event if user have already liked your page but it's not working. It always go to that user has not liked your page.
window.fbAsyncInit = function() {
                    FB.init({
                        appId      : 'app_id', // App ID
                        channelURL : 'path', // Channel File URL
                        status     : true, // check login status
                        cookie     : true, // enable cookies to allow the server to access the session
                        oauth      : true, // enable OAuth 2.0
                        xfbml      : true  // parse XFBML
                    });
<code>                FB.getLoginStatus(function(response) {
                    console.log(response);
                    if (response.authResponse) {
                        // logged in and connected user, someone you know
                        var user_id = response.authResponse.userID;
                        var page_id = "1457622007810260";
                        var fql_query = "SELECT uid FROM page_fan WHERE page_id = "+ page_id + " and uid= "+ user_id ;
                        var the_query = FB.Data.query(fql_query);
                        alert(fql_query);
                        alert(user_id);
                        the_query.wait(function(rows) {
                            alert(rows);
                            if (rows.length == 1 && rows[0].uid == user_id) {
                                //user likes the page
                                //do your stuff here
                                alert('likes');
                            } else {
                                // user doesn't like our page yet
                                alert('unlikes');
                            }
                        });
                    } else {
                        // no user session available, someone not known, not logged into fb'
                        alert('no');
                    }
                });
            };

            // Load the SDK Asynchronously
            (function(d){
                var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
                js = d.createElement('script'); js.id = id; js.async = true;
                js.src = "//connect.facebook.net/en_US/all.js";
                d.getElementsByTagName('head')[0].appendChild(js);
            }(document));
</code>
and somewhere in html
Answer: The user need to grant the user_like permisison. This requires your application to be submitted to and reviewed by Facebook.com
<code>https://developers.facebook.com/docs/facebook-login/permissions/v2.0
</code>
If you want to get all the fans of a page, you will need the page_management permission I reckon.
Facebook shows how to do this programmacally on:

https://developers.facebook.com/docs/facebook-login/login-flow-for-web/v2.0
Comment: But, facebook did return some page ids i guess that was array of size 20. But what about other pages? which i recently liked?


Solve $\dot{x} + 2x = e^{3t}\cos(4t)$ and use ERF?

Question: MIT ODE class assignment here
http://math.mit.edu/classes/18.03/spr10/pset_04.pdf
talks about solving $\dot{x} + 2x  = e^{3t}\cos(4t)$ and using ERF to do it. I know how to solve this using integrating factors, but what is ERF? The solution is below, but explicit steps are not mentioned.
http://math.mit.edu/classes/18.03/spr10/pset_04_sol.pdf
Answer: It seems to mean exponential response formula. See math.mit.edu/classes/18.03/spr10's LTI operators and exponential signals (subsection 10.2 of Operators and the exponential response formula).
Quote:

The Exponential Response Formula ties together many different parts of this course. Since the most important signals are exponential, and the most important differential operators are LTI operators, this single formula solves most of the ODEs you are likely to face in your future.


Como converter em Java um arquivo PDF para TXT?

Question: Existe alguma forma em java para converter um arquivo de extensão PDF para a extensão TXT?
Comment: O conteudo do PDF pode variar muito, não tem como extrair exatamente algo padronizado, existem muitos documentos PDF que foram gerados de arquivos .doc Deve haver sim, mas não será nada fácil. Isto é apenas uma dica do que você tera pela frente, vou pesquisar e ver se existe alguma lib. Até mais.
Comment: Ja tenho ciencia desse empecilho, mas ajudaria mostrando e exemplificando uma forma e ficaria grato @GuilhermeNascimento
Answer: Você pode tentar utilizar a biblioteca iText, que possui algumas funcionalidades prontas para a extração de texto de arquivos PDF. Uma forma de fazer isso seria:
public void parsePdf(String pdf, String txt) throws IOException {
    PdfReader reader = new PdfReader(pdf);
    PdfReaderContentParser parser = new PdfReaderContentParser(reader);
    PrintWriter out = new PrintWriter(new FileOutputStream(txt));
    TextExtractionStrategy strategy;
    for (int i = 1; i <= reader.getNumberOfPages(); i++) {
        strategy = parser.processContent(i, new SimpleTextExtractionStrategy());
        out.println(strategy.getResultantText());
    }
    out.flush();
    out.close();
    reader.close();
}

Onde o parâmetro pdf é o arquivo PDF que deve ser extraído o texto e o parâmetro txt é o arquivo TXT de destino.
Este trecho de código foi retirado de um exemplo pronto, criado pelo desenvolvedor do iText. Este exemplo, bem como o TXT resultante, podem ser encontrados neste link.
Comment: A biblioteca PDFBox também poderá ajudá-lo


What methods are there to load more ROWS into a View display without reloading the page?

Question: I have a basic View showing 2 node teasers at a time. I want to be able to have a button below it that says load more. Once you click it, it will load the next two. I know that there is the module "views_load_more", but there seems to be a bug with that module that causes duplicates. There is a patch for this issue, but it doesn't solve the problem from what i have tried.
I was wondering what other modules or methods to achieve this same functionality?
I was thinking of continuing to use the views load more module, and just use jquery to detect if there are duplicates and then remove them. But that way seems to be a bit hacky.
Comment: Commenting because it doesn't actually answer the question: I have used views_load_more in a few sites and not had issues with duplicates. If I was going to spend time writing custom code to work around the duplicates problem I would probably spend that time fixing the bug in views load more instead.
Answer: The Views Infinite Scroll module is an alternative solution for ajax pagers in views however I haven't used it so I cannot comment on how well it works.
It also works a little differently to views load more so it may or may not meed your requirements.


A layout with one fixed width column, one fluid one that stretches to fill empty space, and one fluid that is as wide as it's content

Question: I need to make three columns, one of them needs to be fixed width, one needs to be fluid to fill up empty space, and one needs to be fluid, but to have the combined fixed width of its children (they don't have to be inline, I just wrote the code to make my question more clear).
The div that the three columns will sit in, has a variable width, and all the empty extra space has to go to just the one column with an input inside it (that also has to stretch to fill that columns width, but once the column works, that won't be a problem).
Here's my code, the right column has to keep the width of it's three containing boxes:

.container {
    width: 100%;
    display: table;
    vertical-align: top;
}

.col_left {
    width: 100px;
    display: table-cell;
    background: #708A91;
}

.col_mid {
    display: table-cell;
}

.col_mid input {
    width: 100%;
}

.col_right {
    display: table-cell;
    background: #708A91;
}

.col_right .element_with_variable_width {
    padding: 10px
}

.inline_box {
    display: inline-block;
    vertical-align:  top;
    height:19px;
    width: 30px;
    margin: 0 5px;
    background-color: #E066FF;
}

        <input type="text">

Any ideas? Can this be done with CSS alone?
Comment: You should look at `display:flex` in CSS (http://stackoverflow.com/questions/27090585/equal-height-flexbox-columns-in-chrome)
Comment: Oh, forgot to mention it has to run in IE 9 as well. But thanks, didn't know about flex.
Comment: Just to point you in the right direction, you can do this with PHP or Javascript. I can't think of a legacy way of doing this with CSS.
Comment: That's what I thought, I could use this old trick: http://alistapart.com/article/holygrail combined with JS to determine the width of the columns with variable text in them.

Was hoping for a cleaner way :) but thank you!
Comment: Ie9 ? so display : table ... but what is your html and what have you tried so far ? It can be done via CSS only of course ...
Comment: No HTML yet, I'm exploring options. But it would be something like this:

Fixed widh

    This has to take up all existing space in "container"

    this stretches to fit one word text

Comment: Sorry, looks like you look for someone to do your job :) . This is a question that comes back often and this for years. You should find many answers to this ;)
Comment: I don't want code, just an idea, I have not been able to find anything about this, looks like bootstrap might be able to do it, and I will try to figure out how it does it if it works.

Are you sure it's a recurrent question? Tree fluid columns, one expanding to fill the space of the container, two only expanding according to their content?
Comment: I wrote a code idea: https://jsfiddle.net/93mghhkb/ it works, only both columns with no width stretch to fill the empty space, not just the middle one. Can I somehow force the right one to not stretch when the container stretches?
Answer: So the key with display: table; and display: table-cell; is for both left and right columns to have their widths dictated by their content, white-space: nowrap; allows inline columns to not be pushed down by the width: 100%; middle column.
It's a working answer, and display: table; is not evil: http://colintoh.com/blog/display-table-anti-hero

* {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
}

.container {
    width: 100%;
    display: table;
    vertical-align: top;
}

.col_left {
    display: table-cell;
    background: #708A91;
}

.col_mid {
    display: table-cell;
    width: 100%;
}

.col_mid input {
    width: 100%;
}

.col_right {
    display: table-cell;
    background: #708A91;
    white-space: nowrap;
}

.logo {
    display: inline-block;
    vertical-align:  top;
    width: 100px;
    height:19px;
}

.inline_box {
    display: inline-block;
    vertical-align:  top;
    height:19px;
    width: 30px;
    margin: 0 5px;
    background-color: #E066FF;
}

        <input type="text">


Ranking performance measure

Question: I have a system able to produce a ranking of some operations according to their  anomalous score. I have N anomalous operations inside the dataset, which I expect to be in the first N positions (best case).
This score is computed by a formula which has some parameters. According to the parameters configurations obviously the ranking changes.
How can I measure the performance quality of the system? Currently, I am measuring the true positive rate, but I would prefer some measure that shows how much the anomalous operations are concentrated in the first positions. What I mean is that I can have the same TPR but in one case the FNs can be in N+1, ..., N+10 position, right after the Nth position, and another case where the FNs are at the end of the ranking. I definitely prefer the first case.
Answer: What you want is average precision, that you will compute on each element in the dataset, and then you will obtain mean average precision (MAP)
Comment: Thank you, I will try to use it. It seems to be exactly I was looking for!
Instead, what do you think about [DCG](https://en.wikipedia.org/wiki/Information_retrieval#Discounted_cumulative_gain)? Can it be also a good measure if I found a way to define the "relevance" variable?
Comment: Well, it could be, but really for your problem, the standard is MAP.

Ranking performance measure


Como faço ao preencher uma combo eu preencho o Value dela com wpf e c#

Question: Fiz esse código para preencher uma combobox. Funciona perfeitamente, porém eu preciso além do texto a ser apresentado na combo, precisa também carregar uma espécie de Value, como fazemos na web onde temos o Name e o Value. Eu uso WPF. Se eu preencher a combo em design time assim:
<ComboBoxItem Content="Milho" Name="M"/>
            <ComboBoxItem Content="Soja" Name="S"/>
            <ComboBoxItem Content="Feijão" Name="F"/>

Veja que o name funciona como um Value e consigo pegar esse valor no code behind. Esse é code para preencher a combo em runtime:
public void CarregaComboSecagem()
        {
            ListaSecagens lista = new ListaSecagens();
            ObservableCollection<string> listaCtg;

            var prod = lista.listaSecagens();

            listaCtg = new ObservableCollection<string>();

            foreach (var prd in prod)
            {
                listaCtg.Add(prd.Umidade.ToString());
            }

            cbxSecagem.ItemsSource = listaCtg;

        }

Prod é a listaSecagem:
public class ListaSecagens
    {
        private SiloContext contexto = new SiloContext();

        public List<Secagem> listaSecagens()
        {
            return contexto.Secagens.ToList();
        }
    }

Minha entity Secagem
[Table("Secagem")]
    public class Secagem
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int IdSecagem { get; set; }
        public int IdProduto { get; set; }
        public decimal Umidade { get; set; }
        public decimal Desconto { get; set; }
        public decimal Valor_Sec { get; set; }
    }

Meu context
public class SiloContext : DbContext
    {
        public SiloContext()
            : base("SiloConn")
        {
            Database.SetInitializer<SiloContext>(null);
        }
        public DbSet<Produto> Produtos { get; set; }
        public DbSet<Balanca> Balancas { get; set; }
        public DbSet<Secagem> Secagens { get; set; }
    }

Comment: qual o tipo de `prod` ?
Comment: @RovannLinhalis, editei o post e coloquei a classe listaSecagem
Answer: Coloque o source do combo, como a lista de seus objetos, depois você acessa o objeto selecionado com a propriedade SelectedValue. Exemplo:
No seu caso, conforme me explicou no chat, você deve preencher o combo de produtos no evento Loaded da Window. Quando o usuário escolher um item, você deve disparar o evento SelectionChanged do combo de produtos, e carregar o combo de Secagem. Seu código deve estar semelhante a este:
    private void Window1_Loaded(object sender, RoutedEventArgs e)
    {
        comboBoxProduto.ItemsSource = ProdutoDAO.GetProdutos(); //Seu método que retorna a List<Produto>
        comboBoxProduto.DisplayMemberPath = "Nome";
    }

    private void comboBoxProduto_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (comboBoxProduto.SelectedValue != null)
        {
            comboBoxSecagem.ItemsSource = SecagemDAO.GetSecagem(((Produto)comboBoxProduto.SelectedValue).Id);
            comboBoxSecagem.DisplayMemberPath = "Umidade";
        }
        else
            comboBoxSecagem.ItemsSource = null;
    }

Classes de Exemplo
public class Secagem
{
    public int IdSecagem { get; set; }
    public int IdProduto { get; set; }
    public decimal Umidade { get; set; }
    public decimal Desconto { get; set; }
    public decimal Valor_Sec { get; set; }
}

public class SecagemDAO
{
    public static List<Secagem> GetSecagem(int idProduto)
    {
        //codigo de selecionar a lista de acordo com o produto
        //return Context.Select(...Where...) //Exemplo!!!
        return new List<Secagem>();
    }

}

public class Produto
{
    public int Id { get; set; }
    public string Nome { get; set; }

}

public class ProdutoDAO
{
    public static List<Produto> GetProdutos()
    {
        //codigo do Select dos produtos
        //return Context.Select(...Where...) //Exemplo!!!
        return new List<Produto>();
    }
}

Comment: No caso acima, você preencheu a combo manualmente. No meu caso, que vem de um BD, terei que criar uma espécie de Chave/Valor e a chave eu apresento na combo e o valor seria meu "value", certo?
Comment: editado, veja se ajuda
Comment: Alguma coisa que ainda não entendi, deixa eu tentar fazer, mas ainda to meio confuso
Comment: o source do combo, será uma lista de objetos, da sua classe e não uma lista de string, quando você acessa o `SelectedValue` você acessa o objeto que está selecionado, com todos os seus valores. Editei novamente a resposta
Comment: Rodei antes dessa atualização e na combo não veio os valores corretos, tipo, deveria vir: Soja, Milho, Feijão e etc e veio Domain.Entities.Umidade. Me desculpe-me, mas não entendi nada
Comment: faltou essa parte: `cbxSecagem.DisplayMemberPath = "Umidade";`
Comment: Tá dando erro nas vars que vc criou. Se eu retirar, consigo trazer na combo os dados, mas não consigo o value, pois não setei ele.
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/63872/discussion-between-rovann-linhalis-and-pnet).


Creating media_bundle entities programatically

Question: I am still trying to wrap my head around some of the D8 things.  Working with some media bundles like media_audio_bundle and need to write some migration scripts. I have spent couple of days now researching and trying everything but nothing seems to work.
Its like Drupal wall all over again.
This is the closest I came:
<code>$audio = \Drupal::entityTypeManager()
          ->getStorage('media_bundle')
          ->create(array(
            'type' => 'media',
            'bundle' => 'audio',
            'title' => 'Another Audio',
            'field_audio_file' => 11
          ));
</code>
It seems to create some sort of media object but does not save it.
If somebody can help, would be much appreciated.
Answer: <code>use Drupal\media_entity\Entity\Media;

$image_data = file_get_contents("URL OF FILE");
$file_image = file_save_data($image_data, 'public://FILENAME', FILE_EXISTS_REPLACE);
$media_image = Media::create([
  'bundle' => 'image',(YOUR BUNDLE)
  'name' => "FILENAME",
  'field_image' => [
    'target_id' => $file_image->id(),
  ],
]);
$media_image->save();
</code>
Try this one, maybe this will help.
Answer:
You should invoke save method to save the entity to database.

<code>$audio->save();
</code>
Comment: For some reason this would throw an error for me.
Answer: Not sure if this is the best way, but it seems to work.
<code>$media =  Drupal\media_entity\Entity\Media::create([
 'bundle'        => 'audio',
 'name'       => 'demo audio',
 'field_audio' => [
   [
      'target_id' => $file->id(),
   ]
 ],
]);
$media->save();
</code>


Is $B^s_{p,p} = W^{s,p}$?

Question: In Adams & Fournier's book "Sobolev Spaces" page 255, there are assertions:
$$ W^{s,p} = F^{s}_{p,2}
\\
B^s_{p,p} = F^s_{p,p}$$
Note: Here $s>0$, $1\leq p<\infty$, and the fractional order Sobolev spaces are defined as complex interpolation spaces $W^{s,p} = [L^p , W^{m,p} ] _{s/m}$ where $m$ is the smallest integer greater than $s$.
AFAIK, the above definition is equivalent to the following definition (at least for $0<s<1$), employing Gagliardo seminorms:
$f \in W^{s,p}$ iff $f \in W^{\left \lfloor{s}\right \rfloor ,p}$ and $[D^\alpha f] := (\int \frac{|D^{\alpha}f(x)-D^{\alpha}f(y)|^p } {|x-y|^{(s-\left \lfloor{s}\right \rfloor)p + n}} dxdy)^{1/p} < \infty$ for all $|\alpha|=\left \lfloor{s}\right \rfloor$.
The Triebel-Lizorkin spaces and the Besov spaces are defined by Paley-Littlewood decompositions.
In Triebel's book "Interpolation theory, function spaces, differential operators(1978)", page 169,
the fractional order Sobolev spaces are defined as
$W^{s,p} = B^s_{p,p}$ for $s>0$ non-integer.
Therefore, the two monographs are coherent only when $p=2$. Could someone explain about this situation?
My background: I have little experience and knowledge of function spaces. To get some knowledge, I am starting to have a brief overview of the famous monographs. However, the problem described above makes me very confused.
Any bits of help are welcome. Thank you!!
Answer: The notations in the two books are different.
With the definition using the Gagliardo seminorms, these are the real interpolation spaces (which are now more usually denoted by $W^{s,p}$ I think) when $s$ is not an integer
$$
W^{s,p} = B^s_{p,p} = F^s_{p,p} = (L^p,W^{n,p})_{s/n,p}
$$
while the complex interpolation gives you
$$
H^{s,p} = F^s_{p,2} = [L^p,W^{n,p}]_{s/n}
$$
with the seminorm $\left|f\right|_{H^{s,p}} = \|\Delta^{s/2}f\|_{L^p}$. The notation is quite misleading since when $n$ is an integer, then the classical $W^{n,p}$ is $H^{n,p}$ and not $B^n_{p,p}$.
By the general embeddings theorems between Besov and Triebel-Lizorkin spaces, you get
$$
W^{s,p} ⊂ H^{s,p}
$$
when $p≤ 2$ and the reverse inclusion when $p\geq 2$. Of course, when $p=2$, then $H^{s,2} = W^{s,2} = H^s$.
Comment: Thanks for your elaborate answer. I think I got the point: I should take care of the differences between Sobolev-Slodobeckii space (Gagliardo seminorm) and the Bessel potential space (using the Fourier approach), which amounts to real interpolation spaces versus complex interpolation spaces of the classical Sobolev spaces.

1. Did I correctly rephrase your answer?
2. Could I ask for some references for the equivalences of spaces quoted in your answer?

Thank you!
Comment: The introduction of the book of Triebel *Theory of function spaces II* is good to explain the relation between the spaces. And you will also find the complex interpolation of classical Sobolev spaces there.
Comment: You can find the real interpolation of Sobolev spaces in the book of Lunardi, *Interpolation Theory*, section 1.1.
Comment: I think your complex interpolation is incorrect. It should be $[L^p,W^{n,p}]_{s/n}$. There is only one index rather than two.
Comment: Yes, of course, corrected, thanks for the comment.

Is $B^s_{p,p} = W^{s,p}$?


QPlainTextEdit ignores most of the text block formats

Question: I wanted to increase spacing between paragraphs (text blocks) in QPlainTextEdit, to no avail. After experimenting I found that though some format properties (e.g., background color) take effect, others (e.g., margins) are ignored.
I found this bug report, but it mentions only QTextBlockFormat::lineHeight(). In my case, almost all methods of QTextBlockFormat::* are ignored. A minimal example:
#include <QtWidgets>

int main(int argc, char *argv[]) {
    QApplication a(argc, argv);

    QPlainTextEdit te;
    te.setPlainText("block1\nblock2\nblock3");

    QTextCursor cursor = te.textCursor();
    cursor.select(QTextCursor::Document);
    QTextBlockFormat fmt;
    fmt.setBackground(QColor(Qt::yellow));
    fmt.setBottomMargin(600);
    fmt.setIndent(20);
    fmt.setTopMargin(600);
    fmt.setLeftMargin(40);
    cursor.setBlockFormat(fmt);
    te.show();
    return a.exec();
}

Except fmt.setBackground(QColor(Qt::yellow)), others are all ignored. Using Qt 5.10.
Answer: Don't use QPlainTextEdit for intensive formatting over text. Use its cousin, QTextEdit instead.
Using your code and changing it from QPlainTextEdit to QTextEdit resolved the issue.
FYI, this was also mentioned in the Bug Report you linked. Maybe you missed it or forgot to mention it in your question?

Replacing QPlainTextEdit with QTextEdit shows the expected result.

QTextEdit te;               //  note the change in type
te.setPlainText("block1\nblock2\nblock3");

QTextCursor cursor = te.textCursor();
cursor.select(QTextCursor::Document);
QTextBlockFormat fmt;
fmt.setBackground(QColor(Qt::yellow));
fmt.setBottomMargin(6);     //  let's not overexaggerate anything
fmt.setIndent(1);
fmt.setTopMargin(12);
fmt.setLeftMargin(1);
cursor.setBlockFormat(fmt);

Here's the result of using QPlainTextEdit (on a MacOS).

And here's the result of using QTextEdit (on a MacOS).

Note that none of the member functions need to be modified, so that's a plus. Transitioning from QPlainTextEdit to QTextEdit shouldn't be much of a pain.
Further Reading: This other SO post kinda helped. Would also be good to read if you're planning on using more Qt Text Classes.
Comment: Yes, I know that it works for QTextEdit :) For certain reasons, however, I am confined to deal with QPlainTextEdit. And so it looks not much as a bug, but as documented feature of a class (QPlainTextEdit) which in fact is merely not implemented....


Using differentials to estimate max error,

Question: Question:
The radius of a circular disk is given as 24 cm with a maximum error in measurement of 0.2 cm. Use differentials to estimate the maximum error in the calculated area of the disk.
My attempt:
Look at the linear approximation of $A(r) = \pi r^2$ near $r=24$.
We have that
$$A(r) \approx A(24) + A'(24)(x-24)$$
and maximizing the error in measurement of the radius gives
$$A(r) \approx A(24) + A'(24)(24.2-24)$$
and we read off the differential term
$$A'(24)(24.2-24)$$
which equals $9.6 \pi$.
I'm just double-checking my solutions before showing it to my calculus students tomorrow.
Thanks,
Comment: This is correct. I would tell them why you plug in $24.2$ instead of $23.8$. You have the interval $I = (24-.02, 24+.02)$ and by taylor's approximation we have $f(x) - f(24) = f'(24)(x-24) + \epsilon(x)$ where $x \in I$. Hence, the error term is approximated by $g(x) = f'(24)(x-24)$ which you want to maximize on $I$. Okay so now we just plug in $24.2$ since this function in monotonically increasing. Technically I think it would be better if you also got the upper bound on $\epsilon(x)$ and so you want to maximize $g_{\epsilon}(x) = f'(24)(x-24) + \epsilon(x)$.
Answer: Being a physicist, even if your solution is very correct, instead of using linear approximation, I suggest you use differentials (as written in the title of your post).
Let us start with a modified version of your example
$$A=k\, r^n\implies \log(A)=\log(k)+n\log(r)$$ Differentiate $$\frac{dA}{A}=n\frac{dr}{r}\implies\frac{|\Delta A|}{A}=n\frac{|\Delta r|}{r}\implies|{\Delta A}|=n k r^{n-1} {|\Delta r|}$$


malloc problem?

Question: Hello I use malloc() to generate a buffer like this where buffer is a char*
buffer = (char*)malloc(chunksize+1);
  for (k = 0; k < chunksize; k++) {
    buffer[k] = (char) (j+k);
  }

however, in debugger i can see the buffer[3] for example is the char i wrote in, but the buffer buffer is empty(a lot of spaces). But the second time I write stuff in the buffer after free(buffer), it shows the the content I wrote the first time, and overwrite it. Can anyone tell me why? Thank you!!
Comment: What's `j`? What's `chunksize`? And did you really say "write stuff in the buffer *after* `free(buffer)`"?
Comment: don't do the two casts. they are redundant, at least, and the first one may even hide problems like forgetting to include the prototype.
Comment: sorry my bad. It is in a loop, free the buffer in the end of the loop but i do malloc every time before writing like the code shown
Comment: Shouldn't that be `malloc((chunksize+1)*sizeof(char))`? (I don't know C, but that just looks wrong.)
Comment: sizeof(char) is always one, so drop the pointless part of multiplying by 1.
Comment: @JeffreyLWhitledge: `sizeof(char)` is guaranteed to be `1`, and therefore multiplying with it is redundant. It actually looks wrong when it *is* there, rather than when it isn't.
Comment: @Mk12 - I can tell that I would not enjoy C very much! The compiler—with even the most basic of optimizations—will replace `sizeof(char)` with the constant 1, then it will remove the multiplication by 1. So the code will have no run-time performance impact. But the *logic* of what you are doing requires the multiplication. Omitting it would make the code more difficult to maintain, because it places hidden assumptions in the details of the code. For example, if you decide to change the datatype later, then you have to change the malloc size calculation. Thus, omitting it looks wrong (to me).
Comment: @JeffreyLWhitledge: Of course, I'm sure there are many C coders that prefer having it there for consistency with other types. I suppose I should have said IMO above—but really, (to me), allocating *bytes* is a special case and using `sizeof(char)` implies the lack of understanding that it is always `1`. As long as you're consistent, there are more important things to worry about.
Comment: @Mk12 - Of course, this is a matter of taste. I often include things that are unnecessary (e.g., decorating C# methods with "private"), just because I like things to be explicit and obviously correct. It is interesting that your taste is to make the null character explicit in your comment to the accepted answer. I agree with you there!
Answer: Generally speaking, malloc implementations work by getting a large chunk of memory from the OS, then sub-allocating bits of it when you ask for buffers. This is because getting memory from the OS is relatively slow.
As a security measure, your OS will give malloc blank memory (full of 0 or some other repeating value). You wouldn't want one process to be able to read the leavings of an unrelated process.
However, malloc has no such problems, because it only serves from that chunk to one process. It doesn't matter if you can see your own leavings (at least not from a security POV).
So what's happened is that you've malloced a buffer, and seen it initially blank. Then you've freed it and asked for "another" buffer, and malloc happens to have handed you the same memory again, this time containing the values you left in it.
This "coincidence" of getting the same memory twice isn't very unlikely, since there's a good reason for malloc to re-use recently-used memory where possible - it's more likely to be in cache.
You might think this doesn't matter to you, because normally you wouldn't read from newly-allocated memory. But it matters to malloc, because typically malloc keeps its own house-keeping data adjacent to the buffer. It also may matter if there's a cost associated with expelling memory from the cache - if you can be "tricked" into re-using the same memory over and over again, then this happens less.
Comment: Thank you. but why the chars are not written when I check the buffer from the debugger? I intent to write the buffer to a file right after. And when I read the content from the file, I get a lot of "32" which is space. but second time, it is acting normal.
Comment: @user512853: Hmm, I may have misunderstood the question. I thought you meant that you saw blank memory while your loop was executing, overwriting with your values (`j`, `j+1`, etc). Actual space characters (i.e. ASCII 32), as opposed to unprintable characters shown as blanks in the debug memory view, doesn't sound likely for uninitialized memory. When you write to file, are you definitely writing the same chunksize that you've filled in, and starting from the same address? Check what memory looks like just before you call `fwrite`.
Comment: I generate the buffer, then write the buffer to the file, free the buffer, malloc it again and repeat the previous steps. Later on, I read the file to a buffer and compare if the content is the same as I wrote before, one the first chunk is full of 32, other chunks are correct.
Comment: when I check the memory, the debugger is acting weired. I can see buffer[3] for example is the char I wrote in, but buffer is full of spaces
Answer: One problem might be that you try to print your char buffer with printf or equivalent? You are missing to assign
buffer[chunksize] = 0;

So your buffer is not well terminated. It may have anything behind that, e.g '\r'.
If on the other hand buffer doesn't represent a string for you, better use a different base type, probably unsigned char.
Comment: That should be `buffer[chunksize] = '\0';`. Although they may have the same bitwise representation, your intention is clearer when you use the appropriate literal.
Comment: This is nothing but a matter of taste. `'\0'` is nothing than another name for `0`. I am more in favor of using the same `0` for all initializations.
Comment: Empty string: `buffer[0] = '\0';`
Answer: Your code is correct. The problem could be in some part of the code that you haven't shown if you are concerned that you overwrite some bad memory. For example, if buffer is a pointer to non-char array, in which case pointer arithmetic that you use will result in bad memory access (corruption). You can use the following program as a reference:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main ()
{
  const size_t chunksize = 15;
  size_t k;
  char *buffer;

  buffer = malloc (chunksize + 1);
  memset (buffer, 0, chunksize + 1);

  for (k = 0; k < chunksize; ++k)
    {
      buffer[k] = '0' + (char)k + 49;
    }

  for (k = 0; k < chunksize; ++k)
    {
      printf ("%lu = %c\n", k, buffer[k]);
    }

  free (buffer);

  return 0;
}

Output:
0 = a
1 = b
2 = c
3 = d
4 = e
5 = f
6 = g
7 = h
8 = i
9 = j
10 = k
11 = l
12 = m
13 = n
14 = o

malloc problem?


Probability of Two Independent Events, Unknown Distribution

Question: I'm trying to deepen my understand of probability, unions and intersections.
How would you go about finding the probability of x and y ( P(x U y) ??) for a collection of n objects (2 < n < 40) of unique heights, arranged along a line sequentially. Where x is the number of objects visible if you were to look from one direction along the line, and y is the number visible from the opposite direction?
It's a pretty good brain teaser I'm trying to wrap my head around. I wrote some python to help my generate some empirical evidence. I can easily brute force check the number of permutations up to n = 10, but above that permutations are n factorial, which gets large, quickly. So I'm trying to determine the probabilities for X and Y, or even the distinct counts themselves.
import itertools
from collections import Counter
import math

f = math.factorial

def answer(x,y,n):
    n = float(n)
    ans = []
    h = []
    counts1 = []
    counts2 = []
    perms = []

    for i in xrange(int(n)):
        h.append(i+1)

    for i in itertools.permutations(h,len(h)):
        count1 = 1
        count2 = 1
        perms.append(i)
        p1 = i[0]
        p2 = i[-1]

        for j1,k1 in enumerate(i):
            if i[j1] > p1:
                p1 = i[j1]
                count1 += 1
        counts1.append(count1)

        rev = [z for z in reversed(i)]

        for j2,k2 in enumerate(rev):
            if rev[j2] > p2:
                p2 = rev[j2]
                count2 += 1
        counts2.append(count2)

#         print count1, i, count2

#     print zip(counts1, counts2)

    c1 = Counter(counts1); print c1, "\n"
    cz = zip(counts1, counts2)
    czip = Counter(cz); print czip, "\n"
    combs = [i for i in itertools.combinations_with_replacement(h,2)]

    print "A \tC(A) \tP(A)"
    for i in combs:
        print i, "\t", czip[i], "\t", czip[i]/float(f(n))

    answer1(x,y,n, c1)

    ans = czip[(x,y)]
#     print ans

    return ans, float(ans) / f(n)

def answer1(x,y,n,c1):
    print "\n##### just calculations #####"

    f = math.factorial
    fn = float(f(n))
    nn = int(fn/n)

    print "\n", "n =", n, "\n","n! =", math.factorial(n), "\n", "n!/n =", nn, "\n"

    px = c1[x] / fn
    print "P(X), x =", x,"\t", c1[x],"\t", px, "\t", px * nn

    py = c1[y] / fn
    print "P(Y), y =", y,"\t", c1[y],"\t", py, "\t", py * nn

    c1xORy = c1[x] + c1[y]
    pxORy = c1xORy / fn
    print "P(X or Y) \t", c1xORy, "\t", pxORy, "\t", pxORy * nn

    c1xANDy = abs(c1[x]-c1[y])
    pxANDy =  c1xANDy / fn # px + py - pxORy
    print "P(X and Y) \t",c1xANDy, "\t", pxANDy, "\t", pxANDy * nn, "\n"

Insight much appreciated.
Comment: If $X$ is the number of visible objects, then $X$ is a random variable rather than event (and $Y$ as well). There is no meaningful 'union' of random variables, so you may want to replace $P(X\cup Y)$ by something else.
Comment: Note that these random variables (number visible from right and number from the left) are *not* independent, despite that characterization in the title. They tend to be inversely associated.
Comment: Also, it's going to depend on both how high the eye is above the line and how far apart the objects are, no?  I don't read python, so I can't figure out what you are assuming about that.
Answer: To make this question definite and answerable, I interpret it as placing $n$ distinct positive numbers $h_1 \lt h_2 \lt \cdots \lt h_n$ independently and randomly on the Real line at locations $x_1, x_2, \ldots, x_n$.  I assume the (common) distribution of these random locations is continuous so that there is zero chance of collision.  Finally, the number $h_s$ is "visible" from the left provided all the numbers at locations less than $x_s$ are less than $h_s$, with a similar definition of visibility from the right.

The figure shows four random configurations of heights $(1, 2, \ldots, 15)$. Those visible from the right are shown in red and those visible from the left in blue. One is always visible from the left and the right; it is shown in black.
Analysis
Visibility is determined by the sequence in which the heights are encountered from left to right. All sequences are equally likely (regardless of the actual distribution used to place the heights).  The chance there are $t$ visible from the left depends on the location of the largest height, so suppose there are $s-1$ heights to its left (that is, the largest height is located at position $s$ counted from the left).  Call this chance $e(t, s)$.  We count the maximum height as visible and recursively evaluate $e(t,s)$ in terms of the remaining $s-1$ heights to the left of the maximum,
$$e(t,s) = \sum_{i=1}^{s-1} \Pr(t-1\text{ are visible left of } i)\Pr(\text{max height is at }i) \\ = \frac{1}{s-1}\sum_{i=1}^{s-1} e(t-1,i),\, s \gt 1.$$
For $s=1$ it is obvious that $e(1,1)=1$ and $e(t,1)=0$ for $t\ne 1$.
Visibility from both sides can be computed by breaking the configurations into the number visible from the left plus the number visible from the right: they must sum to $t+1$ (because the maximum height is uniquely visible from both sides).  This has to be averaged over all the equally likely locations of the maximum.  Letting the chance of $t$ heights being visible out of $n$ heights be $p(t,n)$, we conclude
$$p(t,n) = \frac{1}{n}\sum_{s=1}^n \sum_{i=1}^{t+1}e(i,s) e(t+1-i, n+1-s).$$
(This is an example of computing the distribution of a sum of random variables based on their joint distribution.)
The overall computational effort is $O(s^2)$ to find the distribution of $e$ for any given $s$ and therefore $O(n^3)$ to find the distribution of $p$ for a given $n$.  This is feasible, taking a few seconds for $n$ up to several hundred or so.

Implementation
The recursion can be implemented directly in many languages.  For those that do not support memoization, it's a good idea to cache the values of $e(t,s)$ as they are computed (effectively making it into a dynamic program).  Here is an R example.
e <- function(t, s) {
  if (is.na(e.cache[t+1, s+1])) {
    e.cache[t+1, s+1] <<- mean(sapply(1:(s-1), function(i) e(t-1,i)))
  }
  return (e.cache[t+1, s+1])
}

p <- function(t, n) {
  mean(sapply(1:n, function(s) {
    sum(sapply(1:(t+1), function(i) {
      e(i,s) * e(t+1-i, 1+n-s)
    }))
  }))
}

To use it, create a cache for $e$ and compute $p$:
e.cache <- matrix(NA, n+2, n+2)
e.cache[1:2, ] <- e.cache[, 1:2] <- 0; e.cache[2, 2] <- 1
p.n <- sapply(1:n, function(t) p(t,n))

Here is a partial plot of the distribution stored in p.n:
Comment: This is very helpful, thank you @whuber. What are we calculating in p.n? Is it the number visible, given t_x AND t_y (the intersection of t_x and t_y)?
Comment: `p.n` is an array where `p.n[t]` is the probability that exactly $t$ of the heights will be visible from the ends of the line when there are $n$ heights. ("Intersection" makes no sense here: we are describing a *random variable,* not a particular event.)


How to delete an array of pointers to generic type objects

Question: My class has a generic array of pointers member named A:
T** A

Currently, i delete the array in the destructor in the following way:
~MyQuickInitArray(){
    delete [] A;
};

Will this cause a memory leak? if so, should i iterate through the array and call delete on each object?
On a side note -  Do I need to call delete [] B if B is an array of integers or does the destructor handles it already?
EDIT:
This is how the allocation occurs:
MyQuickInitArray(int size)
{
    if(size <= 0)
    {
        throw new std::exception;
    }

    _size = size;
    _counter = 0;
    A = new T*[size];
    B = new int[size];
    C = new int[size];
}
    MyQuickInitArray(const MyQuickInitArray& myQuickInitArray)
    {
        _size = myQuickInitArray._size;
        _counter = myQuickInitArray._counter;
        A = new T*[_size];

        for(int i = 0; i<_size ;i++)
        {
            if(myQuickInitArray.A[i] != NULL)
            {
                A[i] = new T(*myQuickInitArray.A[i]);
            }
        }

        B = myQuickInitArray.B;
        C = myQuickInitArray.C;
    }

Comment: Unless you show allocation code how can one say if deallocation code is correct or not?
Comment: @user1929959 A is not a pointer to an array of pointers
Comment: @AlokSave please view my edit
Comment: whoa, why this `throw new std::exception;`?? Throw by value catch by reference(possibly const).
Comment: @AlokSave can you elaborate what is wrong with this?
Comment: Because you dynamically allocate a object being thrown, there can be multiple things that can go wrong with that. Do a little bit of research it should help you understand better. If you still have doubts ask a specific question here. In short the rule as i stated it throw by value catch by reference(possibly const).
Answer:
Will this cause a memory leak?

You can surely count on it if A is an array of pointers. You need loop through the array and delete the pointers yourself.
~MyQuickInitArray {
    for (int i =_size; i--;) {
        delete A[i];
    }
    delete [] A;
}

Do I need to call delete [] B if B is an array of integers or does the destructor handle it?

Yes, always delete that which is allocated with new. You can do this inside your class's destructor.
Comment: You have used `delete` in your program. This is incorrect. You should use an appropriate smart pointer.
Comment: Firstly it's not incorrect and secondly by your wording it follows that the OP deserves a downvote as well.
Answer:
Will this cause a memory leak?

Yes, calling delete[] on the array of pointers without deleting items pointed to by individual elements will cause a memory leak, because "built-in" pointers of C++ do not have ownership semantic. Consider using "smart" pointers, e.g. unique_ptr<T> instead of "plain" ones to avoid calling destructors in a loop.

Do I need to call delete [] B if B is an array of integers

You need to call delete[] on everything that you allocated with new[], regardless of the element type of the array.
Comment: You should place a bit more emphasis on the use of `unique_ptr`.


Creating followups to Commerce Orders for each Line Item

Question: I had asked a question in another thread, and thought it might be helpful to create its own thread just in case it could be helpful to any other developers out there:
"I am trying to create a rule which follows up on existing orders of specific products. Each product has a different time interval for "follow up reminder", and my rule should trigger an email to be sent to a customer at a date which is calculated Order Creation Date + Follow Up Interval.
ie Order Creation + Value provided from Products in the order"
Answer: I wanted to share how I solved this problem: I created a rule which is dependent on an Order's Status being "Completed". This rule runs a custom PHP script which loads the Completed order Entity, retrieves each Line item and checks for its field called "Follow-up", which gives a time value in weeks
Comment: If that field isn't empty, it runs some code to convert the time into seconds, choose a date value based on the order date + the followup time, and inserts a row into a database for EACH line item which requires a followup service. In order to send out mail for each particular followup, I created a cronjob using crontab directly on the server hosting the project. This simply runs each morning, checks the database to see if any of the rows have a date which matches "today", and subsequently retrieves the relevant information and sends the customer the appropriate followup notice!
Comment: If anyone wants some more info, snippets, etc, I would be happy to share any part of this code! It is somewhat lengthy, so I didn't want to paste it all.


Yellow goo on ISP's WiFi equipment?

Question: I am seeing a yellow like goo in my ISP's outdoor cabinets for my WiMax network.
The cat5 runs up the building to a BSR and then to the antennas. Am I losing power and signal quality from this, and what causes this goo?
Comment: Welcome to Server Fault. What are the details of the equipment you're using? Also, I don't think anyone will be able to identify a mysterious yellow goo without at least being able to see it. Do you have any pictures you can share?
Comment: Why would you not just report this to your ISP ?
Comment: lain: Why take the most direct and sensible route when you can post your question to the internet instead?
Answer: This is kinda funny, but it's probably the result of water causing chemical run off from treated paper or wood used in cheap cabinets and air conditioners and dehumidifers.  Really.  The best online reference I could Google real quick is the review linked here.

The evaporator is a treated paper filter. The chemical used to treat
  the paper comes off in the continuously circulating water in the form
  of an accumulating yellow goo. I, daily, cleaned the water "trickling"
  tray as the drip-orifices would clog. Over 6 months the tubes to and
  from the pump clogged with the goo. It's now just a low-noise fan.

Yellow goo on ISP's WiFi equipment?


Puppet or Chef to configure webapplication

Question: I'm looking for a deployment tool for java based webapps deployment to QA/preprod enviroments.
Application is typical webapp, compiled to war/ear with .properties file. During deployment (Jboss,tomcat or webshpere) some of properties inside war/ear needs to be configured with different names (like different database host/ports/schemas);
Looked through google for something what could help. Find out that Puppet/Chef is used actively in opensource, but couldn't find any info about possibility to use it as a "war/ear" deployment tool, or I'm totally mistaken.
Answer: Puppet & Chef aren't really deployment tools.   You could certainly juryrig something, but they're more config management.   The popular tool these days for what you're doing is called "fabric".  Although others like func or capistrano would work as well.


downgrade php from 5.3.5 to 5.3.2

Question: I have PHP 5.3.5 running on my dev server. I need to downgrade it to php PHP 5.3.2 to verify some issues. Is there a tutorial to do that .
dev server OS : Cent OS
Comment: What version of CentOS are you running? Did you compile php 5.3.5 yourself or did you install a package?
Comment: Please edit your post to append the release version (`cat /etc/issue`) and the repo list (`yum repolist`)?
Answer: The PHP module is only a simple shared lib. You can compile it on your own. Here is explained how to do it: http://www.web-tech-india.com/articles/php/compiling_php_apache/
Answer: You might want to use phpfarm to install the second php version on that machine.

downgrade php from 5.3.5 to 5.3.2


Cannot Forward IP and portnumber to another IP address

Question: I am trying to forward the packets to another internal IP address in AWS. (Linux).
My scenario is Gateway(EC2)(126.96.36.199) and two internal IP address (10.0.0.5) and (10.0.0.6).
The packet coming to to 10.0.0.5 on 10009 from 18.104.22.168 (all) to be forwarded to 10.0.0.6 on 10010 port number.

iptables -t nat -A PREROUTING -p tcp -s 22.214.171.124/32 --dport 10009 -j DNAT --to-destination 10.0.0.6:10010

I tried pre-routing but seems not to be working
Answer: In order for this to work, you need to either:

Configure routing in 10.0.0.6 so that packets leaving from port 10010 are forwarded to 10.0.0.5.

Add a masquerade rule at 10.0.0.5, which replaces packet source address with 10.0.0.5. An example would be iptables -t nat -A POSTROUTING --dport 10009 -j MASQUERADE

In both cases you need to make sure IP forwarding is enabled, that is cat /proc/sys/net/ipv4/ip_forward shows 1.


How to generate multiple unrepeated random variables with a fixed non-uniform distribution?

Question: So for a given discrete distribution, say (0.2, 0.4, 0.4), it would be easy to generate one random number that follow this distribution.
However, what about to generate multiple unrepeated random numbers from it?
e.g. from distribution (p1 = 0.2, p2 = 0.4, p3 = 0.4), if I generate
(1,2) with p12 = 0.2,
(2,3) with p23 = 0.6,
(1,3) with p13 = 0.2.
I'm able to have the marginal distribution of
p1 = (p12 + p13)/2 = 0.2,
p2 = (p23 + p12)/2 = 0.4,
p3 = (p13 + p23)/2 = 0.4.
which is same as the given distribution.
Any idea to build a generator to accomplish this in terms of a general distribution? Thanks:)
Answer: If you look at the problem as a set of linear equations, you will be able to express it using a matrix equation. For instance:
|1/2 1/2  0 |   |p12|     |p1|
|1/2  0  1/2| * |p13|  =  |p2|
| 0  1/2 1/2|   |p23|     |p3|

Now you can invert the matrix to get:
|p12|   | 1  1 -1|   |p1|
|p13| = | 1 -1  1| * |p2|
|p23|   |-1  1  1|   |p3|

In your example this will produce:
|p12|   | 1  1 -1|   |0.2|   |0.2|
|p13| = | 1 -1  1| * |0.4| = |0.2|
|p23|   |-1  1  1|   |0.4|   |0.6|

So, p12 = p13 = 0.2 and p23 = 0.6.
Comment: Thanks! But what if we have n variables and we are choosing an group of m variables? For sure that we may solve it by linear equations. However if n and m are relative big, then it may not efficient to do this. I am wondering if there is an random generator can generate these groups with given marginal distribution, am I clear? Thanks
Comment: As you stated the problem it is equivalent to solving a linear equation system. So solving it is the same as solving the system. Note however that "my" solution is general in the sense that it works the same for the general case where `(p12 + p13 + ... + p1n)/(n-1) = p1`, etc.
Comment: Thanks! so I understand to choose the group of m variables from n variables, we can try to solve the linear systems to know exactly probabilities of each group and then generate it from some generating method. e.g. In my example, once I know p12 p13 and p23, I'm able to generate 12, 13 or 23 with this probabilities.
Comment: (Cont.) While I don't know if there is a way to generate 12, 13 or 23 without knowing their exact probabilities. I tried to generate them in turns, like to produce the first variable by its marginal distribution and then generate the next one by distribution conditional on the first variables, but it doesn't work since it gives anl overall biased result...
Comment: @XiHe The method I depicted in my answer addresses the question you posted and is a little bit more general (see my comment above.) If your problem is different or harder, you should edit the question and rephrase it.


Componente HTML para seleção de múltiplos itens

Question: Estou precisando saber o nome deste componente e a lógica deste componente em Javascript. Caso vocês possam indicar algum com 'drag n drop', seria melhor ainda.

Os texto em  PRETO são os componentes e os CINZAS são as explicações (transcritas abaixo).

Items Disponiveis para Ativar
Setas para Transição dos Items
Items Ativos
Comment: Não sei se existe um componente pronto com essa funcionalidade, me parece mais um padrão que usa vários componentes para se atingir a um objetivo (selecionar um subconjunto de itens de um conjunto). De todo modo, sugiro dar uma olhada [nesse exemplo no jQuery UI](https://jqueryui.com/sortable/#connect-lists) para uma forma de fazer isso usando *drag-and-drop* (não é uma solução completa, mas é um bom ponto de partida).
Comment: Como eu tinha falado em relação a este componente, não é necessário que o mesmo seja **'Drag n Drop'**, mas que utilize as setas para separar o conteúdo disponível do conteúdo requerido, como é feito em muitas interfaces de painel de controle
Answer: Não conheço um componente pronto que faça isso - seja em HTML5 ou usando alguma biblioteca ou framework. A lógica, no entanto, é bastante simples:

À esquerda e à direita você tem componentes que permitem seleção múltipla (ex.: um select com atributo multiple, ou algo mais complexo);
Ao clicar no botão com a seta pra direita, pega-se todos os elementos selecionados na lista da esquerda e os transfere pra lista da direita;
Idem pra seta pra esquerda, apenas invertendo as listas.

Aqui está um exemplo simples, usando select multiple (semelhante ao usado no Django):

function mover(fonte, destino) {
  var selecionados = fonte.querySelectorAll("option:checked");
  for ( var i = 0 ; i < selecionados.length ; i++ ) {
      fonte.removeChild(selecionados[i]);
      destino.appendChild(selecionados[i]);
  }
}

document.querySelector("button.dir").onclick = function() {
    mover(document.querySelector("select.esq"),
          document.querySelector("select.dir"));
};

document.querySelector("button.esq").onclick = function() {
    mover(document.querySelector("select.dir"),
          document.querySelector("select.esq"));
};

 <select multiple class="esq">
  <option>Item A</option>
  <option>Item B</option>
  <option>Item C</option>
  <option>Item D</option>
  <option>Item E</option>
 </select>

  <button class="dir">▶</button>
  <button class="esq">◀</button>

 <select multiple class="dir"></select>

Então é só adaptar para ficar mais parecido com o que você quer. Nesse segundo exemplo, eu substituí o select multiple por uma lista em que cada item possui um checkbox para marcar a seleção, e usei a funcionalidade de drag-and-drop do jQuery UI para que os itens possam ser movidos também dessa forma:

function mover(fonte, destino) {
  var selecionados = fonte.querySelectorAll("li input:checked");
  for ( var i = 0 ; i < selecionados.length ; i++ ) {
      var li = selecionados[i].parentNode.parentNode;
      fonte.removeChild(li);
      destino.appendChild(li);
      selecionados[i].checked = false;
  }
}

document.querySelector("button.dir").onclick = function() {
    mover(document.querySelector("ul.esq"),
          document.querySelector("ul.dir"));
};

document.querySelector("button.esq").onclick = function() {
    mover(document.querySelector("ul.dir"),
          document.querySelector("ul.esq"));
};

// Drag-and-drop
$( function() {
    $( "#sortable1, #sortable2" ).sortable({
      connectWith: ".connectedSortable"
    }).disableSelection();
} );

<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">

<input type="checkbox"> Item A

<input type="checkbox"> Item B

<input type="checkbox"> Item C

<input type="checkbox"> Item D

<input type="checkbox"> Item E

  <button class="dir">▶</button>
  <button class="esq">◀</button>

Comment: simplesmente perfeito, era isso que eu queria, para implementar no meu sistema, muito obrigado @mgibsonbr
Answer: Fala Thales, tudo bem?
Eu não sei exatamente o nome desse 'drag n drop', mas dei uma pesquisada e achei um tutorial que te explica como fazer. ;)
Doc:
http://www.daviferreira.com/posts/interface-drag-and-drop-com-jquery-atualizado
Demo:
http://www.daviferreira.com/blog/exemplos/draganddrop/novo.html
Outros exemplos de drag n drop
http://codepen.io/search/pens/?limit=all&page=2&q=drag+n+drop


Web worker as type module fails to load module script

Question: I have the worker helper in react called workerBuilder.js:
export function getWorker(worker) {
  const code = worker.toString();
  const blob = new Blob([`(${code})()`]);
  return new Worker(URL.createObjectURL(blob), { type: 'module' });
}

I then have this fileUploadWorker.js:
import { uploadFile } from 'utilities/storage.utils';
import { STORAGE_BUCKET_ENUM } from 'models/application/enums/ImageEnums';

export default () => {
  self.onmessage = async (message) => {
    const result = await uploadFile(message.data.file, STORAGE_BUCKET_ENUM.ATTACHMENTS, message.data.filePath);
    if (!result) {
      postMessage('Could not upload');
      return;
    }

    postMessage('File uploaded');
  };
};

Now when I try to use it in another function, like this:
const instance = getWorker(fileUploadWorker);

instance.postMessage({ file, filePath });

I see this error in console:
Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "". Strict MIME type checking is enforced for module scripts per HTML spec.

Not sure where the problem lies, but I suspect the imports don't work? Any ideas?
My goal is to create a worker that handles uploading files async so I don't have to wait for it to complete.
Comment: Does this answer your question? [ES6 modules in local files - The server responded with a non-JavaScript MIME type](https://stackoverflow.com/questions/47403478/es6-modules-in-local-files-the-server-responded-with-a-non-javascript-mime-typ)
Comment: Not really. I tried that, for example: `import { uploadFile } from 'utilities/storage.utils.ts';` and still the same error
Comment: Browsers can't execute TypeScript.
Answer: Did you try to explicitly set the MIME type for your blob ?
export function getWorker(worker) {
  const code = worker.toString();
  const blob = new Blob([`(${code})()`], { type: 'application/javascript' }); // Explicitly set the MIME type
  return new Worker(URL.createObjectURL(blob), { type: 'module' });
}

This explicitly sets the MIME type of the Blob to 'application/javascript', which should probably resolve the error you're encountering.
Comment: Yes, by default, web workers don't have built-in support for TypeScript. You'll need to transpile your TypeScript code into JavaScript first.
Comment: yep, just tried and now it says `ncaught (in promise) ReferenceError: utilities_storage_utils_ts__WEBPACK_IMPORTED_MODULE_0__ is not defined` but its prob as mentioned that i cant import typescript files?


Could not connect to development server on new projet on React Native 0.37 (iOS)

Question: I just created a new project on react-native version 0.37 on iOS.
I've setting up this part of info.plist

server is running :

But this loads loop on this url:

url: /index.ios.bundle?platform=ios&dev=true&minify=false

And I finally get this error :

my package.json
<code>{
  "name": "Mich",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest"
  },
  "dependencies": {
    "react": "15.3.2",
    "react-native": "0.37.0"
  },
  "jest": {
    "preset": "jest-react-native"
  },
  "devDependencies": {
    "babel-jest": "17.0.2",
    "babel-preset-react-native": "1.9.0",
    "jest": "17.0.3",
    "jest-react-native": "17.0.3",
    "react-test-renderer": "15.3.2",
    "whatwg-fetch": "2.0.1"
  }
}
</code>
I have never had this error before by starting a new project. Someone can explain me what is wrong?
Comment: Had same problem but it is intermittent. Once I redeploy to app to the sim it goes away..
Comment: Are you running the application on an emulator or a device? If the latter, I manage to get it working with some extra code on `AppDelegate.m`. Let me know if it is the case. Otherwise, does the development server receive the emulator's request? If you, you might be facing a timeout error, since the server takes a bit to transpile all files. In any other case you might want to check that the emulator has access to the sever by opening `localhost:8081` on Safari.
Answer: I've found a solution, i press CMD+R and during server is loading, i press CMD + D and i press on Debug JS remotly.