Convolution of exponential and uniform distribution-why is there not four possibilities to consider

Question:
Let $Y$ be an exponential random variable with parameter $λ$ and $X$ be a uniform random variable on $[0,1]$ independent of $Y$. Find the probability density function of $X+Y$:

I know that where $X+Y=a$ the solution involves two possibilities, one where $0\le a \le1$ and the other where $1\le a $.
My question is, why is it not also dependent upon where the exponential random variable intersects $X+Y=a$? I will illustrate with a diagram:

Here the purple line is $X+Y=a$ and the red curve is the exponential random variable. As you can see, $a$ starts after the red curve.
Another possibility is this:

Here $a$ starts before the red curve.
Why would not have to consider four possibilities, two where $0≤a≤1$ depending on the positioning of $a$ to to the exponential random variable, and two where $1≤a$ depending on the positioning of $a$ to the exponential random variable?
Comment: 1) $u$ is commonly used as the dummy variable in integration. It does not matter if you use any other variable, as long as it is different from the variable $a$, which is the argument of the resulting pdf. 2) $1$ is the indication function, $1_A(x) = 1$ when $x \in A$ and $0$ otherwise. 3) After putting in the definition, it help you to get the support of the integrand, by noting that $1_A1_B = 1_{A\cap B}$
Comment: Did you already find that convolution? It surely depends on $\lambda$.
Comment: In general if $X,Y$ are independent then $f_{X+Y}(a)=\int f_X(a-u)f_Y(u)\;du$. Applying that here leads to $f_{X+Y}(a)=\int1_{[0,1]}(a-u)1_{[0,\infty)}(u)\lambda e^{-\lambda u}du=\int_{\max(0,1-a)}^{a}\lambda e^{-\lambda u}du$
for $a>0$. For $a<0$ the integrand is $0$. Especially the expression
$\max(0,1-a)$ asks for discerning the cases $a>1$ and $a<1$.
Comment: No, I didn't find it myself, but from the answers here:https://math.stackexchange.com/questions/1439969/finding-convolution-of-exponential-and-uniform-distribution-how-to-set-integral it didn't seem that it depended on that, would you be able to explain a little more?
Comment: Would I have to consider four possibilities, two where $0 \le a \le 1$ depending on $λ $ and two where $1 \le a \le 2$  depending on $λ $?
Comment: I always find it annoying when someone refers to "an exponential distribution with parameter $\alpha.$" Does that mean $\alpha$ is the rate or that $\alpha$ is the expectation? I.e. $$ \begin{align} & e^{-\alpha x} (\alpha\,dx) \quad \text{for } x\ge0, \\ \\ \text{or } \quad & e^{-x/\alpha} (dx/\alpha) \quad \text{for } x\ge 0 \quad \text{?} \end{align} $$ Both conventions are used. $\qquad$
Comment: Here I am pretty sure it is the former. $\lambda e^{-\lambda y}$
Comment: @drhab, I am not familiar that notation you used for the integral, would you be able to explain how it works? - $1$. Is there a reason that $u$ is being used in the convolution rather than $x$ or $y$? $2$. How do those expressions in parentheses under the $1$'s work? $3$. How do they disappear and turn into  the bounds of that last integral?
Answer: You have two piecewise functions, one nonzero on $[0,\infty)$ and the other nonzero on $[0,1]$. This is all that matters. When sliding the uniform $\text{pdf}$, you have three regimes: $[0,1]$ before $0$, $[0,1]$ over $0$, and $[0,1]$ after $0$. The first regime can be trivially ignored, and in fact there are just two cases to be considered.
The valuations of the $\text{pdf}$ are not relevant in the case analysis.
Answer:
I know that where $X+Y=a$ the solution involves two possibilities, one where $0≤a≤1$ and the other where $1≤a≤2$.

This is wrong. For any positive value of $a$ there is a corresponding pair of values ($X$,$Y$).
Comment: Thanks @rrv, I edited it to say $1≤a$
Comment: @agblt. Please kindly note that your new version "I know that where $X+Y=a$ the solution involves two possibilities, one where $0≤a≤1$ and the other where $1≤a$." is still wrong. For any positive $a$ there are infinitely many possible values of a pair $(X,Y)$.


PHP Beginner: Where and how are objects stored?

Question: In an app written in PHP (e.g., a social network), let's say that 10 users (signed-in) are browsing the website.
In PHP code, there is "user" object created to store users data and to pass values to other functions and classes.
Question: When these 10 users go to user.php, which has code to create "user" object, how are these objects stored in memory in PHP? Do they not conflict? Is each one of the "user" objects are uniquely stored in the memory or would one be overwritten by another?
For example, user a visits first so object "user" contains his/her data but when user second visits, the "user" object in memory is overwritten so when first user calls the object, it's the second users data retrieved.
Or, is it unique?
I want to understand object in PHP as a newbie, please explain it simply because none of the web pages I found regarding OOP explains this.
Answer: PHP is a CGI application, that means, it's being started and terminated on each request.

a client sends a request to the web server
the server starts PHP and passes the request to it
PHP allocates a chunk of memory for your script
your script is being executed, all objects it creates are stored in that chunk of memory
you script generates some html, this html is sent to the client
the memory is being freed and PHP is stopped

If you have 10 clients requests coming at the same time, 10 copies of php will be started and 10 independent memory chunks will be used. So, no, objects from different requests do not interfere.
(Note: this explanation is deliberately simplified, there are actually different php setups and persistence options).
Answer: The best way to learn this is to install php on a local PC or Mac and then create a php info file
<code><?php
phpinfo();
?>
</code>
... then open it in your browser...This will show you all the settings on your server for php and other things.
Regarding the answer to your question, it's a bit more of an advanced topic for a newbee, but php sessions are what do the work of keeping user info. They usually work off a session id which is unique to the user for a small amount of time, and they dynamically allocate memory or disk space/flat files or a database (again see the settings above) to store the relevant data.
Unfortunately for you none of this is "automatic" you have to create the scripts to make it happen and behave in the way you want. Asking questions on this site is a good start...
Answer: You need to look at object design patterns in relation to php which is quite a big subject in its own right. There is an excellent Apress book called 'PHP Objects, Patterns and Practice' which explains some of the more common patterns and how you might use them and would be a good place to start learning.
Answer: The users information is all stored in a database, the user object will have to retrieve this data each time the page loads.
The object know what user is looking at the page because of their session_id, which in a nut shell is a random id given to you, stored in a cookie.
using the session_id you can retrieve the correct information form the database.


OSX/ObjectiveC: List all the objects created in the heap by my app

Question: Is it possible to list all the objects that lives in the heap and have been created by my app?
I think it's possible, Instruments do something like this.
Comment: Of course it is, `free()` and `malloc()` need to store their data somewhere...
Answer: Instruments
In instruments, choose the Allocations template in the Memory system and you'll have the ability to look at all objects that are either live in the heap, or which have ever been allocated in the heap.
There's reasonably good filtering in here as well, and if you have lots of memory, or an app that doesn't create/destroy a lot of objects, you can even track reference counts.
Code
There isn't an API to look into the malloc/free data structures officially, so if you have a compelling non-debugging need to look at individual allocs, you're probably looking at replacing the standard memory allocation routines with a specialized instrumented version (kind of like what guard malloc does -Guard Malloc).


How to fit a distribution with an "10 and more" category at the bottom?

Question: I want to fit a distribution to some data to sample from it in a subsequent simulation. There are  I got a dataset that looks somehwat like this:
dat <- data.frame(num=1:10, value=c(6000, 2800, 1000, 230, 142, 53,
                                    32, 21, 10, 110))

