The nth integral of $\frac{1}{1-x}$

Question: I was taking the nth integral of both sides of the geometric series sum formula with the first term being 1:
$$I^n \frac{1}{1-x} = \sum_{r=n}^\infty \frac{r!x^{r+n}}{(r+n)!} + P$$
Wher $P$ is some polynomial. I literally just got the nth integral of $\frac{1}{1-x}$, but I am sure that there's another way without using an infinite series. In another post I saw that the nth integral of $\frac{1}{x} $ is $$\frac{x^{n-1}\ln x}{\Gamma (n)}+ P$$ Could I just plug in $1-x$ for $x$ and be done? I feel skeptical about this.
Answer: If we take it as given that $I^n\left[\frac{1}{x}\right] = \frac{x^{n-1} \ln x}{\Gamma(n)} + P_n$, where $P_n$ is a degree $n-1$ polynomial, then we can't just substitute $1-x$ for $x$ and call it a day, but we can use that to make things much easier. Set $T_n(x) = I^n\left[\frac{1}{x}\right]$, and notice that:
$\begin{eqnarray} \frac{d}{dx} \left( T_n(1 - x) \right)& = & T_n'(1 - x) \frac{d}{dx} (1 - x) \\
& = & -T_{n - 1}(1 - x) \end{eqnarray}$
Since taking the derivative of $T_n$ reverses one of the integrals, taking us back to $T_{n-1}$.
From here, it's pretty quick to derive that $\frac{d^n}{dx^n} T_n(1 - x) = (-1)^n T_0(1 - x) = \frac{1}{1 - x}$, and hence your idea of substituting $1 - x$ was only off by a factor of $(-1)^n$.
Proving that this is equivalent to your expression is left as an exercise for the reader.

The nth integral of $\frac{1}{1-x}$


Sysinternals Sysmon: How to log an unsuccessful TCP/IP connection attempt

Question: I would like to use Sysmon to log an unsuccessful TCP/IP connection attempt.
For example, with the following configuration:
<NetworkConnect onmatch="include">
 <DestinationPort condition="is">22</DestinationPort>
</NetworkConnect>

I do see a successful connection, such as
ssh firstname.lastname@example.com

logged as
Network connection detected (rule: NetworkConnect)

However, if the handshake is not successful, e.g. because the attempt is dropped or reset, the attempt is not logged.
Is it possible to use Sysmon to log TCP/IP connection attempts?
If not, what would be a good way to achieve this?
Answer: You can try procmon (from sysinternal too) which log all activities of your server's process.
Or you can install netmonitor from microsoft which hrlp you to see you network traffic associated with yours processes.
Comment: Thank you for this suggestion. However, procmon uses (as far as I know) a proprietary, binary log file. Which makes it quite difficult to use procmon in combination with other tools in an automated, configurable manner.


Find all functions $f\colon \mathbb{R} \to \mathbb{R}$ such that $f(af(b) − b^2) = (b + 1)f(a − b)$ for all reals $a$ and $b$

Question:
Find all functions $f\colon \mathbb{R} \to \mathbb{R}$ such that $$
f(af(b) − b^2) = (b + 1)f(a − b)
$$
for all $a, b \in \mathbb{R}$.

Holds for f(x) = x and f(x) = 0 but I can't seem to prove its the only solution (if it is).
Edit: Sorry made a mistake, it doesn't hold for f(x) = x.
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Comment: Could you please include _some_ personal work? Like how you've tried to approach the question?
Comment: I don't think it does work for $f(x)=x$. On the left hand side, we would have $f(af(b)-b^2) = f(ab-b^2)=ab-b^2$. But on the right side we would have $(b+1)(a-b) = ab -b^2+a-b$.
Answer: Note that $b = -1$ yields the relation
$$ f(af(-1)-1) = 0, $$
which holds for all $a \in \mathbb R$. Assume that $f(-1) \neq 0$, then this implies that $f(x) = 0$ for all $x$. A contradiction since we said $f(-1) \neq 0$. Therefore $f(-1) = 0$ is forced. Consider the line $a = b -1$ then we have
$$ f((b-1)f(b)-b^2) = 0. $$
Suppose that $(b-1)f(b) - b^2 = c^2$, then we have
$$ f(x) = \frac{x^2 + c^2}{x - 1} $$
but also we have $f(c^2) = 0$. Which is never true unless $c = 0$, but then note that $x = -1$ is not 0 so this is not a solution. So we instead look at $(b-1)f(b) - b^2 = -c^2$, which yields
$$ f(x) = \frac{(x+c)(x-c)}{x-1} $$
again with the condition $f(-c^2) = 0$, which implies that the only solutions are $c = 1$.
If $c = 1$, then we see that $f(x) = x+1$ with $x \neq 1$. What happens at $x = 1$? Well, lets go back to the functional equation with $a-b = 1$:
\begin{align}
f((b+1)f(b) - b^2) & = (b+1)f(1) \\
f(2b+1) & = (b+1)f(1) \\
2(b+1) & = (b+1)f(1) \\
2 & = f(1).
\end{align}
The above equalities require $b\neq -1, 0, 1$ for all the operations to be valid. Hence $f(1) = 2$ and so there is no discontinuity. Therefore $f(x) = x + 1$ is the other solution.
Comment: how would you prove that this and f(x) = 0 are the only solutions?
Comment: @DS - updated. I believe it is not circular anymore.
Answer: The solutions are $f(x) = 0$ and $f(x) = x + 1$. The following is my un-optimized deduction.

Set $b=1$:
$$ f(f(1)a-1)=2f(a-1). $$
This implies that $f(1) \neq 0$ otherwise $f(x)$ is constant, meaning $f(x) \equiv 0$ (one solution). So suppose $f(1) \neq 0$.

Set $a=0$:
$$ f(-b^2)=(b+1)f(-b)=(1-b)f(b), \tag{1}$$
where the latter equation follows from the former by replacing $b$ with $-b$. Setting $b=1$ in (1) gives us $f(-1) = 0$.

Set $b=0$ then we have $f(f(0)a)=f(a)$. Setting $b=f(0)$ in (1) gives us $f(0) =1$, since $f(-1) = 0$ and $f(1) \neq 0$.

Set $a=b$:
$$f(b(f(b)-b))= b+1. \tag{2}$$

Set $a=2b-f(b)$:
$$f(-(b-f(b))^2)=(b+1)f(b-f(b)). \tag{3}$$
By (1),
$$(1-b+f(b))f(b-f(b)) = (b+1)f(b-f(b)).$$
This equation implies that if $f(b-f(b)) \neq 0$ then $f(b) = 2b$. For such $b$, $f(b^2) = b+1$ by (2). Moreover by comparing the left-most side and the right-most side of (1), we have $f(-b^2)=2b(1-b)$. On the other hand, by replacing $b$ with $b^2$ in the latter equation in (1), we have $2b(1-b)(b^2+1) = (1-b^2)(b+1)$. In reals, $b=1$ is a unique solution to this equation. Summarizing the above, $f(b-f(b)) = 0$ for $b \neq 1$.

If $f(1-f(1)) \neq 0$ then $f(1)=2$. However now $f(1-f(1))=f(-1)=0$. Therefore $f(b-f(b)) = 0$ for all $b$.

Finally, replace $b$ with $b-f(b)$. By (3) we have
$$(b-f(b)+1)f(a-b+f(b))=0.$$
If $f(b) \neq b+1$ for some $b$, then $f(x)$ is constant and zero. Therefore $f(b) = b+1$ (which is a solution).
Answer: Consider $a=0$ which gives us $f(-b^2)=(b+1)f(-b)$ Making the substitution $b \rightarrow -b$ we arrive at $f(-b^2)=(1-b)f(b)$ and therefore  $(b+1)f(-b)=(1-b)f(b)$. So $b=1$ gives us $2f(-1)=0$ and we have $f(-1)=0$. Similarly with $b=-1$ we have $2f(1)=0$ so $f(1)=0$.
Now setting $b=1$ in the original expression gives $f(af(1)-1)=2f(a-1)$ and so $f(af(1)-1)=f(-1)=0$ meaning $f(a-1)=0$ and so $f$ is the zero function.
Comment: How does $a=b=0$ imply $f(0)=0$? Plugging it in gives $f(0)=f(0)$?
Comment: @QC_QAOA good point. Let me work on that.
Comment: I am pretty sure that $f(x) = x + 1$ is a solution, but I could be wrong.
Comment: @Gregory if we have $f(-1)=f(1)=0$ then it can't be $f(x)=x+1$ since it is injective.
Comment: Interesting. But when I insert $f(x) = x + 1$ into the functional equation, it is true for all $x$...
Comment: I think the claim that $f(1) = 0$ is not always true. It certainly is true (the $f(x) \equiv 0$ is a solution), but unless I made a silly mistake, $f(x) = x + 1$ works.
Comment: When we evaluate your expression in $b=1$ and $b=-1$, we only get $f(-1) = 0$. How did you get $f(1) = 0)?
Answer: I'm not sure $f(x)=x$ works. I think I solved your problem :
If I understood you well we have $f:\mathbb{R}\mapsto\mathbb{R}$ verifying, for any $a,b\in\mathbb{R}$ :
$$f(af(b)-b^{2}) = (b+1)f(a-b)\label{eq0}\tag{0}$$
if you evaluate it for $a=0$, you get :
$$f(-b^{2}) = (b+1)f(-b)\label{eq1}\tag{1}$$
if you evaluate \ref{eq1} by replacing $b$ by $-b$, seeing that $f(-b^{2}) =f( (-b)^{2})$ we see that :
$$(-b+1)f(b) = (b+1)f(-b)\label{eq2}\tag{2}$$
if you evaluate it in $b=1$ and $b=-1$ you get
$$f(1)=f(-1)=0\label{eq3}\tag{3}$$
know if we evaluate \ref{eq0} with b=1, you get:
$$f(af(1)-1) = f(a-1)\label{eq4}\tag{4}$$
so if we remember \ref{eq2} we have, for any a :
$$f(a-1)=0\label{eq5}\tag{5}$$
so we can conclude that f is identically zero.
Comment: When we evaluate (2) in $b=1$and $b=-1$, we only get $f(-1) = 0$. How did you get $f(1) = 0)?
Comment: @DS You seem absolutely right and I don't remember what I did at all. I'll look into it if I find some time today.


No DNS for ec2 after outage