Every entry of "num" refers to a non-negative discrete observation, except the last one (in this case num=10) which is a category of "10 or more". The column "value" refers to the frequency of that observation. The data is extremly right skewed, but an exponential distribution seems to be a decent fit if you ignore the last row of the data. (note: this isn't the real data)
I happen to know the maximum value that can occur, let's say that one is 500. So in other words I know the area under the curve between 10 and 500, which is the frequency of the last category, and have exact values before that. How do I fit an exponential (or other fitting) distribution to this data that satisfies these constraints?
So far I only managed to fit an exponential distribution to the first 9 columns and predict values for the subsequent values of 10-500 like this:
m.exp <- nls(value ~ I(a * exp(b * num)),
             data = dat, start = list(a = 1, b = 0), trace = T)

new_dat <- predict(m.exp, newdata = data.frame(num=c(9:500)))

This does work somewhat, but the area under the curve between 9 and 500 obviously is not correct (e.g. it is not equal to 110). Another solution I implemented is fitting a triangle, which does satisfy the area under curve and the maximum value, but the distribution would be far off from the prior distribution of values.
Edit:  Is it possible to fit a distribution that has 112 (the frequency of "10 and more") as the area under the curve between the values 9 and 500, which roughly follows the same distribution as the values before it?
Comment: The general idea is maximum-likelihood fitting of *censored* observations - when you have a parametric distribution in mind, of course. See e.g. https://stats.stackexchange.com/q/133347/17230.
Comment: So the first vector is of observations, the last item being a bin for counts between 10 & a known upper bound of 500; the second of their frequency? The exponential distribution is for a continuous random variable with no upper bound.
Comment: Exactly correct. I know that exponential distributions don't have an upper bound, what I am trying to ask is: Is it possible to fit a distribution that has 112 (the frequency of "10 and more") as the area under the curve between 9 and 500, which roughly follows the same distribution as the values before it?
Comment: Thank you for that reference. I see that this works for survival data, but it's unclear to me how I could use this for the present case.
Comment: Take a look at the fistdistrplus package.
Comment: @friendlystatsguy I'll let you in on a secret -- survival data don't actually *know* they're times; they're just  numbers, so they can't complain about it. None of the survival models actually know those are times they're getting either. If you use some other censored variable than time in a parametric survival model, *everything still works exactly as it should*, because all it is is fitting distributions to data with censoring. There are a number of examples (of using survival models to fit censored data that are not survival times) on site here.
Answer: The data you showed seem to be quite well modelled by a geometric distribution, expect by the truncation (which seems to be expected).
dat <- data.frame(num=1:10, value=c(6000, 2800, 1000, 230, 142, 53,
                                                                        32, 21, 10, 110))

suppressPackageStartupMessages(library(tidyverse))

avg <- dat %>% summarise(avg = weighted.mean(num, value)) %>% pull(avg)

p <- 1/avg

dat <- dat %>% mutate(expected =  dgeom(num - 1 , prob=p), prop = value/sum(value))

dat %>%
    gather(measure, value, expected, prop) %>%
    ggplot(aes(x = num, value, fill=measure)) +
    geom_col(position = 'dodge') +
    labs(title = 'Expected and actual counts oberved for the num variable')

Created on 2019-11-29 by the reprex package (v0.3.0)
Comment: Could you explain how you determine the data are "quite well modeled" by a geometric distribution?  Please don't forget that you *must* account for the above-10 group: if its count isn't very accurately reproduced by the fitted geometric distribution, then using that distribution to extrapolate into the above-10 group (in a simulation, for instance) would be highly suspect.
Comment: The data I posted here was completely arbitrary and does not really represent the data I actually have. I was just trying to illustrate the problem I am facing. I sadly can't share the actual data here. The truncation *is* the problem here. I can easily fit a distribution to the other values
Comment: I was waiting for me to get home to perform the requested simulations. If these data are not representative of your case I can try and delete the answer.
Comment: If you can show me how you wanted to draw values from the "10 or more" category that might still be very usefull to me. If you wanted to ignore that part I probably failed to formulate the question correctly. Either way: Thanks for your help!


Second derivatves with respect to rotations in SO(3)

Question: For some background, I'm trying to calculate some physical properties such as magnetotropic coefficients for crystals in a magnetic field. I want to avoid doing discrete derivatives where I can and I need some help with the calculus.
If $R^\alpha_{\hat u}$ is a matrix implementing an rotation of angle $\alpha$ about $\hat u$ and $F(\vec r)$ is a smooth, differentiable scalar funtion over $\vec r \in \mathbb R^3$.
By using the infintessimal rotation
$$\tilde R^\alpha_{\hat u}  = \left [ \begin{matrix}
1 & -\alpha u_z & \alpha u_y\\
\alpha u_z & 1 & -\alpha u_x \\
-\alpha u_y & \alpha u_x & 1
\end{matrix} \right ]$$
It's easy enough to show that
$$ \frac {\partial}{\partial \alpha} F(R^\alpha_{\hat u}\, \vec r)  = \hat u \cdot (\vec r \times\vec \nabla F)$$

Is there a similarly simple expression for the second derivative?
Are there any general statements that can be made about the higher-order derivatives with respect to these rotations?
$$ \frac {\partial^n}{\partial \alpha^n} F(R^\alpha_{\hat u}\, \vec r) $$
Answer: From
$$
\tilde R_\hat{u}^\alpha=I+\alpha\begin{bmatrix}0&-u_z&u_y\\u_z&0&-u_x\\-u_y&u_x&0\end{bmatrix}
$$
we see that
$$
\tilde R_\hat{u}^\alpha\,\vec{r}=\vec{r}+\alpha\,\vec{u}\times\vec{r}\,.
$$
Therefore, by the chain rule,
$$
\frac{\partial}{\partial \alpha}F(\tilde R_\hat{u}^\alpha\,\vec{r})=(\vec{u}\times\vec{r})\cdot\nabla F(\tilde R_\hat{u}^\alpha\,\vec{r})
=\nabla F(\tilde R_\hat{u}^\alpha\,\vec{r})\cdot(\vec{u}\times\vec{r})
\,.
$$
(By the triple product identity this is equivalent to your equation.)
Therefore, by the chain rule again,
$$
\frac{\partial^2}{\partial \alpha^2}F(\tilde R_\hat{u}^\alpha\,\vec{r})=\sum_{i,j=1}^3\frac{\partial^2}{\partial x_i\partial x_j} F(\tilde R_\hat{u}^\alpha\,\vec{r})\,(\vec{u}\times\vec{r})_i\,(\vec{u}\times\vec{r})_j\,.
$$
Obviously,
$$
\frac{\partial^n}{\partial \alpha^n}F(\tilde R_\hat{u}^\alpha\,\vec{r})=\sum_{i_1,...,i_n=1}^3\frac{\partial^n}{\partial x_{i_1}...\partial x_{i_n}} F(\tilde R_\hat{u}^\alpha\,\vec{r})\,(\vec{u}\times\vec{r})_{i_1}...(\vec{u}\times\vec{r})_{i_n}\,.
$$


Deixar um menu li com treeview ativo após reload da página

Question: Eu tenho um menu em um Sidebar utilizando
 e
, quando eu clico em algum a página é atualizada, porque utilizo um link  no meu.
eu estou usando o seguinte javasscript para atualizar o menu ativo :
    $('li').each(function () {
    if (window.location.href.indexOf($(this).find('a:first').attr('href')) > -1) {
        $(this).addClass('active').siblings().removeClass('active');
    }
});

Esse modelo fuciona bem para os menus
 normais , mas quando tenho um
como este :

         Partners

             List Partners

             Register a new Partner

ele não muda o
 ele volta ao padrão, gostaria de saber como fazer para deixar o esse item como ativo. Vi varias respostas mas não consegui entender nenhuma.
assim é como esta a minha pagina:

 Statics and Reports

          Falcon Company

         Jobs Schedule

             Employee

 List Employees

Register a new Employee

             Client

 Client List

Register a new Client

            @*
 Outras Informacoes
*@

             Partners

                 List Partners

                 Register a new Partner

Answer: Vais ter que gravar essa informação no browser do cliente (ou por cookies, ou por localStorage, ou por alguma maneira que aches aceitável) e quando fazes load à página verificar se essa preferencia existe e se sim, então seleciona o valor que é igual à informaçao gravada.
Comment: Qual forma você me indicaria para fazer isso ? tem algum exemplo ? estarei procurando sobre os assuntos citados , muito obrigado.
Comment: O estranho é que ele funcona perfeitamente se o menu tiver apenas 1 nível, mas quando ele tem subníveis ele não funciona.


Reorder a factor based on the ratio of the group sums of two columns - grouping by the factor to be reordered

Question: I have a data frame, df:
  District TypeofSchool Nstudents Nteachers Percent_failure
1        A            I      1936       157            21.5
2        A           II        67         8             0.5
3        A          III      5288       146            78.0
4        B            I       653        72            27.8
5        B           II       865        22             9.0
6        B          III      2278       100            63.2

For graphing using ggplot2, I'd like to recorder the District factor. I'd like to order it by the student to teacher ratio for that district, i.e. sum up the number of students and the number of teachers for all Types of Schools in that district, and take the ratio; reorder the Districts by that ratio, so that the lowest ratio district would show up on the left most position when I plot, say, a stacked bar graph:
ggplot(df, aes(x=District, y=Percent_failure, fill=TypeofSchool)) +
  geom_bar(stat="identity")

Any suggestion how to do the reordering?
Answer: Base R solution (using dat as your data.frame)
stu.tea <- names(sort(by(
             dat[c("Nstudents","Nteachers")],dat["District"],
             function(x) do.call("/",as.list(colSums(x)))
           )))
#[1] "B" "A"

dat$District <- factor(dat$District,levels=stu.tea)
dat$District
#[1] A A A B B B
#Levels: B A

Answer: Here is one way to look at it with data.table
require(data.table)
setDT(df)

df[ , ST.RAT := sum(Nstudents)/sum(Nteachers), by = District][order(ST.RAT)]
df[ , District := factor(District,levels=unique(as.character(District)))]

And then do your ggplot stuff.
Comment: Does factor() behave differently in data.table? Won't factor just alphabetize the levels?
Comment: thanks @Arun. the code was edited after i commented.
Answer: with dplyr:
dat = dat %>% group_by(District) %>% mutate(RST=sum(Nstudents/sum(Nteachers))) %>%
arrange(RST)

dat$District = factor(dat$District,levels(dat$District)[unique(dat$District)])

Answer: Another dplyr solution:
df <- df %>%
  group_by(District) %>%
  mutate(RST=sum(Nstudents/sum(Nteachers))) %>%
  arrange(RST) %>%
  mutate(District = factor(District,District)) # the factor levels are reset here

Note that the last line works by setting the order of the levels of the factor by the current df order which is set by arrange.


How to nullify a global Authorize attribute for a specific action

Question: I have a global AuthorizeAttribute which is applied throughout my app to check authorization
I have a single controller however which shouldn't be authorized when built in debug mode (it contains my jasmine unit tests).
How do I tell Asp.Net Mvc to not use authorization for just this one controller?
Answer: have you tried [AllowAnonymous] attribute
   [AllowAnonymous]
   public ActionResult LogIn () {
   }


SSIS Flat File Export - Only need certain rows from file

Question: I am using SQL Server 2012 and am trying to import a flat file and store it into the database. The problem I am having is that I only need certain rows in a file that contains much more data.
Here is an example from part of a file which I am trying to import.
12/02/2015 09:47:44:917 Rx: Message Header: Ver: 1, MsgType: 1, MsgId: 3 Status: 0x00
TranId: 6, Data ByteCount: 55
Data: 86 A6 4E 0B 6A 64 54 2E 00 50 00 02 00 00 60 1A E0 AD 10 12 BF 07 56 54 20 31 32 42 46 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 CB

Rx Cmd=84, Rsp code=0x00, Device Status=0x50
Sub-Device Index=2
IO Card=0
Channel=0
Manufacturer ID=24602

The only values I care about are ones which are delimited by = (Sub-Device Index, IO Card, etc.). In this example, how can I import the file in a way that the value 2 gets inserted into a column for Sub-Device Index, 0 inserted into a column for IO Card, 0 for Channel, etc.?
Comment: It is better that you add text and not picture of it
Comment: I changed it, thank you
Answer: You can do this with a script task that reads and parses the file, and either populates SSIS variables for use with an Execute SQL task, or the script task can insert them directly into the database.


If $A^*x_n \to y$, there exists a sequence such that $A^*Ay_n \to y$.

Question: I'm struggling with a problem from Young's Introduction to Hilbert Space (7.30 to be more specific)
Let $\mathbb{H}$ be a Hilbert space, $A\in B(\mathbb{H})$ (ie a bounded operator) and $(x_n)_{n=1}^{\infty}$ a sequence in $\mathbb{H}$.
Prove that if $A^*x_n\rightarrow y$, there exists a sequence $(y_n)_{n=1}^{\infty}$ such that $A^*Ay_n \rightarrow y$.
I'm 99% sure this has something to do with the relationship between the kernel and the image of $A$ and $A^*$ ($\ker A^*$ being the orthogonal of the image of $A$, etc), but I haven't been able to make much progress. Could I get a hint on how to proceed?
Answer: Recall that $\ker A = \ker A^*A$. Namely, clearly $\ker A \subseteq \ker A^*A$. Conversely
$$x \in \ker A^*A \implies A^*Ax = 0 \implies 0 = \langle A^*Ax, x\rangle = \langle Ax, Ax\rangle \implies Ax = 0\implies x \in \ker A$$
Since $(\ker T)^\perp  = \overline{\operatorname{Im} T^*}$, taking orthogonal complements in the above relation gives
$$\overline{\operatorname{Im}A^*} = \overline{\operatorname{Im}A^*A}$$
Therefore, $A^*x_n \to y$ implies that $y \in \overline{\operatorname{Im}A^*}$, so $y \in \overline{\operatorname{Im}A^*A}$ implying that there exists a sequence $(y_n)$ such that $A^*Ay_n \to y$.
Answer: As you say: use that ${\Bbb H}=\ker A^*\oplus \overline{\operatorname{range}A}$. Then we can split accordingly
$$
x_n=z_n+z_n^\bot,\quad z_n\in\ker A^*.
$$
Apply $A^*$: $A^*x_n=A^*z_n^\bot\to y$. But $z_n^\bot\in\overline{\operatorname{range}A}$, i.e. there exists $v_{n(k)}$ such that $Av_{n(k)}\to z_n^\bot$ as $k\to\infty$. For every $n$, pick $k_n$ that makes $\|Av_{n(k)}-z_n^\bot\|\le\frac1n$ for the tail $k\ge k_n$. Can you prove that $y_n=v_{n(k_n)}$ works?
Answer: The image of a linear operator is closed, so $y$ is a limit of elements of an image iff it is an element of that image.  So this is equivalent to showing that given any $v$, there is some $u$ such that $A^* Au = A^*v$.
$v$ can be written as $h+p$, where $h$ is in $ker A^*$ and $p$ is orthogonal to $ker A^*$, and $A^*v =A^*p$. So we need, given arbitrary $p$, to find $u$ such that $Au = p$.
Comment: It's not true that the image of every linear operator is closed. This is not even true in general if the operator is bounded.
Comment: $A : \ell^2 \to \ell^2$ given by $A(x_n)_n = \left(\frac1n x_n\right)_n$. Notice that $\operatorname{Im} A$ contains the canonical vectors $(e_n)_n$ so $\operatorname{Im} A$ is dense in $\ell^2$. If it were closed, we would have $\operatorname{Im} A = \ell^2$, but clearly $\left(\frac1n\right)_n \in \ell^2 \setminus \operatorname{Im} A$.
Comment: @PhoemueX can you give a counterexample?


If $X$ is distributed $\mathcal{N}\sim(\mu,1)$ then what is the PDF of $X^2$?

Question: If $X$ is distributed $\mathcal{N}\sim(\mu,1)$ then what is the distribution of $X^2$?  Here is my try:
$$\begin{align*}
\mathbb{P}(X^2<x)
&= \mathbb{P}(-\sqrt{x}<X<\sqrt{x}) \\[6pt]
&=  \int_{-\sqrt{x}}^{\sqrt{x}} f(x) \, dx. \\[6pt]
\end{align*}$$
Then:
$$\begin{align*}
f_{X^{2}}(x)
&= \frac{d}{dx}\int_{\sqrt{-x}}^{\sqrt{x}} f(x) \,dx \\[6pt]
&= f_X(\sqrt{x})\frac{1}{2\sqrt{x}}+f_X(-\sqrt{x})\frac{1}{2\sqrt{x}} \\[6pt]
&= \frac{1}{\sqrt{2\pi x}} e^{\frac{-(x-\mu)^2}{2}}. \\[6pt]
\end{align*}$$
How should I continue?
Comment: Cross-post: https://math.stackexchange.com/q/3932295/321264
Answer: Your algebra is wrong in the transition from your penultimate step to your last step (see correct step below).  Part of the problem here is that you are using $x$ both as the variable-of-integration and as the argument for your new density function, which confuses your mathematical statements.  To simplify the notation, let us instead take $R = X^2$ as the new random variable of interest, and specify its arguments by $r$.  You then get:
$$\mathbb{P}(R \leqslant r) = \mathbb{P}(- \sqrt{r} \leqslant X \leqslant \sqrt{r})
= \int \limits_{-\sqrt{r}}^{\sqrt{r}} f_X(x) \ dx.$$
Using Leibniz integral rule on your probability integral you should then get (omitting some of the steps, which I will leave for you):
$$\begin{align}
f_R(r)
&= \frac{d}{dr} \int \limits_{-\sqrt{r}}^{\sqrt{r}} f_X(x) \ dx \\[6pt]
&= \frac{1}{2 \sqrt{r}} \cdot f_X(\sqrt{r}) + \frac{1}{2 \sqrt{r}} f_X(-\sqrt{r}) \\[6pt]
&= \frac{1}{2 \sqrt{r}} \Bigg[ \text{N}(\sqrt{r}|\mu, 1) + \text{N}(-\sqrt{r}|\mu, 1) \Bigg] \\[6pt]
&= \frac{1}{2 \sqrt{r}} \cdot \frac{1}{\sqrt{2 \pi}} \Bigg[ \exp \Big(-\frac{1}{2} ( \sqrt{r} - \mu)^2 \Big) + \exp \Big(-\frac{1}{2} ( -\sqrt{r} - \mu)^2 \Big) \Bigg] \\[6pt]
&\ \ \ \vdots \\[6pt]
&= \frac{1}{\sqrt{2 \pi r}} \cdot \exp \Big( - \frac{r + \mu^2}{2} \Big) \cdot \cosh(\mu \sqrt{r}) \\[12pt]
&= \text{ChiSq}(r | \text{df} = 1, \text{ncp} = \mu^2). \\[12pt]
\end{align}$$
This demonstrates that the random variable $R=X^2$ has a non-central chi-squared distribution with one-degree-of-freedom and non-centrality parameter $\mu^2$.  This is consistent with the general theory for how this kind of distribution arises in general.
Comment: From this result can I derive the density function of the sum of several normal distributed random variables with different mean and variance 1?
Comment: Presumably you mean the sum of their *squares*?  Yes; that will also have a non-central chi-squared distribution.
Comment: you have this proof?
Comment: A simple Google search away: [Guenther (2012)](https://amstat.tandfonline.com/doi/abs/10.1080/01621459.1964.10480742?journalCode=uasa20)


APEX- Unable to call REST API from the salesforce lightning component

Question: I am calling sample google book URL from the lightning component, For that i have written APEX controller to make http request . But it is throwing 404 error for the Google Book API. Here is my APEX controller please check ,
<code>public  class WebservicesController {
     public static String responseFormat='application/json';
     public static String bodyContentType='application/json';

@AuraEnabled
public static Response makeRequest(String url,  String method, String bodyContent) {
    System.debug('Making request httpResponse ' );
    HttpRequest request = buildRequest(url, method,bodyContent);
    HttpResponse httpRes = sendRequest(request);
    Response restRes = buildResponse(httpRes);
    return restRes;
}

private static HttpRequest buildRequest(String url, String method, String bodyContent) {
    HttpRequest request = new HttpRequest();
    System.debug('Making request httpResponse '+ url );
    request.setEndpoint(url);
    request.setMethod(method);
    request.setHeader('Content-Security-Policy', '*');

    if (bodyContent != null) {
        request.setBody(bodyContent);
        request.setHeader('Content-Type', bodyContentType);
    }

    request.setHeader('ACCEPT', responseFormat);

    return request;
}

private static HttpResponse sendRequest(HttpRequest request) {
    return new Http().send(request);
}

private static Response buildResponse(HttpResponse httpRes) {
    Response restRes = new Response();

    restRes.status = httpRes.getStatus();
    restRes.statusCode = httpRes.getStatusCode();
    restRes.body = httpRes.getBody();
            System.debug(' Status code is  ' + restRes.statusCode  );

    System.debug(' httpResponse ' + httpRes.getBody() );

    return restRes;
}

public class Response {

    @AuraEnabled
    public String status { get; set; }

    @AuraEnabled
    public Integer statusCode { get; set; }

    @AuraEnabled
    public String body { get; set; }
}
</code>
}
and also my helper js controller where i am calling this apex controller is method is below ..
<code> createCustomer: function(component, customer) {
    var action = component.get("c.makeRequest");
    action.setParams({
        url: "https://www.googleapis.com/books/v1/volumes/NFPqCQAAQBAJ",
        method: "GET",
        bodyContent: "",
    });
    action.setCallback(this, function(a) {

        action.setCallback(this, function(response){
            var state = response.getState();
            if (state === "SUCCESS") {
                var customers = component.get("v.data");
                customers.push(response.getReturnValue());
                component.set("v.data", customers);
            }
             var action = component.get("c.saveCustomer");
                action.setParams({
                    "customer": customer
        });
        });
        $A.enqueueAction(action);
    });
    $A.enqueueAction(action);
},
</code>
And i also given this google api url in Remote settings and also added as CSP trusted site in my domain.
Answer: Add @AuraEnabled in front of following method:

buildRequest
sendRequest
buildResponse


Are there complete formal systems?

Question: I am relatively new to logic, so forgive my ignorance. My question is: Are there any formal systems that are deemed complete? If so, how did we prove they were complete and which are they?
Comment: "Complete" in what sense?  There are certainly first-order theories which are complete (_e.g._ the theory of dense linear orders without endpoints), but these are not capable of encoding "mathematics" wide and large.
Answer: Inconsistent theories are trivially complete, so I'm going to assume that you're looking for systems that are both consistent and complete.
One such system is Presburger Arithmetic (PreA), which resembles the usual Peano Arithmetic, but has no multiplication.
A common technique for showing completeness is quantifier elimination:
a theory admits quantifier elimination if every quantified formula corresponds to a logically equivalent quantifier-free formula.
Strictly speaking, PreA does not admit quantifier elimination, but a finite extension does: the resulting procedure is Cooper's algorithm.
Quantifier elimination, by itself, does not mean that your theory is complete: you also need to show that all quantifier-free statements are either provable or refutable. In the case of PreA and its extension, this follows by a simple structural induction.

Are there complete formal systems?


How do i determine the nth weekday of a given date in php

Question: I am working on a calendar script where in i need to repeat a calendar event like
"Repeat on every 1st Tuesday of every month"
In the example above. How do you get the "1st"?
for example today is June 12,2009 this would mean it's "2nd Friday of June" How do i get the "2nd"?
Thanks in advance
Answer: Divide by 7 and round up:
ceil(date('j') / 7);

Comment: Also, remember that date take an optional second parameter (timestamp), so this solution could be reused for an arbitrary date.
Comment: haha yeah, it took me a minute and then I was like "oh, of course!"
Comment: Heh I was trying to think of how to solve this problem. This didn't occur to me. Clean, elegant, +1.
Comment: You're awesome Nick! Good job.
Comment: @nickf  Wow really. I missed it completely. Thanks so much.
Answer: This works:
<?php

$date = date('Y-m-d', mktime(0, 0, 0, date('m'), 1, date('y')));

echo date('Y-m-d', strtotime($date.'next tuesday'));

?>

The first line creates a date thats the first day of this month.
The second line get the next tuesday from $date.
You can do much more see date and mktime and strtotime.
Comment: you're doing the reverse of what the OP is asking. Given a date, tell me how many Fridays (or whatever) there have been before this in this month, not what is the date of the nth Friday?
Answer: function dayOfWeek($d, $m, $y)
{
    static $t = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4];
    $y -= $m < 3;
    return ($y + $y / 4 - $y / 100 + $y / 400 + $t[$m - 1] + $d) % 7;
}

// 30th August 2010
// 0: sunday - 6: saturday
echo dayOfWeek(30, 8, 2010);


Prove that $S^2 \vee S^2$ is path connected?

Question: Prove that $S^2 \vee S^2$ is path connected?
Let $a$ and $b$ be two points in a topological space $X$. A path in $X$ from $a$ to $b$ is a continuous map $f$ from [0,1] to $X$ s.t $f$(0) = $a$ and $f$(1)=$b$.
A topological space X is said to be path connected iff given any two points $a$ and $b$ , there exists a path in $X$ from a to b
I can draw but i can't give a function.
Comment: What is $s^2$? What is $*$? Did you mean the $2$-dimensional sphere $S^2$ and [the wedge sum](https://en.wikipedia.org/wiki/Wedge_sum)? I don't think its the Cartesian product cause otherwise how can you draw it? That would require some serious skill. :)
Comment: $X * Y$ is not usual notation for the wedge of pointed spaces $X$ and $Y$: the wedge is usually written $X \vee Y$. $X * Y$ is the usual notation for the topological join of $X$ and $Y$. As you now write $X \mathop{x} Y$, you almost certainly mean the product $X \times Y$ (as Asaf suggests) and you **definitely** need to start using MathJax to typeset your questions.
Comment: The symbol you're looking for is `\times`, I think.
Comment: @freakisb i mean Spherical coordinates
Comment: I don't even know how that answers my questions...
Comment: @freakish yes $S^2$ and the wedge
Comment: Right, so $S^2$ is path connected (which is a consequence of $S^2\backslash\{p\}$ being homeomorphic to $\mathbb{R}^2$ - see stereographic projection). The wedge sum of two path connected spaces is also path connected because each point can be connected to the common glueing point.
Comment: @freakish what the function of this?
Comment: You don't need to write down a function in symbols. Instead you can describe it using the fact that $S^2$ is already itself path-connected.
Answer: Let $p$ be the joining point, which belongs to both copies of $S^2$.
Let $x_1,x_2\in S^2\vee S^2$. There exist paths $f_1, f_2$ such that $f_i(0)=x_i$ and $f_i(1)=p$. Then consider the path
$$F(t) = \begin{cases} f_1(2t) \ , \ t\in[0,.5) \\  f_2(2-2t) \ , \ t\in[0.5,1]\end{cases}$$
Note, $F(t)$ is sometimes called the path composition of $f_1, f_2^{-1}$ and might be notated $f_1*f_2^{-1}$ (the "inverse" because here I traverse $f_2$ backwards).
There was also nothing special about $S^2$ here.


The dirty coins and the three judges

Question: All things being perfect, if we want to know if a set of coinage (all coins with the same bias) is biased, and to what degree, we would just use the outcomes and  confidence intervals of the binomial distribution and be done with it.
Unfortunately, things are rarely that simple in real life. Indeed, this question arose as one of my concerns for what seems like a completely different problem elsewhere. If we are not sure what the true outcome is, and we have to adjudicate the results, that muddies the waters, and alters the confidence interval width. Now suppose we have dirty coins and we do not know for sure what is a heads or tails, or, some other similar problem, like having to use adjudication with three judges to say which image reconstruction method is more diagnostic (for example), then how well the judges agree with each other becomes a factor in whether we can detect that one method of image reconstruction is better than another or whether we can detect biased coinage.
Question: How do we determine, without having truth data, how sloppy our confidence interval is if we have three judges who do not always agree with each other as to what the outcome is?
Now, I did not know how to calculate this (but see answer below after help from colleagues), but I could simulate it, and even the simulation has a curve ball. To that in a minute, first though, keep in mind that we do not have access to the hidden truth in the real world, all we know is probable truth. However, we can assign a synthetic truth when we simulate results.
The simulation
I did 10,000 binary random trials with 3 different biases of coinage, 0.5, (0.2, 0.8), and (0.1  0.9). Note that a bias of p=0.2 is symmetric with p=0.8, so that the 3 trials covers 5 cases in total. Next, as I had that as truth data, I could arbitrarily assign known reliabilities for our judges, and for each judge I simulated their decisions using two factors. For example, for a reliability (or correct knowledge, if you will) of 50%, I allowed the truth data to influence that judges decision 50% of the time. The next factor is that I randomized the remaining decisions, i.e., 50% in our example to be a yes 50% of the time (the latter is perfect cluelessness). That means that for a reliability of 50%, the judge will make a correct decision a factor of 0.5 + 0.5 p of the time. However, to increase the overall reliability of adjudication, we need more than one judge.
Now the curve ball. With three judges, I was able to contrast two strategies to adjudicate their decisions. These are 1) The median result, which is appealing because it is always a 0,1; yes or no, or 2) the mean result. Now let is look at the result for 10,000 trials of three adjudications each.
In the figure, the $y$-axis represents R$^2$, i.e., explained fraction, and the $x$-axis represents the judges reliability. Note that the most accurate (i.e., efficient) results were had when coinage was 50-50 (p=0.5). However, that is also the least useful result in the sense of being able to detect the one method is better than the other for image reconstruction or for detecting coinage bias. When the three judges' reliability was >0.63, the median method outperformed the mean as an adjudication strategy. This became pronounced when the judges were very reliable (0.95). On the other hand, the mean became the better adjudication strategy for more unreliable judging (<0.63). Now results for single judges are not shown, they were miserable.
In the real world case, the judges might have different abilities, one might be 50% reliable and another 80%, depending on how 'expert' they are. Notwithstanding, for the real case, we only need some indication as to how to calculate our confidence intervals more or less accurately, and any insight into this interesting problem would be welcome.
Comment: @Scott I know, but, surprisingly perhaps, that does not affect our use of the of 50% uncertainty measurement. To wit, suppose that a judge increases his overall score by learning during the selection process. That would increase his overall agreement with the truth data. It would not, however, change the fact that we can still divide his then better than they would be overall agreements with the truth data into a larger portion that is 100% correct and a portion wherein he is still only right 50% of the time.
Comment: How do you calculate $R^2$ for the accuracy of judging?
Comment: Same as always, 0's and 1's for false and true, yes and no. It at least autoscales for the mean values, i.e., the thirds in the results. Quick and dirty, it is.
Comment: "It would not, however, change the fact that we can still divide his then better than they would be overall agreements..." This is an artifact of the particular end metrics you are using.  If this is the case, there is a deeper result where there is no measurable distinction between a judge who is 100% correct 90% of the time and 50% correct 10% of the time, and a judge who is just 100% correct 95% of the time and 0% correct 5% of the time, which is probably a simpler way to frame your problem, and one in which more people will intuitively grasp the situation.
Comment: @Scott Your helpful comment led me to the $\text{J}1_{\text{agr}}=\dfrac{3}{4}+\dfrac{\text{M}_{\text{J}}^{\,2}}{4}$ observation in my answer, a simple probability calculation. More to go, but not much, I hope.
Comment: "The next factor is that I randomized the remaining decisions" This seems an unreasonable assumption for judges.  If I were judging a thing, and I had noticed a 90% true rate, then, when uncertain, I might be more likely to pick true.  Also attempting to cast "success of image reconstruction" is hard to cast as 0-1.  If a judge thinks "hmmmm, well it kinda worked", what do they put?
Comment: @Scott The problem of how to make a choice for a problem of this type occurred in practice; suggested [reading](https://pdfs.semanticscholar.org/c336/0e31e42df28a0eda4c17c87b22245765972a.pdf). Such things are usually taken care of up front by giving the judges instructions. In this analysis, we would correctly identify this as a perfect indecision, 50% of the time correct.
Comment: @Scott It depends on what you are talking about. For example, agreement is 100% correct answers, and 0% false answers. But look at what that yields in the agreement charts in my answer for pure guesswork, which for 100% random guesses judge 1 agreement with the median is still 75%, which it has to be to because if I choose a 1, the only way I can disagree with the median is if both other judges choose a 0, which is 1/4 of the time. For disagreement of the median with the truth 50% is pure guesswork. Only way to get significantly less agreement is to knowingly choose wrong answers.
Answer: If you rephrase the question,

not asking about the 'true' $p_{coin}$ how often the coin is heads or tails
but instead you analyze the 'effective' $p_{judges}$ the probability how often the judges say heads or tails

, then the regular analysis becomes 'ok'.
This analysis does not become more difficult. Even if the $p_{judges}$ is not a constant like $p_{coin}$ (the probability that the judges say heads or tails is not a constant every throw); the distribution of the outcome can still be modeled as a Bernoulli distribution (a mixture of Bernoulli distributions is a Bernoulli distribution).

The outcomes from the three judges together could possibly be modeled as a beta-binomial distribution, or one could throw other more specific analyses at it. But this depends on assumptions that we can make about the consistency and variability among judges. at least we can do more than the simple Bernoulli distribution.
For instance: in the case of the dirty coins we should expect some correlation between the occasions that the judges make false/random judgments. We can expect that, if we split the judges results into unanimous and non-unanimous, then the $p$ obtained from these different groups could differ. This allows us to make estimates about $p_{coin}$ based on the two versions of $p_{judges}$. (without such analysis then we only know that $|p_{coin}-0.5| \geq |p_{judges}-0.5|$ but we do not know by how much without a good guess of the reliability)
Comment: When a judge gets it wrong, he does so because he is clueless, and his cluelessness is 50-50. So, for biased coinage, e.g., 0.1, 0.9, his uninformed guesses are not unbiased, that is, his mean or median guess will be less extreme than the underlying truth values. This means that the confidence intervals we think we are using are actually too narrow for the problem.
Comment: "This allows us to make estimates about $p_{coin}$ based on the two versions of $p_{judges}$." Humm, probably not that powerful, and in the case of 63% reliability is indeterminate. More information is from how well the judges agree among themselves, a round robin examination of which this says both how comparatively expert their judgements are, and gives us as well an indication of reliability.
Comment: In your answer, you make suggestions. That is the good direction for an answer, but, I need more in depth analysis for it to be a useful answer. Would you go the extra mile, please?
Comment: *"his mean or median guess will be less extreme than the underlying truth values"*, *"More information is from how well the judges agree among themselves"* That is exactly in my answer. However, for a more in-depth analysis a more concrete example is necessary, unless you just want a solution for your toy model.
Comment: I am working on the simulation data. Will update when I have more information. However, that may also include a solution.
Comment: What I had pointed out is that we can shift the focus and have correct confidence intervals for the probability of a judge to say heads ad tails (but not for the coin actually being heads or tails). This is also the focus that we encounter in the different problem that you link to (*"test **if subjects** (as a group) differed from 50% chance"*).
Comment: However, if you still wish to focus on the actual coin instead the judges opinion about the coin, then you will need some additional information about the relation between the coin and the different judges. Either by assumption or by using some additional tests with information. This makes the solution to the problem depending on this additional information. The only thing that I could contribute is the idea that the judges results can be partitioned resulting into different values for $p$, and based on this (allong with a more accurate model) we can obtain estimated for the true coin p.
Comment: The reason for multiple judges is to get at the truth when it is a matter of judgement, for example, to determine if one method is superior to another.
Comment: @Scott and attention Martijn. I think the problem is tractable. Sure lots of horrible assumptions. See what you think in my answer below. That should at least stimulate conversation.
Comment: @Carl, could you point out what is new?
Comment: Martijn, there is nothing new under the sun, ever. I do not understand what you are asking. I appreciate your contribution. It showed that you understand the problem, and cared to contribute.
Comment: Took awhile, I wanted an explicit answer. You and @Scott helped point me in that direction. I am upvoting your answer (+1) because you helped, not because you actually answered the question.
Comment: Re "toy model" comment. True enough that I defined the truth data for trained judges, who are, among other things, not biased, and would not, for example, answer everything with a "yes". This is perhaps less odious than it seems at first glance, for example, if a judge did answer yes to everything, the statistical aberration would be noticed in practice, and the judge sent for re-education or his results dropped.
Answer: The problem simplifies if we quantify agreement, where by agreement we mean the fraction of $0$'s and $1$'s of the total number of trials that are the same between any two measurements. In specific, we quantify how each (equally good) judge's judgments agree with the median judgments, and how well median judgements agree with the truth data, as below.

First note that each panel above represents 3 curves, and they superimpose. Those curves represents 5 different biases of coinage, $0.5, (0.2, 0.8),$ and $(0.1, 0.9)$. Thus, we have eliminated (apart from noise) the effect of bias on the measurements in a way that cannot be had from correlation. This occurs because agreement of a $0$ with a $0$ is as useful as agreement of a $1$ with a $1$. Thus, it does not matter what the relative number of $1$'s and $0$'s is, just whether those outcomes are the same or different for a single judge and the median judgments.
To use these curves, we calculate the agreement of one of the judges with the median judgments using available data. We then use the curves to back solve for the median judgments. That curve appears to be from total probability $\text{J}1_{\text{agr}}=\dfrac{3}{4}+\dfrac{\text{M}^{2}}{4}$, whose back solution is $\text{M}=\sqrt{4 \,\text{J}1_{\text{agr}}-3}$. We know from simulation that a particular value of median judgments corresponds to a unique (or nearly so) fraction of agreement with the truth data.  This appears to be also from total probability $\text{Agr(frac)}=-\dfrac{\text{M}^3}{4}+\dfrac{3 \text{M}}{4}+\dfrac{1}{2}$. That value, in turn, times the $n$ trials, gives us a number of agreements. It is that number, $<n$, which is the basis for calculating confidence intervals. As that number is less than the number of trials, our confidence intervals will be different. As we shall see in a bit, how they differ depends on judge training. To complete our analysis, we need to make a further assumption and that is that an adequately trained judge makes unbiased errors of judgment. That is, his errors of judgment are $0$'s and $1$'s 50% of the time.
Suppose that there were $60$ yes's (e.g., Yes, picture A is more diagnostic than picture B) and $40$ no's with an agreement fraction of $0.8$. Then we write $60-x+40-x=80$, or $x=10$ giving us a truth value of $50$ yes's and $30$ no's in our "truth" population of $100\times0.8=80$. Then $P$(yes)$=\frac{50}{80}=0.625$, which finally gives us enough information to calculate confidence intervals. The 95% CI for our $50$ out of $80$ yes's was $40.92119$ to $57.83999$, and does not include $40$, where $40$ or $\dfrac{1}{2}$ of the $80$ results would be $p=0.0151145$ one-tailed. Note, as the binomial distribution only allows for whole numbers, I calculated the CI's using the binomial CDF real number equivalent $I_{1-p}(n-k,k+1)$, i.e., the regularized beta function of those parameters.
If we had used the original number of trials in our example; $100$, with a median judgement of $60$ yes's, our one-tailed $p(k\leq 50)$ would be $0.0270992$, and two-tails would have been $p>0.05$. So, it can make a difference how we calculate this. Moreover, training makes a difference. Untrained judgements may have errors in proportion to voting numbers, e.g., $60x+40x=80\rightarrow48$ yes votes out of $80$ [$p(k\leq40)=0.0444971$, one-tailed] and not $50/80,\,p(k\leq40)=0.0151145$  one-tailed. Even that may underestimate the effect of a lack of training, because the agreement of an untrained judge with the median may be worse as well. What is training? For example, for adjudicating diagnostic images, one either knows what all of the applicable diagnoses are, or the judgment is uninformed. That is, the training either covers off all possible implications or we are better off not using that judgement, at least in those circumstances where the outcome really needs adjudication, i.e., is not immediately obvious. So, we saw that the confidence intervals were relatively more narrow for trained judges than for the uncorrected problem, which, in turn, had a relatively smaller confidence interval than that for the corrected results for untrained judges, that is, for our single example case.
The polynomials used fit the above curves well,  $r\sim 0.9999$ for median judgments agreement with truth data, and $\sim 0.9997$ for single judge agreement with the median judgment. The former was suggested by a linear transform of a sigmoidal-like smoothstep functional relationship with the data. The latter appears to be a simple probability calculation. Since we can test for each judge's results compared to the median, and the percentage of yes's and no's, it may be possible to extend the analysis here to include judges of unequal talent, contrarian judges who vote the opposite of what they actually think, and maybe even somewhat for biased judging, or at least we can test for the presence/absence of biased decision making among judges.

The dirty coins and the three judges


How to display multiple columns as a list in a ComboBox?

Question: I want to display multiple, specific columns in a combo box and use it as a search parameter for a query. Any ideas if that's something I can do?
I'll give an example of my table below:
Company Name    Document    Notes    2nd Document    Notes 2
A               1           test     2               test
B               1           test     2               test
C               1           test     2               test
D               1           test     2               test

I have a combobox parameter set up that searches a query via the company name.
So if I select 'A' in my first Combo Box; the results would return:
Company Name    Document    Notes    2nd Document    Notes 2
A               1           test     2               test

I want the next combo box to display the 'Document' column and the '2nd Document' column; essentially displaying a list of documents for a specific company.
Then once a document is selected; I would like a textbox to display the next column over from it.
For example
Combo box 1     Combo box 2           txt box:
'A' selected    '2' selected          Displays text from 'Notes 2'

So in a Nutshell, how can I get a combobox to display specific columns of a query result, if possible? - and how can I get a text box to display the column to the right of the selection in the previous combo box( e.g., selected '1' would display 'Notes' column, selecting '2' would display 'Notes 2' column   If not, any alternatives? Thanks!
Edit:
I had an idea - Perhaps there is a way for a query to convert multiple, specific columns into a single list; then display that list in a combobox?
Comment: One way to display multiple bits of data in a CBO yet keep them separate is to use a List(Of T) as a datasource.  T would be a class which overrides ToString to provide the display.  That many columns though you might want to consider a DataGridView
Comment: Where is your data stored in? DataTable? Kind of `List`? Is it VB.Net or Ms-Access? What have you tried so far?
Answer: It actually sounds like (unless I'm mistaken) what's referred to as Cascading Comboboxes.
So, your first combo box displays all unique options for Company Name:
MyCombo1.RecordSource = "SELECT Distinct CompanyName FROM MyTable"

The second combo box selects all unique options for the selected Company Name:
MyCombo2.RecordSource = "SELECT Distinct Document FROM MyTable
    WHERE CompanyName = '" & MyCombo1.Value & "'"

You can do this infinitely if you need to.  Just keep adding the previous combo box's value to the WHERE clause of the next combo box's RecordSource.
Lastly, in the AfterUpdate event of the last combo box, you set up the text displayed.  So, in MyCombo2's AfterUpdate event, add this:
Dim db as Database
Dim rec as Recordset

Set db = CurrentDB
Set rec = db.OpenRecordset("SELECT Notes2 FROM MyTable
    WHERE CompanyName = '" & MyCombo1.Value & "' AND Document = '" & MyCombo2.Value & "'"

MyTextbox.Text = rec(0)

Of course, it would make it a little easier (a lot easier, actually) if each record had some sort of ID number, so you can reference that instead of having to filter by both CompanyName and Document, but that's the general idea.
EDIT
I just realized your dataset isn't normalized and my answer won't work without some tweaking.  If at all possible, you should normalize your dataset.  Not to sound like a data snob, but there's a reason people go to school to learn this stuff; it's important.  Your table should actually look more like this:
CompanyName      Document     Notes
A                1            Test
A                2            Test 2
B                1            Test
B                2            Test 2

Comment: You'll have to excuse my ignorance; I haven't used access in a few years, so getting to know it all again is proving a little complicating.

But thank you so much; I knew the database didn't look right, I just couldn't figure out where. I'm such an idiot. I've normalized it and the combo box linked up straight away. Excellent stuff!


hover on layer with hidden images doesnt work (IE9), works on firefox and chrome

Question: See description of the problem with all code:
SUMMARY: (basicaly making an imagemap)

I have a div relatively positioned (i will call this the containter :) ), containing 1 image and a couple of div tags with their own image.
The image directly under the container is the background image.
The div under the container are absolutely positioned to be over the background image, the width and height is set to allow to call capture a "hover".
The images under those divs are hidden at the start (the image dimensions are used for the width and height of their respective divs).
When a hover occurs one one of those divs, the image it contains becomes visible)

==> the positioning and hiding showing is all done via jquery, see the pastebin link on top of the post for detailed information.
This works fine in chrome and firefox, but when tested on IE9, the hover doesn't work.
I have tried playing with the z-index of the divs, but at no avail.
Can somebody shed some light on this issue ?
See description of the problem with all code:
Thx!
Edit: Created a jsfiddle from the provided code:
Comment: Pasting a link to pastebin where you describe the question is not very helpful.  Better would either be a link to the page/site where this is happening, or else setting this up in [jsfiddle](http://jsfiddle.net/)
Comment: which version of jquery is it?
Answer: Remove the console.info lines.
console only works with javascript debugger on.
See also: 'console' is undefined error for Internet Explorer
Comment: I know that's why i have following code at the top of all javascript files:
Comment: // because ie does not support console if not in debug...
if (!window.console) console = {log: function() {},info:function(){}};


Adding uncertainty range to probability density function using bootstrapping

Question: I'm hoping this isn't a ridiculous question! Here goes...
I would like to visualise the range of uncertainty in a probability density function fit to observed data using Maximum Likelihood estimation. I have included a sketch to illustrate what I am aiming for (note this is not based on real data, just a sketch).

The steps I have used so far are:

Use bootstrapping to obtain 1000 samples of my data
Use maximum likelihood estimation to fit a three paramter inverse gamma probability density function (aka Pearson V distribution) to each sample from step 1 .
Taking the median of each parameter value from step 2 to plot the "median" distribution. Ditto for the min, max etc.

However, I think I may be going wrong at step 3, as the median of one parameter value does not necessarily correspond to the median of the other two. Is there a more statistically correct way to go about this?
Thanks in advance for any help - Cross Validated has become my go-to for so many questions over the last year (I just wish I could answer more rather than just ask!).
Comment: Normally, people don't use bands around PDFs as in your illustration, because they are unrealistic: the upper band would have total probability greater than $1$ while the lower would have total probability less than $1$. A [standard technique](http://en.wikipedia.org/wiki/Probability_box) draws bands around the *cumulative* distribution functions. Would such a technique be acceptable to you?
Comment: Thanks @Whuber, that makes sense to me that the probabilities would not sum to 1. It will take me a little time to take in the Probability Box concept but I think this could be helpful. Just thinking aloud, I suppose one way of visualising the range of pdfs would be to plot them all in one figure. Thanks again!
Answer: I'll go out on a limb and disagree with @whuber here.  I don't think there's anything wrong with putting bands around pdfs, as long as you understand what they are: pointwise errors. It's like the similar confidence bands around smooth curves for additive regression models. If the bands are wide enough, they make it look like the curve could be far away from the center of the data, but people generally understand what's going on.
What I'd do is obtain the confidence bands and median of your density function directly from the bootstrap samples. You have 1000 estimated functions, so you can obtain your quantiles as the 2.5%, 50% and 97.5% points of the distribution of these functions at any given x.
The main downside is that there's no guarantee the resulting quantiles will actually be members of your parametric density family. Depending on your application, this may or may not be a problem. I doubt it would be, since the bootstrap is generally used only to get estimates of error, and you already have a parametric result from your original sample.
Here's a simple example using the gamma density and moment estimators. You can easily substitute the inverse gamma and maximum likelihood.
<code># the data
x <- rgamma(100, 2, scale=1)

# get 1000 bootstrapped estimates of the density, over a regular grid
xs <- seq(0, 8, len=201)
ests <- sapply(1:1000, function(i) {
    xi <- sample(x, size=length(x), replace=TRUE)
    vi <- var(xi)
    mi <- mean(xi)
    dgamma(xs, shape=mi^2/vi, scale=vi/mi)
})

# plot the individual estimates
plot(xs, ests[, 1], type="l", col=rgb(.6, .6, .6, .1), ylim=range(ests))
for(i in 2:ncol(ests)) lines(xs, ests[, i], col=rgb(.6, .6, .6, .1))

# get the 2.5%, 50% and 97.5% quantiles of the density estimate at each grid point
quants <- apply(ests, 1, quantile, c(0.025, 0.5, 0.975))
lines(xs, quants[1, ], col="red", lwd=1.5, lty=2)
lines(xs, quants[3, ], col="red", lwd=1.5, lty=2)
lines(xs, quants[2, ], col="darkred", lwd=2)
</code>
Comment: +1 - I might also suggest since the OP is fitting ML estimates (and not say just estimating a KDE on the bootstrapped samples) an additional plot might be scatterplots of the bootstrapped parameter estimates. If a reviewer had a problem with this an easy fix is to just remove the quantile lines, the individual bootstrap estimates greyed out are valid PDF's and provide a good visual cue of the uncertainty.
Comment: +1. And by substituting `dgamma` by `pgamma`, the very same script can be used to draw bootstrap bands around the cumulative distribution.
Comment: Thanks hong-ooi for providing such clear code, this works really well. I mainly want this to give a fairly intuitive visualisation of the uncertainty of the pdf fit to the data (as I have several different data sets, each with a different fit this is particularly good for illustrating how certain data sets are more or less variable). I think I just need to be clear that these aren't actually "error" bars, as whuber states. Thanks also @Andy-W, I'm producing boxplots of the parameter estimates.


how can function calls be used in place of loop jump?

Question: I'm currently studying how to use "labeled" loops in javascript on MDN and have encountered the following phrase.

I understand that labeled loops are sometimes used to transfer code execution to a outer loop several layers up. But I dont understand what the author meant by "often function calls can be used instead of loop jumps". Could someone please provide me with an example?
Answer: Here's an example, that searches a 2D array, array, for element n, and prints the coordinates when found:
function searchAndLogCoords(array, n) {
    // The "searching" portion of the function
    outterLoop:
    for (i = 0; i < array.length; i++) {
        row = array[i]

        for (j = 0; j < row.length; j++) {
            // Break out of the "searching" portion of the function,
            // and continue on to the "logging" portion
            if (row[j] == n) break outterLoop
        }
    }

    // The "logging" portion of the function
    console.log("x: " + i + ", y: " + j)
}

var array = [
  [0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0],
  [0, 0, 1, 0, 0],
  [0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0]
];

searchAndLogCoords(array, 1)

Here's the same code, better written by extracting the "searching" part into its own function:
searchAndLogCoords(array, 1)
function searchAndLogCoords(array, n) {
    for (i = 0; i < array.length; i++) {
        row = array[i]

        for (j = 0; j < row.length; j++) {
            if (row[j] == n) return {x: i, y: j}
        }
    }
}

function getCoords(array, n) {
    var coords = searchAndLogCoords(array, n)
    console.log("x: " + coords.x + ", y: " + coords.y)
}

var array = [
  [0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0],
  [0, 0, 1, 0, 0],
  [0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0]
];

searchAndLogCoords(array, 1)

You can try this online, here.
Answer: I am not the author of this article, but I am pretty sure that this is what he means:
Given this example (from that article):

loop1:
for (i = 0; i < 3; i++) {      //The first for statement is labeled "loop1"
   loop2:
   for (j = 0; j < 3; j++) {   //The second for statement is labeled "loop2"
      if (i === 1 && j === 1) {
         continue loop1;
      }
      console.log('i = ' + i + ', j = ' + j);
   }
}

You can transfer this to:

for (i = 0; i < 3; i++){
    (function(){
        for (j = 0; j < 3; j++){
           if (i === 1 && j === 1)
               return;
           console.log('i = ' + i + ', j = ' + j);
        }
    }());
}

Which does not include any labeled loop but breaks the inner loop by returning from the inner function.
Of course, you can declare this inner function elsewhere and then call it, but this way, you keep the current scope of the outer function.
Answer: I can think of two somewhat common cases for needing labels. The first one is when you need to exit nested loops.
outerloop: while (conditionA) {
  innerloop: while (conditionB) {
    doSomething();
    if (exitCondition) break outerloop;
  }
}

One way this could be made is with the following code instead:
(function () {
  while (conditionA) {
    while (conditionB) {
      doSomething();
      if (exitCondition) return;
    }
  }
})();

This takes advantage of a self-executing function's return statement to break out of both loops at once.
The other case would be when you want to continue an outer loop without finishing the current one.
outerloop: while (conditionA) {
  innerloop: while (conditionB) {
    doSomething();
    if (continueCondition) {
      continue outerloop;
    }
  }
  doSomething(); // we don't want this to run if continueCondition is true
}

Which I managed to replace with this:
function innerLoop() {
  doSomething();
  return continueCondition;
}

while (conditionA) {
  if (innerLoop()) continue;
  doSomething(); // we don't want this to run if continueCondition is true
}

Which I decided to make with a named function for readability this time. But honestly, I'd find a way to rewrite the loop in a way that doesn't require a continue like that if I could. Complex loops are hard to maintain.
The important thing to remember is that there's not just one way to do things.


Lua userdata pass by reference - local functions in different files

Question: I have 2 Lua files, namely mydialog.lua and rangecontrol.lua. The code in mydialog.lua is as follows:
local function mydialog()
    --omitted
    local wb_responses=activeobj() --wb_responses points to the current activeobj(), say Obj1
    UI.m_txt=sys.rangetextcontrol(UI.sbSizerInput:GetStaticBox() ,wb_responses) --wb_responses is passed by reference
    --Selection event happened
    --Omitted
    --If clicked on a checkbox execute the following line
    print(wb_responses) --Still prints Obj1 instead of Obj2
end
sys.tools.mydialog=mydialog

Code in rangecontrol.lua:
local function rangetextcontrol(parent, wb_txtBox)

    local  m_txtBox=nil
    m_txtBox=wx.wxTextCtrl( parent, wx.wxID_ANY, "", wx.wxDefaultPosition, wx.wxDefaultSize, 0 )

    local function GetRange()
        wb_txtBox=activeobj()
        local ws=activeobj():cur()
        local rng=ws:selection()
        if (rng==nil)  then return end
        m_txtBox:SetValue(rng:tostring()) -- Here wb_txtBox correctly refers to Obj2
    end

    m_txtBox:Connect( wx.wxEVT_LEFT_DOWN, function(event)
        wb_txtBox=activeobj() --Current activeobj() changed, say Obj2
        local ws=wb_txtBox:cur()
        ws:connect(GetRange) --There is a selection event, call GetRange

        event:Skip()
    end)
    return m_txtBox
end
sys.rangetextcontrol=rangetextcontrol

Briefly what happens:
1) A dialog starts and it has a textcontrol (there might be several textcontrols)
2) When user makes a selection from an object, the text box is populated.
3) My goal is to track from which object the selection is made.
My confusion: Although I pass wb_responses a userdata type, which should be passing by reference to the rangetextcontrol which keeps track of the selections, it seems that wb_responses never changes since it always prints info on Obj1. Therefore, I assume it always points to the first object that it has been initialized with in mydialog.lua. What could I be doing/thinking wrong?
Comment: I think you should provide the code for activeobj() to complete  your question
Comment: @Piglet: `activeobj()` function works correct since the selection shows the correct string values in `m_txtBox:Connect`. It is just when I pass `wb_responses`, its value does not change.
Answer: local function mydialog()
    --omitted
    local wb_responses=activeobj() --wb_responses points to the current activeobj(), say Obj1
    UI.m_txt=sys.rangetextcontrol(UI.sbSizerInput:GetStaticBox() ,wb_responses) --wb_responses is passed by reference
    --Selection event happened
    print(wb_responses) --Still prints Obj1 instead of Obj2
end

You print wbresponses right after you initialize it. How should it change its value? There won't be any event handling between those two lines of code.
Comment: You are right, I have edited the question. `print(wb_response)` is actually inside a checkbox event. So after a selection is made, I click on the checkbox to `print(wb_responses)`


How to use d3 range scale?

Question: Is it possible in d3 to color objects using custom color range values?
I have two json :
One is having values:
<code>[
  {
    "area": "amsterdamn",
    "KPIValue": 98.46
  },
  {
    "area": "brunei",
    "KPIValue": 95.98
  }
]
</code>
Another is having range:
<code>[
  {
    "lowerRange": 0,
    "upperRange": 90,
    "sn": 1,
    "color": "331fcf"
  },
  {
    "lowerRange": 90,
    "upperRange": 100,
    "sn": 2,
    "color": "004F00"
  }
]
</code>
How do I fill a path using color in a range using values?
Answer: Quantile scales should do the job.
<code>// define a variable thresholds as an array of threshold values
// using the lower range
var thresholds = range.map(function(rec) { return rec.lowerRange})

// define a variable colors as an array of color values
var colors = range.map(function(rec) { return rec.color})

// define the scale
var t = d3.scale.quantile().domain(thresholds).range(colors)

// use it
t(KPIValue) // returns the corresponding color
</code>
Here is a working demo
Comment: upvoted but how do I pass pathname example : function(d,i) {return color(i)}) because color is depended on pathname. When I pass d I get whole d3 path object and not current path.
Comment: Please share the code where you would like to use the color scale.