Question: There was a failure in the Sydney region of AWS. After a number of hours they came back up however there was no longer a DNS on the *.2 of my ip range (or at least it wasn't responding).
I've added a public DNS to my <code>/etc/resolv.conf</code> to fix the issues however I'd like to get the one on my subnet working. I've tried to ping the *.2 and it returns nothing (however it might be purposely blocking it). I know I can also enable the old DNS in my VPC however I'd prefer to get the original one working.
Short of recreating the whole VPC again in the hope to get it back I'm not sure what I can do. I've tried posting to the AWS forums however it just goes into redirect loop even after signing in.
Answer: Looks like after 48+ hours it has come back online without any intervention.

No DNS for ec2 after outage


Difference in results when using full dataset vs subset in lmer

Question: I have a dataset with the number of different species across multiple years and locations. I'm interested in seeing how abundance of each species has changed over time in each place. My data looks something like this (but 35000 rows):
Year   Place       Type of fruit  Number of fruits
2000   Orchard     Apple          5
2000   Beach       Apple          0
2000   Mountains   Apple          2
2001   Orchard     Apple          30
2001   Beach       Apple          3
2001   Mountains   Apple          3
2000   Orchard     Orange         18
2000   Beach       Orange         5
2000   Mountains   Orange         0
2001   Orchard     Orange         6
2001   Beach       Orange         1
2001   Mountains   Orange         5
2000   Orchard     Coconut        0
2000   Beach       Coconut        50
2000   Mountains   Coconut        0
2001   Orchard     Coconut        1
2001   Beach       Coconut        52
2001   Mountains   Coconut        2

I ran a test like this:
fit <- lmer(year~number + type + (1|place), data=fruits, REML=FALSE)

which gives me a result for each species.
If I run a separate test like this:
sepfit <- lmer(year~number + (1|place), data=subset(xmasdataover, species == "Apple"),
          REML=FALSE )

I get a different result for Apple than I got for it in the original combined analysis. What's the reason for this and which test would then be more appropriate?
Answer: There are a few issues here, none of which are particularly specific to mixed models, but have to do with parameterization of linear models in R (and to some extent in any software for fitting linear models).

The value on the left-hand side of the ~ is the response, or dependent, variable: since you say

I'm interested in seeing how abundance of each species has changed over time in each place

I would think that number ~ year + type would be more appropriate (i.e., number is the response variable)

when you specify ~ year + type you are fitting an additive model, i.e. the model assumes that fruit types have difference baseline values but that all fruits change between years in the same way. If year is a numeric (rather than a categorical, or factor variable in R), the value that R would give you for typeApple represents the predicted difference at year 0 (!) between whatever your baseline fruit is (usually the first alphabetical level, which makes it a little odd that you got a result for Apple ...) and apples.
if you make year a factor and specify number ~ -1 + type + year:type then you will get separate estimates of the year effect for each fruit, which should be identical to what you get if you use the subset.  You could also consider the lmList() function ...

Example:
dd <- expand.grid(type=c("Apple","Cherry","Grapefruit"),year=factor(2001:2002))
dd$y <- 1:6
lm(y~-1+type+type:year,dd)

Comment: Thanks so much for helping me out. I took your suggestions and put it back into the lmer as

fit <- lmer(number ~ -1 + type+ (1|year:type) + (1|place), data = fruits, REML=FALSE ). This gives me results that are close to what I get with the subset but a little different. Is there any reason you used lm instead of lmer? How would I control for place using lm? Would I just add + place? Thanks so much again.


How can I find the value of this function?

Question: $f$ is a linear function such that $f(6)-f(2)=12$. Find the value of $f(2014)-f(1998)$
what I was thinking is $f(2)= f(6)-12$ and $f(2014=2*1007)$ and $f(1998=2*999)$ but I don't think that means $f(2014)=f(2)f(1007)$ right?
I'm confused on how to solve this problem, can anyone help please?
Comment: Clue is in *Linear* function - what does it mean for a function to be *Linear*?
Comment: so it means that $y=mx+b$ so I'm assuming i should find the slope but I don't know how i can since the points are $(2, f(6)-12)$ and $(6, f(6)+12)$
Comment: A linear function is one whose graph is a line.  So $f(x) = mx + b$  And we know that $4= f(6) -f(2) = (6m + b) - (2m+b) =4m$.  So what is $f(2014)-f(1998)$?
Comment: "but I don't know how i can since the points are (2,f(6)−12) and (6,f(6)+12) "  If that were true (you made a simple mistake) then the slope is $\frac {(f(6)+12)-(f(6)-12)}{6-2}$.  You can do that.  (But your points *AREN"T* $(2,f(6)-12)$ and $(6,f(6)+12)$.  The second point is $(6,f(6))$.
Answer: A simple and intuitive hint: the function is linear, so it has constant slope. When $x$ changes from $2$ to $6$ (i.e. it increases by $4$), the function increases by $12$. So what happens when $x$ changes from $1998$ to $2014$ (i.e. it increases by $16$)?
Answer: hint
If $ f$ is such that
$$f(x)=mx+n$$
then
$$\frac{f(a)-f(b)}{a-b}=\frac{f(c)-f(d)}{c-d}$$
In your case, $n=0$ and
$$\frac{f(6)-f(2)}{6-2}=\frac{f(2014)-f(1998)}{2014-1998}$$
You can take it.
Answer: If $f(x) = mx + b$ then $f(6) - f(2) = (6m +b)-(2m+b) = 4m$.  But we know $f(6)-f(2) = 12$.
Now $f(2014) - f(1998)= (2014m + b)-(1998m + b) = 16m$.
Note: the $y$ intercept isn't necessary for the question.


How do I join multiple lines to a single one if the page is viewed on mobile?

Question: Using Twitter Bootstrap (3.3.X), I want to display these lines on desktop:

Some info
  Some more info
  Even more stuff

And the same on mobile view should display as (pipes as in literal character, not separate blocks if possible):

Some info | Some more info | Even more stuff

This would be on the right side of a div defined with col-md-8, or on a single line above the div if it's on mobile.
Any ideas?
Answer: You can do this with :after pseudo class and display: inline-block
DEMO
@media(max-width: 768px) {
  p {
    display: inline-block;
  }

  p:not(:last-child):after {
    content: " |";
  }
}

Some info

Some more info

Lorem ipsum

Comment: If you are using `col-md-8` breaking point is `992px` just so you know.
Comment: Thanks, was wondering why did it flow into the main content between 768 and that 992 width.
Answer: Optionally if you are using Twitter Bootstrap 3 you can make use of the  visible-*-* classes which will let you hide or show content depending on the screen size.
Example Fiddle
So you could use

Some info
/

Some more info
/

Even more stuff
/

You could even change the "/" character for a glyphicon o another kind of code.
and for CSS
/*Medium Media*/
@media (max-width:1199px) {
  p.custom-menu{display: inline;}
}

/*Small Media*/
@media (max-width:991px) {
  p.custom-menu{display: inline;}
}

/*Extra small Media*/
@media (max-width: 768px){
  p.custom-menu{display: inline;}
}

Choose whichever media query suits your needs the best.


I have code that logs changes into a new sheet. How can I add code that will take the user to the most current entry in that log sheet to add a note?

Question: I currently have code that logs any changes made into a separate change log sheet. I need to add in code that takes the user to that newest entry in the change log so that they have to put in a note for why they changed it. I was exploring this option of being taken to that entry or having a pop-up text box that appears when a change is made prompting the user to type in a note that will then be saved with that entry in the log.
Here's my working code:
Dim oldValue As String
Dim oldAddress As String

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
    Dim sSheetName As String
    Data = "Data"
    Dim ssSheetName As String
    MoreData = "MoreData"

    If ActiveSheet.Name <> "LogDetails" Then
        Application.EnableEvents = False
        Sheets("LogDetails").Range("A" & Rows.Count).End(xlUp).Offset(1, 0).Value = ActiveSheet.Name & " – " & Target.Address(0, 0)
        Sheets("LogDetails").Range("A" & Rows.Count).End(xlUp).Offset(0, 1).Value = oldValue
        Sheets("LogDetails").Range("A" & Rows.Count).End(xlUp).Offset(0, 2).Value = Target.Value
        Sheets("LogDetails").Range("A" & Rows.Count).End(xlUp).Offset(0, 3).Value = Environ("username")
        Sheets("LogDetails").Range("A" & Rows.Count).End(xlUp).Offset(0, 4).Value = Now

    If ActiveSheet.Name = Data Then
        Sheets("LogDetails").Hyperlinks.Add Anchor:=Sheets("LogDetails").Range("A" & Rows.Count).End(xlUp).Offset(0, 5), Address:="", SubAddress:="'" & Data & "'!" & oldAddress, TextToDisplay:=oldAddress

    ElseIf ActiveSheet.Name = MoreData Then
        Sheets("LogDetails").Hyperlinks.Add Anchor:=Sheets("LogDetails").Range("A" & Rows.Count).End(xlUp).Offset(0, 5), Address:="", SubAddress:="'" & MoreData & "'!" & oldAddress, TextToDisplay:=oldAddress
    End If

    Sheets("LogDetails").Columns("A:D").AutoFit
    Application.EnableEvents = True

    End If
End Sub

Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)

    If Target.Count > 1 Then Exit Sub
    If Target.Count = 1 Then
        oldValue = Target.Value
    End If
    oldAddress = Target.Address
End Sub

Comment: `changeReason = InputBox("Please enter a reason for the change", "Log entry", "")` then add that to the log sheet
Comment: `newest entry` is not necessarily a change to previous data
Answer: I couldn't resist to do a bit of refactoring:
It's always a good idea to create a seperate sub-routine for a work like this - and then call the routine from the worksheet_change-event.
Furthermore I am first creating an array with the values to log - and then write this array to the log-sheet. Usually this is for performance reasons - which is not the case for this logging.
But as you can see: it is much easier to read and understand the code - as the reader doesn't have to "walk" along the long code line to see what is happening.
By using a variable for the target range it is pretty easy to select it later.
Regarding your basic question:
This code first asks the user for the comment with a input-box. If he/she doesn't give an answer, according cell will be highlighted and user again asked to put in a comment.
Put this into a normal module
Public Sub addLogEntry(rgCellChanged As Range, oldValue As String, oldAddress As String)

Dim wsChanged As Worksheet
Set wsChanged = rgCellChanged.Parent

Dim wsLogData As Worksheet
Set wsLogData = ThisWorkbook.Worksheets("LogDetails")

'we don't need logging on the logsheet
If wsChanged Is wsLogData Then Exit Sub

'Get comment from user
Dim commentChange As String
commentChange = InputBox("Please enter a comment, why you made this change.", "Logging")

Application.EnableEvents = False

'Collect data to log
Dim arrLogData(6) As Variant
arrLogData(0) = wsChanged.Name & " - " & rgCellChanged.Address(0, 0)
arrLogData(1) = oldValue
arrLogData(2) = rgCellChanged.Value
arrLogData(3) = Environ("username")
arrLogData(4) = Now
arrLogData(6) = commentChange '>>> adjust the column in case your comment column is not G

'get cell to enter log data
Dim rgLogData As Range
Set rgLogData = wsLogData.Range("A" & Rows.Count).End(xlUp).Offset(1, 0)

'write data
rgLogData.Resize(, 7).Value = arrLogData

'create hyperlink
wsLogData.Hyperlinks.Add rgLogData.Offset(, 5), Address:="", SubAddress:="'" & wsChanged.Name & "'!" & oldAddress, TextToDisplay:=oldAddress

'>>> optional: activate log sheet and select comment cell
'If user hasn't entered a comment, activate logsheet and cell
If LenB(commentChange) = 0 Then
    wsLogData.Activate
    MsgBox "Please enter the comment, why you made the change.", vbExclamation, "Logging"
    rgLogData.Offset(, 6).Select
End If

Application.EnableEvents = True

End Sub

And this is how your worksheet_change looks like
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
    addLogEntry Target, oldValue, oldAddress
End Sub

Another advantage: if a code reader gets to this he/she immediately understands what will happen (a log entry will be added) - it is not necessary to read the whole code to understand it
Comment: Thank you for this! I am trying to implement it but get a Compile Error: ByRef argument type mismatch.

I put the addLogEntry sub into a Module, Module1 and I put Workbook_SheetChange into 'ThisWorkbook'

Any tips on alleviating this?
Comment: At which line does the error occur?


Mixed Recurrence

Question: How to solve the following mixed recurrence relations:
$$T(n)= \max_{0<k<n} \left\{ \min \left\{ k, a T\left(\frac{n-k}{b}\right)\right\} \right\}$$
Here $a,b \ge 1$ are constants.
I could solve some special cases such as when $a=b=2$ then by guessing method, $T(n) = \Theta (\dfrac n {\lg n})$. However, I could not generalize for all values of $a,b$.
Comment: What do you mean when you say "solve"? Do you only want to find a lower bound?
Comment: By solve I mean to obtain asymptotically very close upper and lower bound (say the upper and lower bound differ by a constant factor).
For example, $a=b=2$ will imply $T(n)=\Theta(\frac{n}{\log n})$.
Answer: Since you did not define starting values of $T$ and didn't care about divisibility $n-k$ by $b$, I think a solution by asymptotical handwaving is OK for your needs. Assume that $T$ increases. If $a=1$ then the right hand side of the equality for $T(n)$ is less than $T(n)$, so from now we shall assume that $a>1$. Since when $k$ increases $ aT\left(\frac{n-k}{b}\right)$ decreases, we have $T(n)=k=aT\left(\frac{n-k}{b}\right)$ for some $k\in (0,n)$. Let's look for a solution of this equality with a simple form. The following cases are possible.
$a>b$. Assume that $T(n)\simeq cn$ for some constant $c<1$. Then $$k\simeq cn \simeq ac\frac{n-cn}{b},$$  so we can put $c=1-b/a$.
$a=b$. Assume that $T(n)\simeq \frac{n}{\ln n}$. Then $$k\simeq \frac{n}{\ln n}\simeq a\frac{\frac{n-\frac{n}{\ln n}}{b}}{\ln \left(n-\frac n{\ln n}\right)}\simeq \frac{n}{\ln n}.$$
$a<b$. Assume that $T(n)\simeq n^c$ for some constant $c<1$.
Then $$k\simeq n^c \simeq a\left(\frac{n-n^c}{b}\right)^c\simeq a \left(\frac{n}{b}\right)^c,$$ so we can put $c=\log_b a$.

Mixed Recurrence


Benefits of Functional decomposition and currying

Question: I have a function, calculate(String A,int B) in legacy code
Double calculate(String A,int B) {
   if(A.equals("something")){  return B*1.02; }
   if(B.equals("some")) return B*1.0;
   else return B;
}

The calculation applied on B depends on the value of A.
In functional style I can break this into:
Function<String, Function<Integer,Double>> strategyA = (a)-> {
  if(A.equals("something")) return b -> b*1.02;
  if(B.equals("some")) return b -> return b -> b*1.0;
  else return b -> b;
}

Then instead of calling calculate(a,b) I would call
strategyA.apply(a).apply(b)

Is the second style better than first one. As per my understanding this involves Strategy pattern and Functional Decomposition and Currying.
If the second approach is indeed better, how would you convince someone?
Answer: In Java, the preferred way of delivering a named piece of code is and stays the method. There is no reason to express a method as function, just to have "more functional style". The reason, why function support was added to Java, is, that you sometimes want to pass a reference to the code to another method or function. In this case, the receiving method defines the required function signature, not the code you're going to encapsulate.
So your calculate method may be referred to as an ObjIntConsumer<String>, if the receiving method only wants to pass pairs of String and int to it without being interested in the result. Otherwise, it may use a custom functional interface expressing the (String,int) → Double signature. Or when you accept boxing, BiFunction<String,Integer,Double> will do.
Currying allows you to reuse existing interfaces like Function to express functions with multiple arguments, when no builtin interface exists, but given the resulting generic signature, which will appear at least at one place in Java code using such a curried function, the readability suffers a lot, so in most cases, defining a new functional interface will be preferred over currying in most cases…
For other programming languages, having a different syntax and type inference for functional types (or having real function types in the first place, rather than settling on functional interfaces), this will be quite different.
Answer: I agree with Holger that in most cases, it does not make sense to write code using functions just for the sake of using functional programming. Functions are just an additional tool that lets you write code such as collection processing in a nicer way.
There is one interesting thing about your example though, which is that you take the String parameter a, then perform some computation and then return another function. This can be sometimes useful if the first operation takes a long time:
Function<String, Function<Integer,Double>> f = (a) -> {
  if (some-long-computation(a)) return b -> b*1.02;
  if (some-other-long-computation(a)) return b -> return b -> b*1.0;
  else return b -> b;
}

When you then invoke f with the String argument, the function will run some-long-computation and some-other-long-computation and return the desired function:
Function<Integer,Double> fast = f.apply("Some input"); // Slow
Double d1 = fast.apply(123); // Fast!
Double d1 = fast.apply(456); // Fast!

If f was an ordinary method, then calling it twice as f("Some input", 123) and
f("Some input", 456) would be slower, because you'd run the expensive computations twice. Of course, this is something you can handle without functional programming too, but it is one place where returning a function actually fits quite nicely.
Comment: You could still have a method returning a `Function`…
Comment: @Holger the question is not about the syntax..rather its  about benefits of returning a function as result instead of directly computed value and about spreading method arguments over multiple functions.
Comment: Tomas has clearly stated one use case where this might actually make sense.
Comment: @Satyendra Kumar: there is a significant relationship to the syntax, as there are functional programming languages for which there is no difference between curried functions and functions with multiple parameters. So there, getting a partially applied function is as easy as omitting one or more parameters. In contrast, having to declare `Function>>>>>` to do a similar thing in Java *makes* a difference. If you only wanted to see some use case examples, your question is off topic for Stackoverflow.
Comment: In Tomas example it is useful *to return* a function, but since there is still no reason *to define* `f` as a function (instead of a method returning a function), there is no reason to have a curried function here.


If the first order conditions of MLE and OLS are identical, is MLE as efficient as OLS i.e. are they both BLUE

Question: If the first order conditions of MLE and OLS are identical is MLE as efficient as OLS?
It seems that they should be equal in terms of efficiency however if OLS is the best linear unbiased estimator does that mean that there is in fact a difference and OLS is slightly more efficient than MLE.
If there is a difference why?
If there is no difference how do you formally show this. Do you need to show the asymptotic distribution etc.
Answer: Ordinary Least Squares (OLS) is the maximum likelihood estimator (MLE) when the conditional distribution of the $Y$ is normal. However, the proof of the Gauss Markov Theorem (which shows that OLS is BLUE) does not require the conditional $Y$ to be normally distributed, so the BLUE-ness of OLS is a nonparametric result. In fact, if the conditional $Y$ were any other distribution, maximum likelihood would be more efficient, it's just that the estimator would not be a linear one. It should match our intuition: using the knowledge of the actual distribution should help us. The MLE is always the asymptotically efficient estimator.
Reminder: a linear estimator is any estimator of the form $\hat{Y} = bY$ i.e. a projection. There are other forms of linear estimators like the average slope. This is an elusive fact, one must delve into Seber and Lee "Linear Regression Analysis" for the proper definition.


How to get specific index values and store in a array from multiple php arrays

Question: I've multiple arrays received from db table. now i'm trying to check "is their birth date == current date" if yes then their contact numbers saved in a array called birthdays
Here is my try
<code>$curr_date = date('m/d');

$birthday = array(); // array initialization
$anniversary = array(); // array initialization

$con=mysqli_connect("localhost","root","","birthdays");

$sql="SELECT * FROM users";

$result=mysqli_query($con,$sql);

$row=mysqli_fetch_assoc($result);

echo "<pre>";

if ($result=mysqli_query($con,$sql))
{
    while ($row=mysqli_fetch_assoc($result))
    {
        print_r ($row);
    }
}
</code>
Here is a image of current code with expected description

I'm trying lot of time but unable to achieve exact result. kindly guide me. Thanks
Comment: just look whats inside result['birth_date']
Comment: Where are you comparing birth date with current date?
Comment: ok, its genrates dates. now how can i check them from current date?
Comment: What are you doing? You run the query, fetch the first row, then run the query again and start fetching rows in a loop. Start by applying some sanity to your existing code
Comment: this is my actually issue @NanaPartykar. where am i compare this :/
Comment: i'm new to php @RiggsFolly, i'm not sure where i am wrong...!
Answer: I think you need something like this?
<code>$date1 = date('m-d', strtotime($row['birth_date']));
$date2 = date('m-d');

if ($date1 == $date2)   {
    echo 'Happy birthday!';
}
</code>
See PHP date function for more info.
Answer: Obviously you got a result from the database, so you pull all the results in an array:
<code>$sql = "SELECT * FROM xyztable";
$result = $con->query($sql);
$users = array();
while($row = $result->fetch_assoc()) {
    $users[] = $row;
}
</code>
So now we are at the same point.
Now you can do a loop trough the arrays, create a Birthdays array and you should explode the birth date:
<code>$birthdays = array();
for($users as $user) {
  $birth = explode("/", $user['birth_date']);

  $new_birth = "$birth[0]/$birth[1]";
  $actual_date = date("m/d");
  if($new_birth == $actual_date) {
     $birthdays[] = $user['customer_mobile'];
  }
}
</code>
That should be it.
Comment: unable to achieve with it..!
Comment: Notice: Undefined offset: 1
Answer: If this is the only purpose of fetching data from database then there is no need to push these rows in a separate array. Just push the contact numbers to the array. There is no need to loop it twice.
<code>    $curr_date = date('m/d');

    $birthday = array(); // array initialization
    $anniversary = array(); // array initialization

    $con=mysqli_connect("localhost","root","","birthdays");

    $sql="SELECT * FROM users";

    $result=mysqli_query($con,$sql);

    $row=mysqli_fetch_assoc($result);

    if ($result=mysqli_query($con,$sql)) {
        while ($row=mysqli_fetch_assoc($result)) {
            if (date('m/d',strtotime($row['birth_date'])) == $curr_date)
                $birthday[] = $row['customer_mobile'];
        }
    }
</code>
Comment: Notice: Undefined variable: birthday
Comment: its says $birthday is undefined, when i print_r($birthday) bellow your code.
Comment: If the you wish to push the contact numbers to the `$birthdays` array which you have initialized then change the array to `$birthdays`, but if you have that array for some other purpose then initialize `$birthday = array()` where you have initialized other two arrays. I have updated the answer to push the contact numbers to the `$birthdays` array which you have initialized.
Comment: but why it says $birthdays is undefined..!
Comment: obviously, it says:

 Undefined index: birth_date
Comment: Can you print_r($row), and check whether there is `birth_date` index in every array? The screenshot that you have included shows that every $row array has `birth_date` index.
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/148509/discussion-between-ravi-and-devendra-singh).