How to use d3 range scale?


why X|Y=y isn't considered to be a random variable

Question: I read about conditioning of random variables and I got a little bit confused.
Why $X|Y=y$ isn't considered to be a random variable (it is just a function of $y$'s) while $E(X|Y=y)$ can be considered as a random variable?
By definition of random variables from wikipedia it seems that also $X|Y=y$ satisfies it, so where is my mistake?
Answer: $X|Y = y$ is certainly a random variable for a fixed $y$. So, for example, $X|Y = 3$ is a random variable. But $X|Y = 4$ is in general a different random variable, and so is $X|Y = 5$, and so on.
$E(X|Y = 3)$ isn't a random variable; it's a fixed value, namely, whatever the mean of $X$ is given that $Y = 3$. $E(X|Y)$, on the other hand, is a random variable because it gives the value $E(X|Y = y)$ for a random value $y$ of $Y$.
Comment: I think the confusion stems from the fact that many texts have the incorrect X|Y notation which is actually not a random variable when Y is not bound to a particular y.


Persistence Unit not available in JNDI when camel route starts

Question: I am trying to use a persistence unit to configure my JPA component in a camel route.
I am using EAP 6.4 and Fuse 6.3.
Right now the route is really basic just to get it working against my datasource:
private UserTransaction userTransaction;
private JpaEndpoint jpaEndpoint;
private JaxbDataFormat jaxbDataFormat;