How to grey out fields with non editable permission upon node editing?

Question: I need the ability to grey out fields with non editable permission i.e. to show certain field values to the user but forbid him/her to edit them, upon node editing.
How can i achieve this?
Comment: You mean readonly field ?
Comment: Are you using D7 or D6 ?
Comment: Exactly. Field permissions give the ability to leave unchecked the "edit own field" permission but this results to hiding the field. I want that field to be readonly as a reminder for the user. Using D7...
Answer: Form elements have a disabled property you can set as a boolean. For example:
$form['test'] = array(
  '#type' => 'text',
  '#title' => t('Test'),
  '#required' => FALSE,
  '#default_value' => 0,
  '#disabled' => TRUE,
);

Now, you can use hook_form_alter() to check that you're on the right form ($form_id), and any other conditions you require, like for instance checking user permissions, with the user_access() function.
Answer: I think the fastest way to achieve what You want is to use jQuery in Your template or custom module:
$("#fieldName").prop("readonly",true);


Como pegar valores de formulários POST no Django usando Class Based View

Question: Tenho um formulário bem simples e preciso pegar o valor de um input:
    <form method="POST">
        Nome:
        <input type="text" name="user_name" />
        <button type="submit">OK</button>
    </form>

Minha classe da view está assim:
class Home(TemplateView):
    template_name = "home/index.html"

Como eu pego o valor do input? Obs: Preciso usar obrigatoriamente o Class Based View.
Answer: Boa noite,
Para este caso, você deverá utilizar um FormView.
Crie dentro do app um arquivo chamado forms.py, e dentro dele crie o seguinte código:
from django import forms
class MeuForm(forms.Form):

    user_name = forms.CharField(label='Nome')

Faça o import do form dentro da sua view assim:
from .forms import MeuForm
E modifique sua view do seguinte modo:
class Home(TemplateView):
    template_name = "home/index.html"
    form_class = MeuForm
    success_url = 'url_para_onde_direcionar_apos_o_submit'

Com isso já será possível fazer com que o form funcione. Agora, para pegar esses dados e fazer alguma tratativa com os mesmos, basta sobrescrever o método "form_valid" dentro da sua View, ficaria assim:
def form_valid(self, form):
    # aqui você faz o que deseja com os dados
    # e no fim retorna o form para que o submit ocorra.
    return super().form_valid(form)


Doctrine extension :: search entity by other field than ID

Question: Using doctrine extension, when locale changes, searching an entity with, say ID=1, returns proper values for the current locale (stored in translations table), which is a great thing, but what if I need to search for entities by another field, like name or something..
Is there any way to get proper results using other entity field/property that ID?
Comment: What you are using for searching by ID?
Comment: https://github.com/l3pp4rd/DoctrineExtensions/blob/master/doc/translatable.md
Comment: try use `$em->findBy(array('name' => 'example')`
Comment: Belive me, I tried.. Did you succeeded using the above?
Comment: yes, did you tried to get an repository:
`$em->getRepository('MyProject\Entity')->findBy(array('name' => 'example'));`
Comment: Just to be clear: $categRepo = $this->getDoctrine()->getRepository ("RamaCmsBundle:ProductCategory"); $categ = $categRepo->findOneBy (array('webName' =>'somePage'));
Comment: Ricardo, are you using translatable doctrine extension?
Comment: I use the same get repository function:
`$this->getDoctrine()->getRepository('Entity:Product')`
But I not using an translatable doctrine extension =/
Answer: Try use:
<code>$query = $em->createQuery("SELECT pc FROM MyDomain\Model\ProductCategory pc WHERE pc.webName LIKE :name")
$query->setParameter("name", $name);
$query->getResult();
</code>


Is the ideal $I=(x_1 x_5 - x_2 x_4 , x_1 x_6 - x_3 x_4)$ of $k[x_1,...,x_6]$ a radical ideal? Is it a prime ideal?