@Override
public void configure() throws Exception {
    // @formatter:off
    configureErrorHandling();

    configureJpa();

    from("timer:startup?repeatCount=1")
    .to(jpaEndpoint)
    .process(exchange -> {
        Exchange ex = exchange;
    });

    // @formatter:on
}

private void configureJpa() {
    // Configure our JaxbDataFormat to point at our 'model' package
    EntityManagerFactory entityManagerFactory = null;
    try {
        userTransaction = InitialContext.doLookup("java:jboss/UserTransaction");
        entityManagerFactory = InitialContext.doLookup("java:/UtskicksbegaranOraclePU");
    } catch (NamingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    jaxbDataFormat = new JaxbDataFormat();
    jaxbDataFormat.setContextPath(UtskicksbegaranRequestOracle.class.getPackage().getName());

    // Configure a JtaTransactionManager by looking up the JBoss transaction manager from JNDI

    JtaTransactionManager transactionManager = new JtaTransactionManager(userTransaction);
    transactionManager.afterPropertiesSet();

    // Configure the JPA endpoint to use the correct EntityManagerFactory and JtaTransactionManager
    jpaEndpoint = new JpaEndpoint();
    jpaEndpoint.setCamelContext(getContext());
    jpaEndpoint.setConsumeDelete(false);
    jpaEndpoint.setMaximumResults(500);
    jpaEndpoint.setQuery(consumerQuery);
    jpaEndpoint.setEntityType(UtskicksbegaranRequestOracle.class);
    jpaEndpoint.setEntityManagerFactory(entityManagerFactory);
    jpaEndpoint.setTransactionManager(transactionManager);
}

The problem here is that when I start this on my server, this line:
entityManagerFactory = InitialContext.doLookup("java:/UtskicksbegaranOraclePU"); throws javax.naming.NameNotFoundException: UtskicksbegaranOraclePU -- service jboss.naming.context.java.UtskicksbegaranOraclePU
The above code is mostly taken from a quickstart packaged with Jboss.
When I start the server without using or configuring the JPA component in my route, I can access my server and see that my persistence unit has been registered in JNDI.
Here's what my persistence.xml looks like:
<persistence version="2.0"
    xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://java.sun.com/xml/ns/persistence
        http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">

    <persistence-unit name="UtskicksbegaranOraclePU" transaction-type="JTA">
        <jta-data-source>java:jboss/datasources/xa/utskicksbegaran</jta-data-source>
        <class>classes</class>
        <exclude-unlisted-classes>true</exclude-unlisted-classes>
        <properties>
            <property name="hibernate.hbm2ddl.auto" value="validate" />
            <property name="hibernate.show_sql" value="true" />
            <property name="hibernate.default_schema" value="icc" />
            <property name="jboss.entity.manager.factory.jndi.name" value="java:/UtskicksbegaranOraclePU"/>
        </properties>
    </persistence-unit>
</persistence>

Basically, what I'm trying  to achieve is a XA transacted fetch from my datasource which will then be distributed to different queues.
I'm using camel-spring to start the route, and this is my configuration for that:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://camel.apache.org/schema/spring
        http://camel.apache.org/schema/spring/camel-spring.xsd>
    <camelContext id="camelContext_utskicksbegaran-oracle-adapter" xmlns="http://camel.apache.org/schema/spring">
        <packageScan>
            <package>se.sjv.integration.camel.hanterautskick</package>
        </packageScan>
    </camelContext>
</beans>

Is there any other way to access a persistence unit declared in persistence.xml using Spring? What am I missing?
Answer: This is finally resolved.
It had to do with load order on server startup.
For some reason, using jboss-deployment-structure.xml did not resolve this. I am now using a WEB-INF/jboss-all.xml and the file in question contains the following, which my camel integration depends on before starting:
<?xml version="1.0" encoding="UTF-8"?>
<jboss umlns="urn:jboss:1.0">
    <jboss-deployment-dependencies xmlns="urn:jboss:deployment-dependencies:1.0">
        <dependency name="activemq-rar.rar" />
        <dependency name="ojdbc6.jar" />
    </jboss-deployment-dependencies>
</jboss>

Everything runs smoothly with this.


Windows 10 AppLocker AppID issue

Question: I'm trying to enable AppLocker on Windows 10 Enterprise.
I have AppID and AppIDSVC enabled and set to automatic start, and everything looks good. However, when I start inserting policy rules into AppLocker (specifically, .dll rules), I get the following error in Event Viewer:

AppID policy conversion failed. Status Access is denied
User: SYSTEM

That's basically all the info I get.
Why is it trying to convert the policy? Where is this policy? How do I give the system access?
If I ignore this error (which is not a good idea unless you're working on a clean machine with recent restore points) and I continue to configure AppLocker, it works for that session. When I reboot, after the BIOS loads, the OS does not, I get a grey screen and need to restore.
This is obviously not good, and I have been working around the clock trying to fix it. I have found nothing that helps on the internet thus far, so insight or advice would be greatly appreciated.
Answer: The description of this error can be found on Microsoft's Technet article Using Event Viewer with AppLocker, and is:

Indicates that the policy was not applied correctly to the computer. The status message is provided for troubleshooting purposes.

The status you're getting is "access denied," which tells you which general direction to look in, as well.  Someone else had this issue when LOCAL SERVICE had insufficient rights to modify or delete logs at C:\Windows\System32\config\TxR, so that's the type of permissions issue I'd suspect here as well. (By which I mean, something completely unintuitive and non-obvious.)
To track it down precisely, the best thing I can think of is to to open up Process Monitor from the SysInternals Suite just before you start adding your AppLocker rules, and then filtering through the output to see which file or folder it is that SYSTEM is trying to access when the error is thrown.  Once you know where the access is denied, hopefully it's a simple matter of explicitly giving SYSTEM full control to the location.
Comment: I had a similar issue with the local service account not being able to access c:\windows\system32\AppLocker. Thanks to HopelessN00b's suggestion of utilizing Procmon this was fairly easy to find. I was able to create the AppLocker folder manually and give the Local Service Full Control to the directory and it resolved my issues.
Answer: I've seen posts where a user switched it from LOCAL SERVICE to SYSTEM and the service stopped working. Have you tried switching it back to LOCAL SERVICE? The LOCAL SERVICE is the correct/default account in which to run this service.

Windows 10 AppLocker AppID issue


Optimizing Choice of Life Partner

Question: In this link, Hannah Fry mentions that a mathematical argument has been made towards the probabilistically optimal strategy for picking someone to settle down with.
The claim is as follows:
If we pick a threshold $T$ to represent the time window with which you are suitable to date. If we look at the 'first $37$% of your dating window', you should ignore these people and then marry the 'first person who is better than anyone you've seen before.'
Clearly, there is an extreme lack of rigor in the above statement, but she is giving a lecture to the masses, so what can you really expect...
My question becomes:
She mentions there is theory behind this, and that it has a rigorous background. Is there a theorem, or statement about order statistics, probability or others which confirm or support this hypothesis? I've been trying to imagine an approach which is independent of probability distribution of 'partner ratings'. I feel this is the only way that you can make such a blanket statement about this strategy.
Any thoughts?
Thanks
Comment: A key point in the secretary problem as well as the thug problem mentioned by Mark Fischler is that each candidate that is rejected is not available for reconsideration any more. In the real-life version of the _(marriage)_ problem, a rejected candidate _can_ be reconsidered later and accepted, as in, for example, Jane Austen's _Pride and Prejudice._
Answer: Wikipedia knows this as the secretary problem.
The famous 37% strategy (actually not exactly 37% but $e^{-1}$) is optimal in the particular sense that it gives the highest probability of ending up with the best suitor.
This sense of "optimal" contains the implicit assumption that "getting the second best" and "getting none at all" both count as losing and are worth nothing. In many real-life choice situation this assumption may not necessarily hold.
The derivation (which I'm not immediately able to reproduce) doesn't depend on a particular probability distribution on "partner ratings", as long as it's the same for all the interviewed partners, and the probability that two different candidates rate exactly equal is negligible. In this case, only the ordering between the ratings really matter, and instead of choosing random ratings we could start by listing everyone in order of desirability and then permute them randomly afterwards. So the problem is intrinsically a discrete one.
(The fact that "only the ordering matters" is also an implicit assumption, of course. If we relax it such that we can measure the exact rating of every interviewee -- and we can assume WLOG that it is normalized to be uniformly distributed between $0$ and $1$ -- better strategies become available. For example if the first among 20 applicants turns out to score 0.999, it's overwhelmingly likely they're the best overall, and it would be a net loss to continue with the 37% strategy after that).
Comment: @jameselmore: There's a derivation in the Wikipedia article.
Comment: Thanks, your argument regarding the reduction of this problem to a discrete problem makes a lot of sense. I'm most interested in the derivation, however.
Comment: Ah, I see now. I saw at the bottom it said that the solution tends towards $\frac1e$, but I realize now it's due to the integral approximation. Thanks
Answer: This is the same as a more rigorously defined problem given by G. C. Rota in his MIT probability course in 1969 (I am sure it dates farther back than that):
A detective knows there are $N$ thugs in a house and that the leader is the tallest.  He wishes to tail the leader, but the thugs will come out in random order and if he tails one, he will miss the chances to tail any of the others.  How should he decide which one to tail, to maximize the likelihood that he will tail the leader.
The answer, rigorously, is to observe the first $N/e$ of the thugs, and then tail the next one that is taller than all the ones already observed.
I believe the problem was solved on the blackboard using only Stirling's approximatino for $n!$ and some fairly clever reasoning.
Comment: Very interesting (and more concise) redefinition of the problem. I'm interested in the derivation specifically, however

Optimizing Choice of Life Partner


How can I get the text from a simple HTML tag using Selenium RC?

Question: How can I get the text from a simple html tag

ABCDEF

using Selenium RC?
I want to match the exact text. If I use isTextPresent() it returns true even if I put selenium.isTextPresent("ABC").
This is in a HTML tag
.
Comment: I know this doesn't answer your question, but do you have to use RC or can you use WebDriver? From the Selenium home page, "Selenium WebDriver is the successor of Selenium Remote Control which has been officially deprecated..." http://docs.seleniumhq.org/
Answer: Then you need to do the following
strText = selenium.getText("//h2")

if strText.equals("ABCDEF")
     System.out.println("TextMatch")
else
     System.out.println("Text Mismatch")

Comment: Since the OP tagged the post with [tag:junit], more appropriate would be just: `assertEquals("Text Mismatch", "ABCDEF", selenium.getText("//h2"))`


jquery changing the actual css style

Question: I have the following style definition thant can be dynamically changed.

In the following example (see fiddle) you can see that I have a padding box where a user can enter a new value. When they do my code will overwrite everything inside the #box_shipto_header{} and not simply changing only the padding declaration.
I understand that using the jquery html() method will overwrite the content but I don't know of other methods to do what I need.
So if you enter 10 in the box it should update the  id element like that:

see my fiddle
Answer: Use the CSS method:
$(function () {
    $('#padding').blur(function () {
        $("#box_shipto_header").css("padding", $(this).val() + "px");
    });
});

See: http://jsfiddle.net/matthewbj/5c5wX/
EDIT Using the CSS method will add the style attribute to the #box_shipto_header instead of changing it's CSS deceleration.
Answer: $(function(){
    $('#padding').blur(function(){
        $('#box_shipto_header').css('padding',$(this).val()+'px');
    });
});

DEMO
Answer: jsFiddle( http://jsfiddle.net/7V4TU/21/ )
$('#padding').blur( function()
{
    var currentCSS = $("#templateCSS").html();

    var beforePadding = currentCSS.substring( 0 ,  currentCSS.indexOf( "padding:" ) + 8 );
    var afterPadding = currentCSS.substring( currentCSS.indexOf( "padding:" ) + 8 );
    var removePadding = afterPadding.substring( afterPadding.indexOf( "px" ) + 2 );

    $("#templateCSS").html( beforePadding + $(this).val() + "px" + removePadding );
});

jquery changing the actual css style


Problemas em fazer acontecer eventos no JS

Question: Estou aprendendo sobre events no JavaSCript, e começei a praticar, porém me deparei com uma lógica que não estou conseguindo raciocinar ou associar.
Estou querendo que toda vez que eu clicar no botão, o nome dele seja mudado, no exemplo que está em comentário, esse funciona perfeitamente, claro que lá no primeiro modelo HTML o button não tem o onclick, mas no segundo modelo em que eu coloco o onclick: "myFunction()", e faço a função no .js, dá um Uncaght TypeError. Eu não estou conseguindo entender por o nome do button não muda

Eu acho que tem alguma coisa haver com os parênteses no onclick: "myFunction()", sendo isso ou não, não sei o que está havendo

HTML

Easy Shopping Via Mobile

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec lorem justo, sollicitudin vel ultricies
                sed,
                eleifend nec metus. Etiam vitae pellentesque dolor.

            <button onclick="myFunction()">Get Started</button>

JS
const element = document.querySelector("button")

// element.onclick = function () {
//     element.innerHTML = "Hokage"
//  }

const myFunction = (element) => {
    element.innerHTML = "Hokage"
}

Comment: Na arrow function foi declarada  um parametro 'element´   .. que poderia ser apenas parametro vazio na arrow  `() =>`  .... esse parametro não faz relação ao `const element = do....`  é uma declaração a função sem relação ao button... portanto para fazer a ação usa o **this**.. refere se ao objeto que está executando a função atual... no html no parametro da função chamada usa o **this**
Comment: Poderia declarar qualquer nome dentro do parametro da arrow que não tera relação a declaração a declaração do button... poderia até ser `const myFunction = (batataFrita) => {
    batataFrita.innerHTML = "Hokage"
}`    .... mas na chamada dentro do button no html devera ter o **this**
Comment: e a variavel  `element`  podera ser excluida,,, ja que diretamente esta usando `onclick=` no html e não como no código anterior que si manter comentado.
Answer: Ola, seu erro esta no seu evento onclick, a função myFunction recebe um objeto, myFunction(Objeto), porém no seu evento onclick está apenas myFunction(). O correto seria:
<button onclick="myFunction(this)">Get Started</button>

Comment: esse this é um nome específico para essa ocasião na linguagem de programação ou uma palavra qualquer?


Elaboration of Möbius inversion formula.

Question: The Möbius Inversion Formula states:
Let $F$ and $f$ be two number-theoretic functions related by the formula,
$$F(n) = \sum_{d\mid n} f(d),$$ Then, $$f(n) = \sum_{d\mid n} \mu(d) F(n/d) = \sum_{d\mid n} \mu(n/d)F(d).$$
But I do not know how the 2 sums mentioned in the conclusion of the theorem are the same, could anyone explain this for me please?
Comment: You just substitute d by n/d and use the fact that this substitution is involutive.
Answer: If $d$ is a divisor of $n$, so is $n/d$. Since $d$ runs through all divisors of $n$, both expressions are one and the same.
Comment: could u give a proof for it please?
Comment: does not the second formula in the last line in the question must be $\sum_{d'|n} \mu(n/d) F(d')$ instead of the one given above if we substitute $d'$ instead of $d$ in the first formula?
Comment: @hopefully It would be $\sum_{d'|n} \mu(n/d') F(d')$. Since $d'$ is a dummy variable, we can change it back to  $d $ and obtain  $\sum_{d|n} \mu(n/d) F(d)$.
Comment: No if we replace d by d' in the first formula it would not be as you said in your first sentence in your previous comment. I think it would be as I said in my previous comment.
Comment: I mean take this formula $\sum_{d\mid n} \mu(d) F(n/d)$ and put in it d' instead of d..... you will get $\sum_{d'\mid n} \mu(d') F(n/d')$ which is equal $\sum_{d'\mid n} \mu(n/d) F(d)$ which is not the second formula given.
Comment: I am sorry you were correct
Answer: Example:
For $n=9$ the first sum is
$$\mu(1)F(9)+\mu(3)F(3)+\mu(9)F(1)$$
and the second
$$\mu(9)F(1)+\mu(3)F(3)+\mu(1)F(9)$$
Can you see the pattern?


Animated text ribbons in Three.js

Question: I'm new to three.js and not a math-superbrain. However, I challenge myself to learn it by building animated text ribbons.
What I'm trying to build is something like this:

The base idea:

Creating at least two smooth, fabric like ribbons along a custom path.
Front and backside of a ribbon can have different textures
The path of the ribbons should be closed so that I can show/hide segments in an endless animation.

The animation:
I'd like to show 1/3 of a ribbon and then animate along the path to reveal the next segments while hiding the previous ones. So the text/material appears to be in a static position in the room while the ribbon is revealed. If you look at my example below, I kinda achieve this using setdrawRange. However, I was not yet able to reveal the first segments again before the previous range has ended. That causes a jump in the animation at the end of the path.
Here's what I have so far:
Demo:
https://w73zt.csb.app/
Codesandbox:
https://codesandbox.io/s/ribbons-w73zt
What I'm struggling with:

My approach was to use a TubeGeometry and give it only two radial segments. Is this legit, or is there a better way for what I'm trying to achieve?
Somehow I'm not able to put different textures on FrontSide and BackSide of that tube. And if I try to add them as an array according to the docs, no texture is shown at all. What am I missing here?
How can I use setdrawRange to create an endless animation effect without a jump at the end/start of the path? Hope it's understandable what I'm trying to say. The demo above should visualize the issue.
For some reason, the "close" option of the tube is creating a strange connection between the end and the start with fewer segments. This causes the texture to be stretched. How can I prevent this?
Is it beneficial to use SVG to render text like this or would you recommend another approach?

Any help would be really appreciated!
Comment: Have a look at this example: https://threejs.org/examples/?q=curve#webgl_modifier_curve
Comment: Hey @prisoner849 - Yes I found that one as well. But I don't want to move the text along a path. I want to mask and unmask the path for a certain range while the texture remains steady at that path position.
Answer: Here is very rough, unoptimized and imperfect option (not the ultimate solution at all, but at least a starting point), based on the source code of ExtrudeGeometry to form a ribbon, uses modified MeshBasicMaterial to cut the ribbon by the using of discard:

body{
  overflow: hidden;
  margin: 0;
}

Comment: Ahh, I was not aware of this `discard` approach. Definitely a good starting point! Thanks a lot.
Comment: Code snippet doesn't seem to work..
Comment: Now it works :)

Animated text ribbons in Three.js