Question: Is the ideal $I=(x_1 x_5 - x_2 x_4 , x_1 x_6 - x_3 x_4)$ of $k[x_1,...,x_6]$ a radical ideal? Is it a prime ideal?
thanks
Comment: I tried to use initial ideals but it became harder.
Answer: It is not prime since
$$x_1(x_3x_5-x_2x_6)=x_3(x_1x_5-x_2x_4)-x_2(x_1x_6-x_3x_4)\in I$$
but $x_1\notin I$ because every nonzero element of $I$ has degree at least $2$, and $x_3x_5-x_2x_6\notin I$ because every element of degree $2$ in $I$ is a $k$-linear combination of $x_1x_5-x_2x_4$ and $x_1x_6-x_3x_4$ and so cannot involve either of the terms $x_3x_5$ or $x_2x_6$.
Note that this is taking advantage of the fact that $I$ is homogeneous.
Answer: If you compute a Gröbner basis for $I$, you will get that you need one additional generator, namely $x_1x_3x_5-x_1x_2x_6=x_1(x_3x_5-x_2x_6)$. Thus $x_1$ vanishes on the zero set of the ideal, but $x_1 \not \in I$, as in Alex Becker's anser above.
Your ideal in fact decomposes as $I= I_{minors} \cap \langle x_1, x_4 \rangle$, where $I_{minors}$ is the ideal of $2 \times 2$-minors of a generic matrix
$$ \begin{bmatrix}x_1 & x_2 & x_3 \\ x_4 & x_5 & x_6\end{bmatrix}.$$
So the "reason" the ideal is not prime is that you didn't include all minors.
ADDED To see the decomposition $I=I_{minors} \cap \langle x_1,x_4 \rangle$, we show first the $\subseteq$-direction. But this is clear, because the generators of $I$ are a subset of the generators of $I_{minors}$, and they clearly lie in $\langle x_1,x_4\rangle$. For the other direction, one notices that already two of the generators of $I_{minors}$ lie in $I$. The last one, $x_2x_6-x_3x_5$, can be multiplied by elements of $\langle x_1,x_4\rangle$ to give $x_1x_3x_5-x_1x_2x_6$, wich lies in $I$, because it is part of a Gröbner basis of $I$, as explained above. The the decomposition is shown.
Now it is a result that any determinantal ideal is prime (try Google), and so $I$ is an intersection of prime ideals. Thus $I$ is radical, because an ideal is radical if and only if it decomposes as an intersection of radical ideals (easy exercise!). (for a hint: suppose $f^k \in I$. Then $f^k$ is also contained in all the components of $I$, but they are all radical...)
Comment: I think $I= I_{minors} \cap \langle x_1, x_4 \rangle$ deserves a proof. Furthermore, you could add that this shows that $I$ is radical (since determinantal ideals are prime).
Comment: @user26857 Yes, it deserves proof, but I don't believe it should be too difficult. I did the computation in Macaulay2 which I trust more than myself.
Comment: Minor point: my answer is no longer "above".
Comment: @AlexBecker Or is it? (Both answers currently have a score of 5, which leads to the well-known Schrödinger's Answer Paradox).
Comment: @KarlKronenfeld At time of writing, his had 5 and mine had 4.
Comment: @Fredrik Meyer: thanks. can you please write  user26857's comment in details specially about "this shows that I is radical"? you see  my reputation:40
Comment: @user10000 I've expanded somewhat on my answer. Does this clarify?


How do I sort paragraph types?

Question: Hello it is possible to order the output of the paragraphs for example
Type of content Blog
I create a blog details field that calls the type of paragraphs and there I select image and description
In my content it goes in this order

1 Image
2 Description

In the view I call that field
blog details
and they appear to me
but based on the order of the node
But I don't want it to look like this

1 description
2 image

and always look in that order
Comment: Why not make separate fields for image and description of they're always in a specific order?
Comment: Hello, within a paragraph field I can choose between several types of paragraphs, in this case I have an image paragraph and a description paragraph and a single widget button that allows me to add which one I want like this image https://i.stack.imgur.com/9ofvV.png
Comment: Oh, I misunderstood. Sorry. Are we you trying to show only the description and image paragraphs in your view? In your image I see 5 total paragraphs, are you trying to show a subset of the total paragraphs added to your field, and show them in a specific order?
Comment: Hello exactly in the view it is shown according to the order that was saved in the node

But I want a different order of sight
Answer: I don't believe there's a way to sort the values of a field at the view level. However, you can easily get the results you want by creating a custom field formatter and then using it to render your field in the view.
You can read more about field formatters by reading the Create a custom field formatter documentation on d.o.
Create a custom formatter that extends the formatter you're using now. I'm guessing you're using the default ERR formatter so you'll want to extend Drupal\entity_reference_revisions\Plugin\Field\FieldFormatter\EntityReferenceRevisionsEntityFormatter.
You'll need to override viewElements() or getEntitiesToView() - I'd override getEntitiesToView().
<code>protected function getEntitiesToView(EntityReferenceFieldItemListInterface $items, $langcode) {
  // Let the parent class get all entities in the field first.
  $all_entities = parent::getEntitiesToView($items, $langcode);
  $my_entities = [];

  // Get first Description paragraph.
  $desc = $this->getFirstOfType($all_entities, 'MY_DESCRIPTION_BUNDLE');
  if (!empty($desc)) {
    $my_entities[] = $desc;
  }

  // Get first Image paragraph.
  $img = $this->getFirstOfType($all_entities, 'MY_IMAGE_BUNDLE');
  if (!empty($img)) {
    $my_entities[] = $img;
  }

  return $my_entities;
}

protected function getFirstOfBundle($entities, $bundle) {
  foreach($entities as $entity) {
    if ($entity->bundle() == $bundle) {
      return $entity;
    }
  }

  return FALSE;
}
</code>
Comment: Hi thanks for answering I wish I could do it from the views but I will try to use your example

How do I sort paragraph types?


Combinar valores recursivos em um dataframe com valores únicos no R

Question: Tenho um banco de dados com identificações de animais (brincos). Alguns animais perdem esse brincos e, quando isto acontece, o brinco é reposto por outro brinco com outro id e esta informação fica contida em uma tabela similar a esta:
date<- c('2018-01-01','2018-02-20','2018-10-04','2018-12-30','2019-01-03','2019-03-14','2019-05-06','2019-07-01','2019-07-25','2019-10-29','2019-11-26','2020-01-07','2020-05-04','2020-12-30')
> id_brinco_or<-c(1,5,10,20,31,3,4,13,15,12,2,65,9,93)
> id_brinco_rp<-c(2,8,15,12,13,6,28,55,65,9,80,40,93,30)
>
> df<-data.frame(date,id_brinco_or,id_brinco_rp)
> df
         date id_brinco_or id_brinco_rp
1  2018-01-01            1            2
2  2018-02-20            5            8
3  2018-10-04           10           15
4  2018-12-30           20           12
5  2019-01-03           31           13
6  2019-03-14            3            6
7  2019-05-06            4           28
8  2019-07-01           13           55
9  2019-07-25           15           65
10 2019-10-29           12            9
11 2019-11-26            2           80
12 2020-01-07           65           40
13 2020-05-04            9           93
14 2020-12-30           93           30
>

O que eu gostaria é combinar, vincular ou relacionar todos os brincos da sequência.  Montando uma tabela como esta:
   id_brinco_un<-c(1,1,5,10,10,10,20,20,20,20,31,31,3,4)
> id_brinco<-c(2,80,8,15,65,40,12,9,93,30,13,55,6,28)
> df2<-data.frame(id_brinco_un,id_brinco)
> df2
   id_brinco_un id_brinco
1             1         2
2             1        80
3             5         8
4            10        15
5            10        65
6            10        40
7            20        12
8            20         9
9            20        93
10           20        30
11           31        13
12           31        55
13            3         6
14            4        28

Desta forma eu poderia utilizar o df2 com ifelse, %in%, match, etc para tratar os dados que tiro desse banco de dados.
A tabela de reposições de brinco tem quase 2 milhões de registros. Eu tenho trabalhado com mais frequência no R utilizando tidyverse, mas qualquer solução com qualquer pacote do R é bem vinda.
Comment: Olá @ifelipec, bem vindo ao SOpt. O exemplo que postou contém apenas um animal, então é difícil sugerir uma solução que se aplique aos seus dados originais. Se possível, poste um exemplo dele, ou forneça um exemplo mais completo. Veja [aqui](https://pt.stackoverflow.com/questions/264168/quais-as-principais-fun%c3%a7%c3%b5es-para-se-criar-um-exemplo-m%c3%adnimo-reproduz%c3%advel-em-r) como fazer isso.
Comment: @CarlosEduardoLagosta Adicionei um exemplo mais complexo e próximo da minha realidade. Obrigado!
Answer: Pode interpretar os dados como grafo e identificar as sequências de mudança de ID.
library(igraph)

grafo <- graph_from_data_frame(df[, c("id_brinco_or", "id_brinco_rp")])

As datas não são necessárias porque os dados são direcionados:
plot(grafo)

# IDs iniciais
ids.iniciais <- with(df, id_brinco_or[!id_brinco_or %in% id_brinco_rp])

# Matriz de distâncias saindo dos IDs originais
matd <- distances(grafo, as.character(ids.iniciais), mode = "out")

# Cria uma lista com as sequências de IDs
lids <- apply(matd, 1, function(x) colnames(matd)[x > 0 & x < Inf])

# Converte a lista para data.frame com os nomes desejados:
df2 <- setNames(stack(lids)[2:1], c("id_brinco_un", "id_brinco"))

df2
#>    id_brinco_un id_brinco
#> 1             1         2
#> 2             1        80
#> 3             5         8
#> 4            10        15
#> 5            10        65
#> 6            10        40
#> 7            20        12
#> 8            20         9
#> 9            20        93
#> 10           20        30
#> 11           31        13
#> 12           31        55
#> 13            3         6
#> 14            4        28

Alternativa
Se a matriz de distâncias fica muito grande para seus dados completos, pode tentar outra abordagem usando clusters para identificar os grupos (diferentes animais) e trabalhando os dados com data.table ou dplyr:
animal <- clusters(grafo)$membership

Com data.table
library(data.table)

setDT(df)[, id_brinco_rp := as.character(id_brinco_rp)]

df2 <- merge(as.data.table(animal, "id_brinco"), df, by.x = "id_brinco", by.y = "id_brinco_rp")

df2[, id_brinco_un := id_brinco_or[date == min(date)], by = animal]
setorder(df2, id_brinco_un, date)

df2[, .(id_brinco_un, id_brinco)]

Com tidyverse
library(dplyr)
library(tibble)  # para o enframe

df <- df %>% mutate(id_brinco_rp = as.character(id_brinco_rp))

animal %>%
  enframe("id_brinco") %>%
  inner_join(df, by = c("id_brinco" = "id_brinco_rp")) %>%
  group_by(value) %>%
  mutate(id_brinco_un = id_brinco_or[date == min(date)]) %>%
  ungroup() %>%
  arrange(id_brinco_un, date) %>%
  select(id_brinco_un, id_brinco)

Comment: a função distances no grafo do meu caso provocou um "crash" no R. O caso é bem maior que o exemplo, são 1,7 milhões de registros, isso gerou um grafo com 10 elementos e 330 mb segundo o R. Imagino que seja grande demais para a memória que tenho disponível: 8 gb.


Why $g\in F[X]$ by Galois theorem?

Question: Let $F$ a field anf $f\in F[X]$ a polynomial. Let $K_f$ the splitting field of $f$ and $G_f=\text{Gal}(K_f/F)$. Let $g\in K_f$ a polynomial that divide $f$ (i.e. $g\mid f$). Why the fact that for all $\sigma \in\text{Gal}(K_f/F)$, $\sigma (g)=g$, we have that $g\in F[X]$ by Galois correspondance theorem ?
What I see is the fact that $\sigma (g)=g$ then $$g\in K_f^{\text{Gal}(K_f/F)} =\{x\in K_f\mid \forall \sigma \in\text{Gal}(K_f/F), \sigma (x)=x\}.$$
By Galois theorem, $$\text{Gal}\left(K_f^{\text{Gal}(K_f/F)}\big/F\right)=\text{Gal}(K_f/F)\Big/K_f^{\text{Gal}(K_f/F)},$$
but how can I conclude that $g\in F$ ?
Answer: Galois correspondence implies (among other things) that if $G=Gal(K/F)$ then $K^G=F$, so if an element is invariant under all the Galois automorphisms, then it must be in the base field, which in your case means that the coefficients of $g$ are in $F$.

Why $g\in F[X]$ by Galois theorem?


Conditional expectation of product of Bernoulli random variables

Question: Let $\epsilon_1,\ldots,\epsilon_m$ be Bernoulli random variables, i.e. $P(\epsilon_i=1)=P(\epsilon_i=-1)=\frac 12$.
I wanted to calculate (or at least approximate) the following conditional expectation:
$$
E\left(\epsilon^{n_1}_1 \cdots \epsilon^{n_m}_m |\sum_{i=1}^m \epsilon_i=0 \right)
$$
Here $n_1+\cdots+n_m=n$, $n\in N$ and $n_j \in \{0,1,\ldots,n\}$.
Since we have condition that $\sum_{i=1}^m \epsilon_i=0$, then we can say that $m=2k$ is even.
Now, I rearrange random variables:
$(\epsilon^{n_1}_1\cdots\epsilon^{n_k}_k)
\left(\epsilon^{n_{k+1}}_{k+1}\cdots\epsilon^{n_2k}_{2k}\right)$ so that first $k$ of them are 1 and second $k$ of them are $-1$.
Thus,
$$
E\left[\left(\epsilon^{n_1}_1\cdots\epsilon^{n_k}_k\right)
\left(\epsilon^{n_{k+1}}_{k+1}\cdots \epsilon^{n_2k}_{2k}\right)\right]=E\left[(-1)^{\sum_{j=k+1}^{2k}n_j}\right].
$$
And here I am stuck...
Comment: an $n_j$ went missing in the final summation!
Comment: BTW, what is inside the expectation operator looks like a constant to me. So, expectation will be the same constant. Or, likely that I don't understand what's going on? So, let me ask you. expectations are calculated for random variables, what is the random variable in question?
Comment: Thank you. Yes, expectation calculated for the Bernoulli random variables. Since I have assumption that their sum is 0, then the variables are not independent any more. So, I cannot use the fact for independent r.v. that expectation of product is the product of expectations.
Comment: @Robert Israel: I am sorry. I did my rown way.  Eventually, I gess its the same as you suggested, but I did not understand your logic. Could you please show me your way.
Comment: I get pinged every time you ping Robert, I guess, it is because of the space between Robert and Israel. So, please ping him below his answer. I am sure he'll help you out if he's around!
Answer: First of all, these are not really Bernoulli random variables, since those take the values $0$ and $1$, not $-1$ and $1$.  Rather, it's $(\epsilon_i + 1)/2$ that are Bernoulli.
And you do need to assume that $\epsilon_i$ are independent (before you condition on the sum).
Of course $\epsilon_i^{n_i} = 1$ if $n_i$ is even and $\epsilon_i$ if $n_i$ is odd.  So if
$S = \{i: n_i \text{ is odd}\}$, you're asking for $E\left[\epsilon_S | \sum_{i=1}^m \epsilon_i = 0\right]$, where $\epsilon_S = \prod_{i \in S} \epsilon_i$.  Let $T = \{i: \epsilon_i = -1\}$.  If $\sum_{i=1}^m \epsilon_i = 0$,  $T$ has cardinality $m/2$, and all
$m \choose {m/2}$ subsets of that cardinality are equally likely to be $T$.  Now given $T$, $\epsilon_S = 1$ if and only if $|S \cap T|$ is even, $-1$ if it is odd.  Well, that should be enough hints for a homework problem.
Comment: I am sorry for smoll symbols. Here what I've got: I am using definition of conditional expectation through conditional probability. Probability $P=P\left(\epsilon^{n_1}_1...\epsilon^{n_m}_m| \sum_{i=1}^m\epsilon_i\right)={\frac{1}{2^{m/2}}}1/({{m \choose m/2}\frac{1}{2^{m/2}}})$. Now, $E\left(\epsilon^{n_1}_1...\epsilon^{n_m}_m| \sum_{i=1}^m\epsilon_i\right)=P\sum_{\{\epsilon_i,..., \epsilon_m\}: \sum_i\epsilon_i=0}\prod_{i=1}^m\epsilon^{n_i}_i=1/(2^{m/2}{m \choose m/2})\sum_{\{A \subset \{1,..,m\}, card(A)=m/2}\}(-1)^{\sum_{i\in A}n_i}$


How to find the analytical expression for the supporting hyperplane?

Question: In Stephen Boyd & Lieven Vandenberghe's Convex Optimization book we have following set
$$\{x\in \mathbb R^2_+ \mid x_1x_2\geq1\}$$
Now the analytical expression for the supporting hyperplane is given as follows $$\frac{x_1}{t^2}+x_2=\frac{2}{t}.$$ I know that the supporting hyperplane at the boundary point $x_0$ is $a^Tx=a^Tx_0$. (The boundary of the above set is $(t,1/t)$). Further, I know that at $x_0$ the supporting hyperplane is trangent to the set. The tangent to the set at any boundary point  is $-\frac{1}{t^2}$. I want to know how we obtain the following analytical expression for the supporting hyperplane $$\frac{x_1}{t^2}+x_2=\frac{2}{t}$$ Any help in this regard will be much appreciated. Thanks in advance.
Answer: Consider the set $C$ to be the epigraph of $f$:
$$C = \{(x,r) \mid f(x)\leq r\}.$$
An outer normal vector at $(t,f(t))$ is given by
$$\big(f'(t),-1\big)$$
and the supporting hyperplane is described by
$$0=\langle (f'(t),-1),(x,f(x))-(t,f(t))\rangle.$$
Now if your case, $f(x)=1/x$ and so $f'(x)=-1/x^2$.
Consider the point $(t,1/t)$ fixed, and in the boundary of $C$ for your choice.
Then $(x_1,x_2)=(x,f(x))$ is in the graph, where $x=x_1$ and $x_2=1/x_1$.
In this case,
\begin{align*}0&=\langle (f'(t),-1),(x,f(x))-(t,f(t))\rangle\\
&= \langle (-1/t^2,-1),(x_1,x_2)-(t,1/t)\rangle\\
&=(-1/t^2)(x_1-t)+(-1)(x_2-1/t),\\
&=\frac{-x_1}{t^2}+\frac{1}{t}-x_2+\frac{1}{t},
\end{align*}
which turns in what you have.
Comment: Looks fine to me!
Comment: Thank you so much for your answer. I think your answer is a bit difficult to understand therefore I try to explain my own reasoning below. Pick a point on the boundary $(t,1/t)$. The tangent to the boundary is $(1,-1/t^2)$. The normal vector associated with the hyperplane must be normal to the tangent vector. Let the normal vector to be $a^T=[a_1 a_2]$ then we must have $=0$ which results in $a_1=a_2/t^2$. Now if we pick $a_2=1$ then we know that product of $a^T$ with the reference point $(t,1/t)$ is equal to the product of $a^T$ with $(x_1,x_2)$. Therefore ...
Comment: $$a^T[x_1 x_2]^T=a^T[t 1/t]^T$$ $$x_1/t^2+x_2=2/t$$. Is this explanation wrong?
Comment: Please let me know if my reasoning is wrong. Thank you so much.


dont work MultiView and view control when upload project in host

Question: This code is correct in visual studio
But when upload in host and click on Button Error is displayed.

Login failed for user 'WIN-1JU0K094NDD\IWPD_334(loyaltoi)'.
  Description: An unhandled exception occurred during the execution of
  the current web request. Please review the stack trace for more
  information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Login failed
  for user 'WIN-1JU0K094NDD\IWPD_334(loyaltoi)'.
Source Error:
An unhandled exception was generated during the execution of the
  current web request. Information regarding the origin and location of
  the exception can be identified using the exception stack trace below.

client code
            <asp:MultiView ID="mvShowListUsers" runat="server" ActiveViewIndex="0">
                <asp:View ID="VwShowUsers" runat="server">

                            <asp:Button ID="btnAddUser" runat="server" Text="add" CssClass="btn btn-warning" OnClick="btnAddUser_Click" />

connection string :
connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=.;initial catalog=loyaltoi_CustomerDB;User ID=loyaltoi_CustomerDB1;Password=*****;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />

Comment: "The code is correct in Visual Studio". It may well be, but the error clearly states that SQL Server is rejecting the connection, either because the user/password is wrong, or because the user isn't allowed to access the SQL Server from the IP address the server is accessing it from.
Comment: @john
I'm logged in correctly with this connection string
Comment: So from the same IP address as the server the ASP.NET site is running on, that connection string is working outside of the ASP.NET site?
Answer: user or password for login database on host is wrong, or IP Address Database is wrong.
replace Dot (.) by ip addreess of database in "data source=. " connection string and cehck again user ID and password in connection string
Comment: I have no problem logging in. Only the MultiView control during the run has errors. please check my website .go to http://loyalto.ir/login.aspx and set user:aa & pass:1234 and click yellow btn
Comment: maybe Use an already existing login and set is as the user in your Application Pool. Check that the connection you want to open is not already open


Setting up a ssl server socket with signed certificate

Question: I'm trying to make a simple server which listens on a port and authenticates with ssl. I have files
server.crt
server.key
my-ca.crt

obtained with a openssl tutorial (http://www.vanemery.com/Linux/Apache/apache-SSL.html). my-ca.crt is my own CA certificate, server.crt contains the x509 server certificate (signed with my-ca.crt) and server.key is the corresponding private key.
I now don't know how to load these three files in c#; I have something like
serverCertificate = new X509Certificate2("server.crt", "secret_password");
sslStream.AuthenticateAsServer(serverCertificate, false, SslProtocols.Tls, true);

which doesn't work (I get an
Unhandled Exception: System.NotSupportedException: The server mode SSL must use a certificate with the associated private key.

)
but I have no clue how to add the server.key and/or my-ca.crt.
Answer: To use X509Certificate2 in the form
serverCertificate = new X509Certificate2("server.pfx", "secret_password");

you should save certificate in PKCS12 format. See http://www.madboa.com/geek/openssl/#cert-pkcs12 and http://www.openssl.org/docs/apps/pkcs12.html
Comment: i've tried to do it like this:
`openssl req -x509 -nodes -days 365 -newkey rsa:1024 -keyout "temp\signkey.key" -out "temp\signkey.key" -config "openssl.cfg"` and
`openssl pkcs12 -export -out "temp\certificate.pfx" -in "temp\signkey.key" -name "NAME"` but the exception remains. Any idea?
Comment: @Christoph you need include the private key on export process as follow: `openssl pkcs12 -export -out certificate.pfx -in certificate.cer -inkey certificate.key -name "SSL stream
Certificate"` with `-inkey` parameter.


My Site is under DDoS Attack

Question: I hosted my website couponx.com in google cloud. For 24 hrs my site is under DDOS Attack. I have tried every way to get my site back. I spoke with Cloudflare as well. Still, the issue is not resolved. Can anyone suggest me how to stop this?
Answer: Depends, you can check which IP addresses are trying to connect to your site, and manualy block them, try to block also IP range.
Also you can do "under attack mode" if you use cloudflare.
Possibility is also that, you can block countries from where is attack going, but thats really harsh solution and may inpact your traffic.
Comment: Thanks, we did it. Blocked IP addresses.
Answer: The only way to combat a DDoS attack is to have a big enough pipe to absorb it. If you are indeed hosting everything with Google, they should be able to provide you with the required tools.
Take a look here: https://cloud.google.com/armor/

My Site is under DDoS Attack


Obejective-C. Nature of undefined behavior when method is overridden in category

Question: I read this:

Avoid Category Method Name Clashes
Because the methods declared in a category are added to an existing class, you need to be very careful about method names.
If the name of a method declared in a category is the same as a method in the original class, or a method in another category on the same class (or even a superclass), the behavior is undefined as to which method implementation is used at runtime. This is less likely to be an issue if you're using categories with your own classes, but can cause problems when using categories to add methods to standard Cocoa or Cocoa Touch classes.

But I'm interested why it happens. I suspect that it is because how method dispatching works in Objective-C but I wasn't able to find any article that would explain it with categories.
How categories modify method list?
Why it causes undefined behavior?
Answer: The source to the runtime is available.  You can read the definitive truth. :)
In abstract terms, the way the runtime optimizes the method lists for dispatches has changed over time.   Overriding methods via categories has always been sketchy because you are effectively "losing" an implementation when you do that.  If the method being lost is on the core class, it may have implementation details that grub around in the innards of the class in a way that a method loaded later should not do.
So, there is very little effort placed on making the behavior consistent.   Especially if consistency were to cost speed.
Comment: @RobNapier Had some exceptionally long install times this week... ;)
Comment: Also, at some point there were some issues with categories being dynamically loaded into the binary, but not properly flushing the method caches, a long while back in the runtime. Nasty stuff, and while it's been fixed for several years, just another example why you shouldn't do that.
Comment: Two answers in a week? Are you back on SO? You've been missed.


How to implement Pentago AI algorithm

Question: i'm trying to develop Pentago-game in c#.
right now i'm having 2 players mode which working just fine.
the problem is, that i want One player mode (against computer), but unfortunately, all implements of minimax / negamax are for one thing calculated for each "Move" (placing marble, moving game-piece).
butin Pentago, every player need to do two things (place marble, and rotate one of the inner-boards)
I didn't figure out how to implement both rotate part & placing the marble, and i would love someone to guide me with this.
if you're not familiar with the game, here's a link to the game.
if anyone want's, i can upload my code somewhere if that's relevant.
thank you very much in advance
Comment: What have you done so far? any specific issues you are having?
Comment: as for what have i done so far - i tried to start implementing minimax, but i didnt understand how to "represent" **one** move (while it's suppose to be **two**) and save a `List`
Answer: If a single legal moves consists of two sub-moves, then your "move" for game algorithm purposes is simply a tuple where the first item is the marble placement and the second item is the board rotation e.g.:
var marbleMove = new MarbleMove(fromRow, fromCol, toRow, toCol);
var boardRotation = new BoardRotation(subBoard, rotationDirection);
var move = new Tuple<MarblMove, BoardRotation>(marbleMove, boardRotation);

Typically a game playing algorithm will require you to enumerate all possible moves for a given position.  In this case, you must enumerate all possible pairs of sub-moves.  With this list in hand you can move on to using standing computer game playing approaches.
Comment: Yes, it could be slow and game algorithms often have to cope with the exponential explosion of game positions.  Your first friend to help with this problem is the transposition table: http://en.wikipedia.org/wiki/Transposition_table
Comment: i guess you ment to
    `var marblePlace = new MarblePlace(onRow,onCol)`

anyway, is that mean i need to instance all possabile pairs ? isn't that gonna be VERY slow ?
Answer: Rick suggested tuples above, but you might want to actually just have each player make two independent moves, so it remains their turn twice in a row. This can make move ordering easier, but may complicate your search algorithm, depending on which one you are using.
In an algorithm like UCT (which is likely to outperform minimax for simple implementations) breaking into two moves can be more efficient because the algorithm can first figure out what moves placements are good, and then figure out what rotation is best. (Googling UCT doesn't give much. The original research paper isn't very insightful, but this page might be better: http://senseis.xmp.net/?UCT)
Comment: Monte-Carlo can mean a lot of things; UCT is in the broader class of Monte-Carlo Tree Searching (MCTS) algorithms. UCT has an exploration rule, that tell you where to sample next. Usually the UCT tree grows in the areas that are being sampled, and random or pseudo-random samples are performed to get from the end of the UCT tree to the end of the game. This avoids the need for a complicated evaluation function.
Comment: UCT looks like "Monte-Carlo" to me. if not, i didnt got it. can you provide a short example of the UCT algorithm?

How to implement Pentago AI algorithm


View/Find all compressed files on the server?

Question: I need to find all compressed files/folders regardless of file format on a Windows Server 2003 machine.
Search options do not provide this capability.
Is there a way to list/view all compressed files?
Perhaps, this can be done by PowerShell using file/folder attributes and put into a txt file with file location.
UPD:
Under compressed files/folders - I mean files which appear in blue color in Explorer after changing file/folder attribute.
Comment: Can you define what you mean by compressed files? Do you mean all .zip, .rar, .7z, .tar.gz, .etc?
Comment: I mean files compressed with the means of Windows, the ones which appear in blue color in Explorer.
Answer: The compressed indicator is stored in the "attributes" property. This Powershell will report compressed files.
gci -r C:\search\path | where {$_.attributes -match "compressed"} | foreach { $_.fullname }

-- Begin Edit
The file size is stored in the length property, which is in bytes. You can use whats called a "calculated property" to display the size in kb,mb,gb, etc.
$col1 = @{label="Size";Expression={$_.length/1mb};FormatString="0.0";alignment="right"}
$col2 = @{label="Fullname";Expression={$_.fullname};alignment="left"}
gci -r | where {$_.attributes -match "compressed"} | ft $col1,$col2 -autosize

If you want only larger files, say greater than 1MB
gci -r | where {$_.attributes -match "compressed" -AND $_.length -gt 1mb} | ft $col1,$col2 -autosize

Folder size is also possible, a slightly different beast.
Just try google'ing "powershell folder size" lots of posts on how to do that.
There are also many free tools (windirstat) to report folder sizes.
Comment: Perfect! In addition to this, can I somehow get size for each folder/file in the output?
Comment: Incidentally, both 'dir' and 'ls' are actually just aliases for 'gci' and might be easier to remember. Also, I'll add another vote for WinDirStat. It's the perfect tool for viewing file/folder sizes.
Answer: The definition is rather vague as "compressed file" can mean a wide range of files. You have your normal .zip .tar .7z etc. You also have .cab files although I'm not certain how common they are nowdays.
AFAIK, there is no easy way to find compressed files per se. You need to simply define what filetypes you want to find and use the DOS-command dir.
At the root prompt type
dir *.zip *.rar *.7z *.tar /s >> output_file.txt

This will list all the filetypes in all subdirectories and store the output in the file output_file.txt. Then you can go through the "log" and look for what you want.
For more in depth information on DIR - http://www.computerhope.com/dirhlp.htm


Displaying GMT in users Time Zone using DateTime and DateTimeZone not working

Question: Background
I am trying to create an events scheduler that shows a days worth of events to a user. It looks like this.

On the left you can see the 15min time intervals, and underneath each interval is the corresponding unix timestamp.
problem:
Take two users for example.
Gemma is from london which is +01:00 GMT
Françoise comes from Paris which is +02:00 GMT
When Gemma looks at her events schedule each 15 minute row should show ...

a) the time in their timezone and
b) the corresponding unix timestamp

So take the timeslots from 10:00 AM to 11:00 AM GMT at 2016-9-30 for example, they would look something like this.

For Gemma:

11:00 => 1475229600 (10:00 GMT)
11:15 => 1475230500 (10:15 GMT)
11:30 => 1475231400 (10:30 GMT)
11:45 => 1475232300 (10:45 GMT)
12:00 => 1475233200 (11:00 GMT)

For Françoise:

12:00 => 1475229600 (10:00 GMT)
12:15 => 1475230500 (10:15 GMT)
12:30 => 1475231400 (10:30 GMT)
12:45 => 1475232300 (10:45 GMT)
13:00 => 1475233200 (11:00 GMT)

My Code
Here are my functions which generate the time slots
/**
 * intervals
 */
public function getTimeSlots($year, $month, $day, $start_time = '06:00', $end_time = '20:00')
{
    $date = $year . '-' . $month . '-' . $day; // 2016-9-30
    $unix_base_time = $this->getUnixTimeStamp($date); // unix timestamp for 2016-9-30 00:00

    $seconds_start = strtotime('1970-01-01 ' . $start_time . ' UTC'); // 21600 seconds
    $seconds_end   = strtotime('1970-01-01 ' . $end_time . ' UTC');   // 72000 seconds

    while ($seconds_start <= $seconds_end) {
        $slots[$unix_base_time + $seconds_start] = $this->getTime($date, '+' . $seconds_start . ' seconds');
        $seconds_start = $seconds_start + 900; // plus 15 minutes
    }
    return $slots;
}

/**
 * timestamps
 */
public function getUnixTimeStamp($offset = 'now')
{
    $date = new DateTime($offset, new DateTimeZone('UTC'));
    return $date->format('U'); // returns a unix timestamp
}

/**
 * time
 */
public function getTime($date = 'now', $offset = 'now')
{
    $date = new DateTime($date, new DateTimeZone($this->session->userdata('time_zone')));
    $date->modify($offset);
    return $date->format('H:i');
}

If I var_dump the output I get the following:
array(57) {
  [1475215200]=>
  string(5) "06:00"
  [1475216100]=>
  string(5) "06:15"
  [1475217000]=>
  string(5) "06:30"
  [1475217900]=>
  string(5) "06:45"
  [1475218800]=>
  string(5) "07:00"
  etc......
}

The unix timestamp is correct, but the times are displaying as GMT and not the users time zone!
So obviously I am doing something wrong in the getTime() function.
I can't work out why it is returning the time ('H:i') as GMT when I am clearly injecting the DateTimeZone object with the users timezone passed as an argument.
Comment: A few additional comments that are unrelated to your answer. Look into DateTimeInterval. You can generate a start date and end date as a DateTime object and compare them with `<`. You can then add a date time interval to your start date for each iteration. That way you don't have to mix `strtotime` and `DateTime`, but do everything with `DateTime` with in my experience is less error prone.
Comment: Dealing with dates is hard. There are a lot of pitfalls (leap year, leap seconds, etc). `DateTime` isn't easy to understand, but once learned it's an incredible useful tool and saves you from a lot of frustration.
Comment: Great advice, going to look into it now. This is proving more of a challenge then I expected.
Answer: When creating a new DateTime object the timezone that you pass in is considered the timezone of the passed in date. In your case you are telling DateTime to interpret the seconds once as GMT+1 and once as GMT+2.
Try the following instead:
// our $date is in UTC because we derived it from unix timestamps
$date = new DateTime($date,
       new DateTimeZone('UTC'));
$date->modify($offset);
// update the timezone. The time will be interpreted accordingly.
$date->setTimeZone(new DateTimeZone($this->session>userdata('time_zone')));
return $date->format('H:i');


If $X\sim exp(\lambda)$ what is the PDF of $X^2$?

Question: If $X\sim exp(\lambda)$ what is the Probability density function of $X^2$?
I'd like to know how to calculate it, and what is the way...
Thank you!
Comment: probability-theory, statistics, really? @Tunk-Fey.
Comment: @StefanHansen Feel free to edit if I made mistakes. :)
Answer: We have $X\sim$ exponential distribution $(\lambda)$. The CDF of $X$ is
$$
F_X(x)=\Pr[X\le x]=1-e^{\large-\lambda x}.
$$
Let $Y=X^2$, then the CDF of $Y$ is
$$
\begin{align}
F_Y(y)&=\Pr[Y\le y]\\
&=\Pr\left[X^2\le y\right]\\
&=\Pr[X\le \sqrt{y}]\\
&=F_X(\sqrt{y})\\
&=1-e^{\large-\lambda \sqrt{y}}.
\end{align}
$$
Using the CDF of $y$, we can easily obtain that $Y\sim$ Weibull $\left(\frac{1}{2},\frac{1}{\lambda^2}\right)$. The PDF can also easily be found using
$$
f_Y(y)=\frac{d}{dy}F_Y(y).
$$
Comment: @Yoar You can skip it. All you need is only the PDF of $Y$, which can be found from my answer.
Comment: What is Weibull $\left(\frac{1}{2},\frac{1}{\lambda^2}\right)$??
Comment: I saw your edit - we didn't learn it :-(
Comment: @Yoar Click the given link. It's Weibull distribution with parameters $k=\dfrac12$ and $\lambda=\dfrac1{\lambda^2}$ according to Wikipedia notation.
Comment: Yes, I clicked on the link, but we didn't learn it...
Can I skip it? or I must mention it?
Comment: So the PDF is: $$f_Y(y)=\frac{d}{dy}F_Y(y)??$$ This is the final answer?
Comment: @Yoar Yup! Just find the derivative of the CDF. It's easy job.
Comment: So it's: $$(1-e^{\large-\lambda \sqrt{y}})'??$$
Comment: If yes, we get something wired: $$\frac{\lambda e^{-\lambda\sqrt y}}{2\sqrt y}$$
Comment: @Yoar Just click the link of Weibull and plug in $k=\dfrac12$ & $\lambda=\dfrac1{\lambda^2}$ to the PDF of Weibull.
Comment: I try, but I didn't found a place that I can put those values...
Answer: Hint: One way that you could find this would be to find the cumulative distribution function for $X^2$, then use it to find the probability density function.
To find the CDF for $X^2$, note that $X$ is non-negative; so
$$
P(X^2\leq x)=\begin{cases}0 & \text{if }x<0\\P(X\leq\sqrt{x}) & \text{if }x\geq0\end{cases}.
$$
(If we didn't have a non-negative random variable, we would have to be more careful here; in fact, we would get
$$
P(X^2\leq x)=\begin{cases}0 & \text{if }x<0\\P(-\sqrt{x}\leq X\leq\sqrt{x}) & \text{if }x\geq0\end{cases},
$$
which then simplifies to our answer by noting that in that case, $P(-\sqrt{x}\leq X\leq\sqrt{x})=P(X\leq\sqrt{x})$ for $x\geq 0$.)
Once you've found the CDF, do you know how to find the density?
Comment: The latter is correct.
Comment: I don't think so, I'd like to get help from you...
Comment: Remember that $X\sim exp(\lambda)$ and I need to use this fact...
Comment: Obviously, you'll need to use the specific distribution.  But given the method that I've pointed out, this will not be very difficult.
Comment: Please tell me if I'm right: $$X^2\sim exp(\sqrt\lambda)$$ Right??
Comment: Or this: $$\frac{\lambda e^{-\lambda\sqrt y}}{2\sqrt y}$$ Please tell me which one of them is right.... Thank you!
Answer: If $Y=X^2$ and $u$ is a bounded, measurable function, then
$$
{\rm E}[u(Y)]=\int_0^\infty u(x^2)\lambda e^{-\lambda x}\,\mathrm dx.
$$
Now, do a change of variables with $y=x^2$ to obtain something of the form
$$
\int_0^\infty u(y)v(y)\,\mathrm dy
$$
for some function $v$ (to be determined by you) and conclude that the density of $Y$ is $y\mapsto v(y)\mathbf{1}_{y>0}$.
Comment: Read the last sentence. The density of any random variable $Y$ is the unique function $v$ satisfying ${\rm E}[u(Y)]=\int u(y)v(y)\,\mathrm dy$ for all bounded, measurable $u$.
Comment: But i need to find the PDF, not E()....
Comment: I still not understand how I'm getting from it the PDF, I don't understand what I need to do....
Comment: Do you know how to do a change of variables of the first integral by putting $y=x^2$?
Comment: Yes, but I don't understand how does it's helps me...
Comment: It helps you the following way: when you have done the change of variable, and arrived at an integral of the form $\int_0^\infty u(y) v(y)\,\mathrm dy$ where $v(y)$ can be _anything_, then you may conclude that $y\mapsto v(y)\mathbf{1}_{y>0}$ is the density of $Y=X^2$.


Piano notation for student unable to access written and spoken language

Question: I am working with a student in with a developmental delay. He basically cannot understand spoken or written language at all, so he has to learn by observation.
He has expressed much interest in music, so I'd like to explore if he can possibly learn to play piano. When I studied piano, I had to learn using the traditional staff notation. I think the teacher chose this because its what has been used for centuries, that is what is found in music books sold in the music stores, and not because it is easy or intuitive. I'm not one to regard something as "best" just because it is mainstream. I think in his situation, having something he can grasp quickly and will get him started and interested takes priority over being traditional.
Is there another notation system I can consider starting this student on, where the symbol-to-key correspondence is easy to comprehend the logic of?
Comment: There's always the possibility to teach piano playing without reference to those pesky dots. It wouldn't be the first time someone didn't read music - in any form!
Comment: Why not try by ear.  Just learn to play then worry about "reading" later?
Comment: I don't see the benefit of learning an easy-to-grasp notation, if you find no scores afterwards according to that. Somewhat this reminds on the topic of artificial (synthetic) languages: sure they are easy learn, but how to apply them afterwards (outside of a potential messenger group bubble)?
Comment: I can think of dozens of possible ways forward. The problem is we need to know in detail what the student can and cannot do. Do they have manual dexterity? Can they hum a tune? Can they recognise a tune as belonging to a favourite TV programme? Might they enjoy simply hitting a drum or a xylophone at random?  What is their general cognitive ability? Without a full assessment (someone must have done one) it's impossible to say what will work.  The way forward is experiment. Music is about sound before anything else.
Comment: 1. I don't understand why the question was closed. I see no comments suggesting the reason. 2. I agree with Tim and ggcg. Music notation is an abstraction we use to communicate and comprehend music _intellectually_. If the student has trouble to understand language, then there is no point to bother him with notation. Rather let him learn by ear, by demonstrating how to play, maybe by viewing videos. Also, if he has poor manual dexterity, maybe piano is not the best instrument? Perhaps singing (without words) would come more naturally?
Comment: How about [Synthesia](https://synthesiagame.com)? Or one of those keyboards with lights in the keys?
Comment: I like the other comments here but consider, in parallel, teaching something without sheet music. A favorite learning vehicle: Miles Davis' "So What." Play the bass and chords and let the student improvise. The form is modal, over the chords Dm and Ebm. I encourage the student to experiment with interesting rhythms and melodies on all white keys over the Dm and on all black keys over the Ebm. It works!
Comment: @guidot - given that OP's student can't understand written language, why woud he understand dots better?
Comment: @chasly-supportsMonica The student can sing songs, hum classical music, appears to have nearly perfect pitch (except for really high notes), is facinated with symbols and writing. Quick to spot patterns. Has poor manual dexterity.
Comment: @user1079505 Maybe I will post a new question with suggestion on what instrument for someone with poor dexterity. I also don't know why it is closed, I am not looking for opinion, I think there can be very factual evidence to support answers, as we see below.
Comment: @user1079505 it's closed because any answer to this will be equally valid and will just generate list of alternative notations that are all equally valid alternatives. This is a good discussion to have and figure out the path for a student, but it's that a discussion with no objective answer which we typically close.
Answer: This might be more like a comment, or it may answer the actual question behind what you literally wrote. You decide.
You seem to assume a musical scenario with (1) a composition, (2) a performer, (3) an audience. Would it be possible to ditch that whole preconception and think about music in other ways? Why does there have to be notation? What is the thing that is supposed to be communicated using notation? Is that really the only way? Is that really the only possible purpose and goal? Music can be interaction. Music can be playing like a game or child's play with toys. Music can be a conversation. Music can be social. Music can be made in a group. Music can be made on the spot, improvised. Let's sing together, play together, make sounds together. Pitches, melodies, rhythms, harmonies, words, impressions. Real music.
Have you ever participated in music-making any other way than "some mastermind above me tells me what to do, and then I execute the given instructions?" Have you ever said anything of your own to another person musically? Have you had a musical conversation? Musical game? Musical fun and messing around? Have you tried to add something to existing music? Repeat what you hear? Repeat what you hear, but with some deliberate variations? Surprise someone musically? Annoy someone? Make someone laugh? Make yourself laugh? Cry? Dance!?
Sorry for ranting, but I have heard that children these days don't know how to play anymore. They don't take everyday objects and imagine them to be something else, see how other kids react and let their imagination flow freely. They're so used to pre-programmed stories and rules, everything has to be a predefined and pre-imagined detailed product made for that exact playing situation. A similar development has happened with music for a long time already. You don't just take an instrument and start, well, playing. Music has to be legitimate and proper, officially recognized pieces and genres. If you make a sound, you need to make sure that it's a socially acceptable, respectable sound! Or at least one that gets you upvotes and Likes.
obTopic / Re: notation
In the Suzuki method, at least at first, no notation is used. I haven't been there, but I've heard from friends and relatives that for a small child they might use a postcard or other picture as "notation" that's used (IIRC) simply to have something to look at, to assist remembering, if needed.
Figurenotes
There's a thing called figurenotes, which "uses color and shape to show pitch and rhythm".

I'm personally not a huge fan of the goal centered on producing something that's correct. In that thinking, success means being able to correctly obey given instructions, and thus gain social acceptance. But I suppose it can be very helpful for disabled people, who often (so I've heard) suffer from anxiety caused by not being able to follow what's happening around them, in the "normal" people's world.
Comment: This answer is so good I'm gonna print it and study it and learn to recite it to anyone who asks a similar question.
Comment: The Suzuki method is what came to my mind. Or just listening to simple melodies and watching the teacher play them, and then trying to repeat it.
Answer: Provided writing out scores for the student is an option, I suggest creating a notation that matches an image on the "score" with the same image placed on the keyboard.
For example, you could purchase "inventory circle labels" in a variety of colors. The score would be a sequence of variously colored labels which would correspond to keys with the same color labels.

In order to accommodate duration, you could place a row of adjacent labels (cut for partial beats).
I would begin by placing the "notes" in a single row.
If this works for the student, then next steps could include adding a second row for the left hand and/or displacing the "notes" in space to emulate their positions on a staff.
As you develop a sense of how the student processes this notation, you could continue evolving it toward a more standard form or some other arrangement tailored to the student's needs and abilities.
Allowing for the possibility the system can evolve in the direction of standard notation, you could eventually try colorizing more traditional scores. Score-writing software can do this. For example, here's a two-handed score created with MuseScore.

The images comprising the score, of course, need not be colored dots. They could be any objects familiar and easily identified by the student.
Comment: Isn't this wasted effort though? Because if your brain associates the notes with colours and then suddenly they are gone, all the effort you invested in to learning them been wasted. At least if you're only playing by ear you're not wasting time on something that you won't keep on using. I feel that those stickers that literally show the note on the staff would be better in this respect.
Comment: I guess what I'm skeptical of is the assumption that upon graduating from coloured dots to coloured notes, the student will learn to associate the staff positions to the keys using colours as the intermediary. But if the note remains coloured, why would they ever pay attention to the staff position? I know I wouldn't. There would be no need to because you already have something that works.
Comment: @DKNguyen Well, if accidental rules (colours only present on first instance of each note) and then, eventually, fingering rules (colours only present on non-obvious notes) apply, it might be easier to make the shift.
Comment: This idea has worked with youngsters for me. A couple of books 'Through the Rainbow' from memory. C=red, D=orange, etc. 7 colours, 7 notes.
Comment: @DKNguyen Well said. My post should not have suggested a direct move from colored dots to colored notes on the staff. I've updated to suggest how the system might evolve.
Comment: @wizzwizz4 I suppose it could work if you increasingly interspersed black notes within the coloured notes until only black notes remain. But you bring up a good point about accidentals. Those will throw a wrench into things. And I hope the student has good colour differentiation. Because in the image above, those blue and purple notes look nearly identical to me and the yellow note might as well be invisible. I only know its there because of the black line on either side.
Comment: @wizzwizz4 Actually, taking a second look. The blue and so-called purple note are on the same line so should be the same colour but they still both seem to have different shades to me!
Comment: @DKNguyen My brain's doing that too. It's weird, because I think they are the same colour.
Answer: Traditional western musical notation has the advantage of having been subject to lots of practical tests. It can range from the simple lead sheet with the melody written out and the accompaniment indicated symbolically. From experience assisting in teaching a music kindergarten for a few years, I'd say that a single staff (probably treble clef) is pretty easy to understand. Time runs from left to right and pitch from bottom to top. One need not learn lots of highly complex notation at first but the foundation for doing so will be there.
Answer:
I think the teacher chose this because its what has been used for centuries, that is what is found in music books sold in the music stores, and not because it is easy or intuitive.

A writing system must be consistent and effective, that doesn't mean that it has to be intuitive (in fact, it usually can not): is the written latin alphabet an intuitive writing system? Certainly not - in fact, writings based on ideograms like Chinese, while considered complex and unintuitive to "us" latin-writing people, are conceptually more intuitive.
Music is a very complex language, and the traditional staff notation is a convention that has been developed, evolved and tested along centuries. It's not immediate, nor easy, but is ironically more intuitive than latin characters: the horizontal position shows progress in time (usually in a consistent way, as longer notes have wider margins after them), the vertical position indicates the pitch.
It is probably not the "best" system, but I doubt there would be just one.
Take for instance the "piano roll" visualization in many music production programs (this is museScore):

This is clearly more intuitive than staff notation, as the pitch is pretty clear and time positioning is consistent, but it has its flaws: it requires a lot of space, you can easily be "lost", and using the chromatic scale can be confusing since we normally use a tonal system.
That said, also considering the spoken/written handicaps, the first thing to keep in mind is to use the music as it should: by listening and performing.
Before approaching the reading part, there are more important aspects that should be explored and understood first: pitch, time, dynamic.
Assuming that the pupil is able to vocalize in some way, that should be probably done through singing and imitation - exactly as we all do when learning to speak.
Start with short, easy melodies (if he already knows some, use them) with very few notes - avoid tunes that use an extension greater than a fourth or a fifth at the beginning.
Even a simple C, D, E, -, E, D, C, -.
Try to do them at different heights, even very different, so that he can begin to understand the difference of listening and singing/playing very high or very low notes. Imitation can be done with your singing, and then when playing and singing: sing a simple 3-4 notes tune, try to sing them together, then sing the same tune while playing, let him try the same, then do the same tune starting from a different note on the piano.
Then there's the matter of time, both as speed and duration. You can use the same simple tune and sing/play at different speeds, or at the same speed but with shorter and longer notes.
Finally, as the above, but with different dynamics.
You can also do this while "silently" beginning to use the color method Aaron proposed, which is a very good suggestion and is actually widely used for any child. Just put those stickers on the piano, doesn't matter if you don't use them from the beginning; you can
After some time, you can put those stickers on paper, and try to show the correlation while playing.
Let him try to create its own tunes by giving him stickers to put on paper, or, even better, drawing with pastels or colored pencils. This is very important, because it allows a better awareness of what is happening and what can be possibly done.
Consider that once the basic concepts have been grasped, you can also try to play short tunes and see if he's able to "write" them down using colors (maybe you can do the opposite too: he plays some notes, and you draw them).
Answer:
He basically cannot understand spoken or written language at all, so he has to learn by observation.

I feel there is a non-negligible likelihood that you are underestimating your student's capability in learning sheet notation. It is certainly true that we cannot start with sheet notation for him, but I do suspect that he still can eventually learn sheet notation!
From what you said, I surmise that he is able to learn a new piece by imitating you. And you should continue to let him learn new pieces this way. However, this does not preclude you showing him the score (in standard notation) after he has learnt a piece, and show him the correspondence by pointing to the notes as you play them! If you focus on just the notes and duration, (ignoring the notation for the time signature, dynamics, ornaments, and so on), the notation is actually not hard to pick up.
You can try using notes with simple duration (1,1/2,1/4,1/8,1/16) first, and notate other durations using ties, and once he has gotten that you can show him what beamed notation means by starting with a score using simple-duration notes that he has already understood and changing the adjacent quavers appropriately, perhaps by first drawing a wavy line through the flags to join all the poles up, and then erasing and straightening that wavy line.
Similarly for dotted notation. For example, starting with a score using simple-duration notes that he has learnt, you can first circle all the instances of tied pairs of notes where the second has half the duration of the first, and then erase the pole and flag of the second (still leaving the head and tie there), and then replace that head and tie with a little dot next to the first note.
Dynamics can be learnt later, by showing them in sequence:
  pp < p < mp < mf < f < ff
And by starting from a simple score that he has learnt (i.e. after the above steps) and adding just two or three such dynamic markings and playing the piece with those dynamics. Crescendo and decrescendo may take a bit more time to convey without words, but should also be doable.
In general, I believe it should not be hard to grasp the meaning of various notations if it is conveyed via a sequence of simple transformations from a simpler base notation. The key is to introduce new notation step by step and not start from a modern published score that is filled of notation! There may be some notation that cannot be conveyed this way, but I think we do not lose much by not learning them. For example, the time signature can be basically ignored.
Answer: I think you have a kind of disconnect here.  If the kid can't learn to read printed words, then it's unlikely that printed notes (of any kind) will be of any use.  There's really no difference between reading letters to form words and reading notes to make music.  Both involve translating arbitrary, abstract glyphs into concrete actions.
Drop the idea of teaching notes.
Find a simple piece of music the kid seems to like.  You'll have to play songs and watch the reactions.
Once you've got something the kid is enthusiastic about, sit down at the piano together with the kid.  Play part of the song.  Something that the kid obviously likes.  Ask the kid to try playing it.  If need be, place the kid's fingers over the first keys and press to get across the idea that pressing the keys makes the noises of the music.
You're going to have to show the kid how to play the music by doing it together.  It'll probably take a lot of repetition to get the sequence of notes across.  It may even take a while for the kid to recognize that pressing the keys is what makes the sounds and that the order of the keys is what makes the music.

Teaching music (or anything) by hands on demonstrating how to do it is going to involve a lot of close contact.  Be sure that the kid (and the kid's parents) are OK with that.
Be sure that the kid really wants to play music before you try to teach it.
It's going to take a lot of patience.  There will be lots of wrong notes and as many misunderstandings.  Never, ever flip out over a wrong note or a whatever.
Answer: Does the student understand/respond to colors?  Or sizes?  Or shapes?
Perhaps, listening to a simple piece of music (Twinkle Twinkle Little Star, for example), then playing it on a keyboard with color-coded keys, to create something that can be visually matched.  Then, if that works, try putting the colors on a piece of paper - nothing special, just colored blobs or scribbled blocks - to see if the student can follow...a red blotch means the red key, a blue blotch the blue key, etc.
If that works, then refine it still further, and put size to the blotches.  A wider blotch means a longer note, for example.
It's a bit crude, and certainly simplistic, but it eliminates the need for standard notation.  If the student responds well to this, then you could go further and try putting the blotches on a staff, then making the blotches note-shaped, then putting the note-blotches in the appropriate lines/spaces on the staff, etc.  Unfortunately I don't have any ideas for how to make the connection between wider blotches and longer notes in notation, such as half or whole notes, but perhaps you could come up with something there.
It doesn't have to be colors, it could be shapes or anything else the student responds to and understands and can make connections with.  Perhaps even a combination (maybe instead of regular and wide blotches, it could be circles and triangles and squares).
If the student responds better to touch, then perhaps even this crude notation isn't for them...perhaps you could equate certain physical sensations to the notes.  For example, a tap on the left shoulder becomes C, a tap on the elbow becomes G, a stomp of your foot with a tap could mean a longer note, etc.
Be creative!  Let your student guide you...if they truly have an interest, they will find a way.  :)
Answer: I am a mathematician working in time-frequency analysis (and a keyboarder, having a few instruments, and loving improvisation).
I may suggest to try to download the STX software *free, from ARI, the Acoustic Research Institute of the Austrian Academy of Science (google for STX ARI, or STX, ARI, Peter Balazs, the director of this institute, and my former PhD student).
This real-time spectral analyzer allows to produce pictures from sound, so this goes the other direction, but helps to get a good understanding... of the meaning of a decision taken at the keyboard on the sound and coupling it with the visual impression of a score-like graphical notation (so in a way we undo to notation).
Also the gaborator (also based on work of my students) is interesting:
www.gaborator.com   (here you can upload your WAV file, so it it NOT interactive).
Hans G. Feichtinger
email@example.com
Comment: How does this relate to teaching a developmentally delayed student interested in piano?
Answer: Several people answered this in comments, but strangely no one put it in an answer yet:
Just play by ear, i.e. literal imitation. Commit every piece to memory. This is not a bad method for any kid. It's a part of the Suzuki method that was already mentioned as an aside. It places a different focus than sheet music based teaching, but that's ok. Someone learning that way will probably learn to play fewer pieces, better, rather than a lot of pieces, just ok. They will have a better mental connection between pitches and what they need to do to make them sound than someone who primarily plays from sheet music.
In the past it might not have been a viable method to learn exclusively by listening, but today you can access recordings of pretty much every piece you might want to learn, so it's no real problem if even a pretty serious musician never learns any music notation.