Automating predictions from R

Question: Let's say I have the following lagged data frame and am trying to predict income for 9/10 using data from 9/09.
dat = data.frame(main_date=c("09/01/2013","09/02/2013","09/03/2013","09/04/2013","09/05/2013","09/06/2013",
                             "09/07/2013","09/08/2013","09/09/2013","09/10/2013"),
                 lag_date=c(NA,"09/01/2013","09/02/2013","09/03/2013","09/04/2013","09/05/2013","09/06/2013",
                              "09/07/2013","09/08/2013","09/09/2013"),
                 income=c(rnorm(10)), status=c(rnorm(10)), avg_temp=c(rnorm(10)))
dat

mod = lm(income ~ status + avg_temp, data=dat)
summary(mod)

(-0.00848) + (0.4272*(0.641)) + (-0.651*(-1.274))

I have my data frame and run a linear model. Then I grab estimates and july data points for my two predictors and calculate for Y manually. However, I was wonder if R had a built in process for generating predictions of this nature or could provide insights into finding an "automated" process for performing this task in R.
Answer: If I understand your question, what you're looking for is ?predict, or fitted(mod), depending on whether you have july datapoints or not.

Automating predictions from R


Cant connect from host (windows) to pfsense (VirtualBox)

Question: I have installed pfsense in VirtualBox. I'm trying to access its configuration through my windows' browser but I cannot.
In the virtual machine's properties, I have tried to configure the WAN interface as bridge and as NAT, but none of them works. The details are below:
Windows
I am connected to my gateway routher through the Wireless adapter, so I have not connected the ethernet interfaze. My IP address in windows is: 192.168.1.34 / 24.
PfSense - WAN interface as NAT
I start PfSense. The WAN interface takes an IP address from DHCP, that address is 10.0.2.15 / 24. As you can see, that address is outside the windows' network, I do not understand why the DHCP service gives PfSense that IP.
Anyway, with the above address, I can ping both the reouter and the windows host, but I cannot do the same from windows to PfSense.
I have tried to set up the IP manually with an IP address that is inside the windows' subnet, for example 192.168.1.50 / 24. If I do that, I can't ping neither windows nor the router, and of course the same ocurrs if I trty to ping from windows to pfsense.
PfSense - WAN interface as bridge
With this configuration, DHCP does not give any IP to the PfSense's WAN interface, I have to put it manually. With thios configuration, I cannot ping PfSense from windows to PfSense, and the same for the opposite.
EDIT
I have tried another configuration:
I have connected the ethernet interface to the router, and the PfSense adapters as bridge.
I can ping from pfSense to windows and to the router, but I cannot ping from windows to pfSense.
Answer: As you said you have installed pfsense on virtualbox so the ip allocated to pfsense interface is issued by virtualbox  DHCP service thats why you are getting 10.0.2.15 / 24 on pfsense, also bridging is not active/configured or not working on your host machine on which you installed virtualbox
First setup bridge on virtualbox and select proper bridge interface on which your are connected to your LAN network, once done you should be able to get ip address to your guest machine on virtualbox from your LAN dhcp server i.e 192.168.1.0/24, if still your not getting lan ip on pfsense guest then check if any mac address binding is active on your dhcp server which is not allocating ip to pfsense
If your using windows 10 then there are some known issues on bridging with virtualbox you can check this link for more details
Once you figure out the bridge then you can walk on pfsense
Answer: The same thing happened to me as well.
This is because pfSense blocks any private network on the WAN interface (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16) by default.
In your case the wan IP Address is 10.0.2.15/24; so pfsense is blocking the access by default.
To resolve this we have to disable "Block private networks and loopback addresses" in the web GUI. And to access WebGUI you have to follow below steps.
In the pfSense Console (Shell), enter "pfctl -d" to disable "pf". This will only be temporary, pf will be re-enabled every time a change is made to the firewall rules.
Allow WAN access to port 443 with below command:
"easyrule pass wan tcp any any 443"   (you can change any any with your preferences)
Once you are able to access WebGUI do the following:
(first run pfctl -d to disable the packet filter temporarily): Interfaces > WAN > Block private networks and loopback addresses + hit Apply Changes.
Hope this helps.


Help with Gambler's ruin problem

Question: Players A and B each have $10 at the beginning of a game in which each player bets at each play, and the game continues until one player is broke. Suppose that Player A wins on a single bet with probability p = 0.45
What is the average duration of the game?
What is the probability that Player B wins the game?
So far I have created a diagram assuming that it doesn't matter how much is being bet per round ($10 per round in the diagram)

And the associated transition matrix
I do not know how to proceed from here to answer the questions that are being asked. I would appreciate any help in this matter.
Comment: Please add the [tag:self-study] tag & read its
[wiki](https://stats.stackexchange.com/tags/self-study/info).
Answer: You can solve this with techniques from The magic money tree problem which is about a single player/gambler, but you can consider the bank as the opponent player.
Different is that in your case the win probability between two players is different, whereas in the link case the payout between two players is different. Yet the techniques are the same like using a martingale or expressing the distribution as a normal distribution that spreads like a diffusion process.

If you want to solve your problem with your transition matrix then you can write a little computer program that solves the evolution of the game and the probabilities to be in a particular state.

You might also solve this considering an itterative scheme like is used here: The Dead Drunk Man
Let's define p(n) the probability for the player A to ever reach the $n+1$ dollars state when they currently have $n$ dollars (and the game ends at 0 or 20). Then
$$p(n) = 0.45 + 0.55p(n) p(n-1)$$
or
$$p(n) = \frac{ 0.45}{1- 0.55 p(n-1)} $$
and we have $p(1) = 0.45$, because after a loss in that state the game ends and there is no return. With this you can compute all $p$ and use a product to compute the probability to ever reach 20 dollars starting from 10 dollars.

Another approach in that post is the use of simulations.

So this gives you 5 approaches

Martingale.
normal approximation and diffusion (actually not easy with two absorption boundaries).
Compute Markov chain for a very long time.
Use an itterative scheme relating different probabilities.
Run several simulations

Help with Gambler's ruin problem


Access 2007 VBA : Building a listbox with selection choices from another list box

Question: So there are 8 categories that may be associated to each order, but not necessarily all of them. So i was going to build a list box that allowed the user to double click each of the category they wish to associate when they have an "Order Detail" form opened up (unbound form that has hidden text boxes with all needed ID numbers).
I want to have another empty text box right beside it that will allow me to append the selections (up to 8) so the user can see that they have been added.
So one list box with the default choices, and when a choice is double clicked, it adds that choice to the second list box to see the tally so to speak.
What is the VB for getting something like this done?
Thanks
Justin
Answer: I suggest that you are making life difficult for yourself. Create a subform with the Order Detail table and a combobox that allows the user to select the various categories.
Comment: One rule of Access is, I think, "if it is getting difficult, you are doing something wrong" :)
Comment: So I am not sure I follow you on this one.....Just to ellaborate a bit further....So there is an Orders table, and a form that opens up data to one order at a time (unbound form). Once you are into one individual order, a data entry control is needed to tag one indivdual order record with upto 8 categories (or whatever is applicable). I know that sounds a little suspect, but what I mean by 'category' are really division tags that maps out what divisions the product has to go through. So i thought the easiest way (given these are unbound forms) would be to take one list box, with the default
Comment: values (categories/divisiontags), and another use to select choices from the first and build an actual list of applicable values to that orderID...kinda like the Access wizard form idea for crosstab queries. The Order Table is already established, and I wasn't even going to change that....ust add a new Category Table with the Order ID as a FK (I already have it in a hidden text box, since these are unbound forms). So I am defaintely not saying this is the best idea....quite the opposite, and that is why i am asking. I just am not following the above idea...though it may be far more normal??
Comment: In the scenario you describe, a subform may not be the best bet, the subform would relate to the categories table, but unbound forms are not the usual set-up. Can you have a bound subform in your set-up?
Comment: i guess i could because its just DAO recordset stuff that moves data into the controls on load depending on previous form/screen selection. to save or update, its just SQL statements behind the button click that save the records, but also give me additional records in other tables for log and change log...i kinda like the unbound stuff better but i suppose just because that is how i learned to do it. Another point is, I would like to use this scenario to learn how to build a "report builder" with the same idea. list box, with selectable fields, and a little visualization of the report selects
Comment: correction: save/update are just SQL statements in VBA of the button click's sub
Comment: A report builder is a select, not an update statement, so you are likely to be creating a list from a multiselect listbox to use with IN : WHERE cat IN (1, 2, 3) : WHERE cat IN ('abc','def'). Updates are more work and require more checking. You can run an update statement with For Each  in the listbox, but then what about deleting, amending etc etc?
Answer: If you want two list boxes --- one for available choices and another for selected items --- and the ability to move items back and forth between available and selected, it can be done with VBA, but is not trivial.  See How do I select items using dual list boxes? for an example.
Personally I favor Remou's suggestion if you can make that work for your situation.
Comment: thanks Hans! since Remou explained it, i am not sure if this is what I will end up using, though it was what i was talking about in the beginning...thanks!


_reactNativeRouterFlux.Actions.signup is not a function

Question: I am using react native router, but I met this problem which I can solve it. I am using react-native-router-flux version 4.0.6
The Router code:
const AppNavigation = () => {
<Router>
    <Stack key="root">
        <Scene key="signin" component={SignInForm} title="SignIn" initial={true}/>
        <Scene key="signup" component={SignUpForm} title="SignUp"/>
    </Stack>
</Router>
}

The code for using the router:
<TouchableOpacity onPress={() => Actions.signup()}>
            <Text>Please <Text style={{color:"green"}}>sign up</Text> if you don't have an account</Text>
</TouchableOpacity>

Here's the error picture
Answer: Have you added Router component to the first page of App which is mentioned in the Index file? like shown below :
import React, { Component } from 'react';
import Router from '../Router';

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
    };
  }

  render() {
    return (
        <Router/>
    );
  }
}


MSTEST folder deployment question

Question: Is there a way to preserve folder structure with MSTEST deployment?
I have a situation with some existing code where I have .config files in a subfolder (called "Configuration"). I can specify this folder using MSTEST deployment but, in it's infinite wisdom, MSTEST just copies the files from this folder to the run folder (TestResult\\Out), i.e. it does not create a subfolder called Configuration. This royally screws up the code and it fails. I don't really want to have to start using complicated pre-test scripts to create folders etc.
Any ideas gratefully received.
Matt
Answer: I think I had the same problem...
My tests used a folder called xsd and I wanted to deploy the folder to the test \OUT directory. When I did this, the files inside the xsd folder were copied to the test \OUT directory, but I wanted the folder xsd into the test \OUT directory...
To solve this I read this. (Wayback machine has an archive of this page here)
Comment: Please dont just provide a link to a solution. Briefly explain what the solution is incase the link goes down such as in this case.
Comment: You, my friend, are godlike.  Be sure to restart VS2010 , otherwise it won't pick up your changes.
Comment: Also, it appears you need at least one file in the directory otherwise MSTest won't pick it up
Comment: Just adding the solution here (taken from the Wayback machine):

In the testsettings file:

Note that the back slash at the end of the file name attribute value is essential as is the "outputDirectory" attribute for this to work.
Answer: If you're using the DeploymentItem attribute, it takes a second argument for the name of the directory to copy the files into. If you use the same name as your folder it preserves everything.
To use your test case you'd do:
<code>[DeploymentItem("Configuration", "Configuration")]
class TestClass
....
</code>
and it would work.
Comment: I saw this in the MSDN documentation, but it does not help for imported assemblies.
Answer: Yes, you can. read the article Do MSTest deployment items only work when present in the project test settings file?
It explains how to map deployment items.
Answer: In Visual Studio 2012 the output directory is the working directory which means that the DeploymentItem attribute isn't needed for the general case (where you don't have specific per-test or per-class deployment items). You can simply click Project | Show All Files and include the subfolder and files in Visual Studio with the 'Copy Always' or 'Copy if newer' attribute to your project and the files will be copied to your output directory with hierarchy intact. The same applies when running vstest.console.exe from the command line.
See here for more information about Deployment Items in Visual Studio 2012.

MSTEST folder deployment question


Using epsilon-balls on metric spaces

Question: Need help with a metric space epsilon ball question..
If $\ell_1$ is the set of all sequences of real numbers  $(x_n)_{n=1}^\infty$ such that $\sum_{i=1}^{\infty} |x_i| < \infty$ with metric $$d_1((x_n)_{n=1}^\infty, (y_n)_{n=1}^\infty) = \sum_{i=1}^{\infty} |x_i - y_i|$$
Show an example of completeness.
Comment: What have you tried?
Comment: @CraigLutic : Did you mean "$P\subseteq\ell_1$" instead of "$P\in\ell_1$"? Because the latter means $P$ is just a *single* sequence in $\ell_1$.
Answer: Consider the complement, $\ell_{1} - P$, which is the set of all $\textbf{x}\in \ell_{1}$ such that there is some $n \in \mathbb{N}$ for which $|x_{n+1}| > |x_{n}|$. I claim $\overline{\ell_{1} - P} = \ell_{1}$.
Let $\textbf{x} \in \ell_{1}$ and let $B_{d_{1}}(\textbf{x},r)$ be a neighbourhood of $\textbf{x}$. We note that $x_{n} \to 0$ as $\sum_{n=1}^{\infty}|x_{n}|$ converges. This implies that $x_{n}$ is Cauchy, hence, for all $\varepsilon > 0$, there exists some $N \in \mathbb{N}$ such that for all $n,m > N$, $|x_{n} - x_{m}| < \varepsilon$. There then exists some $N \in \mathbb{N}$ such that $|x_{N} - x_{N+1}| < r/2$. If $\textbf{x}$ satisfies the property that $|x_{n+1}| > |x_{n}|$ for some $n \in \mathbb{N}$, then we need not to work anymore. If not, define a new sequence $\textbf{y} = (y_{n})_{n=1}^{\infty}$ such that $y_{n} = x_{n}$ for each $n$ except at $N$. We replace $x_{N+1}$ with $x_{N+1}+r/2$. This gives us the property we want. We have that $\sum_{n=1}^{\infty}|x_{n} - y_{n}| = |y_{N+1} - x_{N+1}| = |r/2| < r$. Hence, $\textbf{y} \in \ell_{1} - P$ and $\textbf{y} \in B_{d_{1}}(\textbf{x},r)$. Therefore, $\textbf{y} \in \overline{\ell_{1} - P}$. The claim follows.
The above gives us that $\text{Int}(P) = \emptyset$. If we find $\overline{P}$, we also get $\partial P$. Now consider a sequence of elements in $P$, $(\textbf{x}_{n})_{n=1}^{\infty}$ that converges to a point $\textbf{x} \in \ell_{1}$. Non-strict monotonicity is preserved under limits, so $\textbf{x} \in P$. This shows that $P$ is closed and so $\overline{P} = P$ and also gives us that $\partial P = P$.

Using epsilon-balls on metric spaces


Apply list of functions to maybe value in Javascript

Question: I'm using ramda-fantasy for the monads. I have a string inside a maybe and a some functions that will perform regex matches on a string and return a Maybe String.
How do I map the maybe to apply all of the functions and concatenate the result?
I have
const fieldRetrievers = [
  getAddress,
  getName,
  getPhone,
]

const text = Maybe.of("a text")

// I want to define
// List (String -> Maybe String) -> Maybe String -> Maybe String
function getInfo(retrievers, maybeText) {...}

How can I do that?
Comment: You want to get the phone from the name part of the address part of the string?
Answer: You're looking for composeK, the function composition over monadic structures ("kleisli arrows").
Basically, your resulting function is supposed to repeatedly chain onto the input:
text.chain(getAddress).chain(getName).chain(getPhone)

which you could implement using a reduce over your array of functions:
R.reduce((m, f) => m.chain(f), text, fieldRetrievers)

so you'd write
const getInfo = R.flip(R.reduce(R.flip(R.chain)))

Comment: Nice. But if one of the functions returns `Nothing` the entire result would be `Nothing`. I would like to ignore all `Nothing`s.
Comment: What do you mean, ignore? What else could you return if not `Nothing`? Please provide some example functions with example input and the expected output in your question.
Comment: Imagine I have the string `"Name: John | Address: Apple Street"`. In this example, `getName` would return `Just "John"`, getAddress would return `Just "Apple Street"` and getPhone would return `Nothing`.
My goal is to run all of these functions against the original string and concatenate the results, ignoring the `Nothing`s.
In the example I gave, the desired output would be `"John, Apple Street"`.

Is there a concise way to do that?
Comment: Please put that example in your question, I'll post another answer.


Different Simile Marks

Question: In the pictures below, there are many measures with different simile marks.
I know there are many different types of simile marks, varying number of lines, with or without dots, on barline or in the measure.  Can someone explain the meaning of each element of the simile mark, and what they do?
Comment: @Tim - I think it was just trying to explain what the simile marks meant
Comment: The first example seems odd, in that the simile marks could/should be present in the left hand part as well.
Answer: All simile marks basically say the same thing which is play what you just played. The only thing that typically changes from simile to simile is how much you play. With a single simile you would only play one note/chord, but the others take groups of notes or measures. The breakdown of all the similes in your post are as follows:

Single - play last notated note/chord
Double - play the last notated figure (typically one beat)
Multi - play the last notated figure (typically two beats)
Measure Repeat - play the last notated measure
Multi-Measure Repeat - play the last two notated measures

In scores for full bands and lead sheets, similes can be used in a slightly different way for instruments that play chords as seen in the picture below:

The first measure has simile-like notes that show note hits and duration, but no actual pitches. The player would play the chord denoted above their staff, but the voicing is up to the musicians. I'm not sure about the proper name for this notation, but Finale calls it rhythmic notation. The other 3 measures have a slash for each beat in the measure. This says play the last noted rhythmic pattern. The chords may change as seen in the third measure, but the rhythm stays the same. Again I'm not sure about the proper name for this notation, but Finale calls it slash notation.
Answer: A single slash symbol shows the repeat of either the last crotchet (quarter note), or the last a group of quavers (eighth notes) that make up a beat.
A double slash is used for a group of semiquavers (sixteenth notes).
Similarly, a triple slash is used for demisemiquaver (thirty-second notes) etc.
In the following images, the lower staff shows what is meant by the upper staff.
Slash repeats in simple time:

Slash repeats in compound time:

A percent sign is used to repeat the last bar.

A double slash percent sign centred on a bar line means to repeat the last two bars:

If more than two bars is to be repeated, a percent sign with more slashes can be used.

The odd-one-out is in your first image, where a double slash percent sign is being used for a group of notes that contains mixed durations.

Different Simile Marks


Bootstrapping clusters in R

Question: I am running a negative binomial regression of clinic counts in each county in the entire country (~3k counties).  I'd like to at least partially account for the non-independence of neighboring counties by bootstrapping the confidence intervals in a "clustered" fashion--e.g. draw an entire state's (50 states total) worth of data at once.  This has become standard practice, for better or for worse, in the econometric literature.
I could write the code to do this myself, but the boot package seems like it should have the ability to do this somehow, and in general I prefer tested, general solutions to one-off hacks.  Is there a way to coerce the boot package to do a clustered bootstrap?
I tried the strata argument, but that randomizes within strata rather than randomizing which cluster gets taken, as the following code confirms:
dat <- data.frame( cluster=rep(letters[1:5],each=10), x=runif(5*10), stringsAsFactors=TRUE )
boot.stat <- function(dat,idx) {
    print(dat[idx,]$cluster)
     print(table(dat[idx,]$cluster))
    mean(dat[idx,]$x)
    }
    boot(
     data=dat,
     statistic=boot.stat,
     strata=dat$cluster,
    stype="i",
    R=5
)

Comment: @AdamO Because it destroys the *within-cluster* correlation.  Maintaining that correlation is the logic behind sampling the entire cluster.
Comment: @AriB.Friedman I seem to have forgotten about this conversation. For unconditional bootstrap, you would need to have a variable indicating cluster membership which is jointly sampled with the rest of the observations in the bootstrap.
Comment: Why would an unconditional bootstrap be inappropriate for your purposes? It would generate a random number of observations from each cluster and there would be no permutation of cluster labels from bootstrap samples.
Comment: Does it? If values were constant within each cluster, they would still be constant within each cluster for any unconditional bootstrap resampling of the data. I think it would maintain cluster level correlation. That wouldn't be the case with permutation testing, of course.
Comment: @AdamO I think it does but I have been crazy recently.  I'll try to come up with a simulation demonstrating soon, but regardless it's the method I'd like to replicate.
Comment: @AdamO if I'm not mistaken it's the same logic behind time series bootstraps--drawing blocks to account for serial correlation. And Ari, that link is dead, do you by any chance recall the paper you had linked? I could go for some academic references on this topic.
Comment: @MichaelChirico Not sure which one I meant to link to, but Cameron Gelbach Miller probably.
Answer: If I understand you correctly you want to estimate a statistic per state and that average that statistic to get a bootstrapped estimation of the overall statistic.
Stratified sampling does something different. It ensures that the label is samples representatively in each sample. I do not think that is what you want to do.
You could do this manually without being hacky. Using the dplyr, tidyr and purrr package from the tidyverse this becomes transparant and clean code.
library(tidyr)
library(dplyr)
library(purrr)

dat <- data.frame(cluster=rep(letters[1:5],each=10),
  x=runif(5*10), stringsAsFactors=TRUE)

boot.stat2 <- function(df) {
  mean(df$x)
}

dat %>%
  nest(x) %>%
  mutate(stat = map_dbl(data, boot.stat2))

More information on the

pipe %>% using dplyr
nesting and unnesting using tidyr
mapping values using purrr

Bootstrapping clusters in R


Variance of sample median of normal distribution

Question: Let $\mathbf{R} \ni X_1, \dots, X_n \sim \mathcal{N}(0, \sigma^2)$. I can show that
$$
\mathbb{E} ~ \text{Med} \{X_1, \dots, X_n\} = 0
$$
and want to compute the variance of the same sample median, i.e.
$$
\mathbb{V}ar ~ \text{Med} \{X_1, \dots, X_n\}
$$

I have a guess that it should behave like sample mean ($\asymp \frac {\sigma^2} n$), since everything is symmetric and stuff, but no idea how to show it rigorously.
Comment: The Theorem referred to [here](https://stats.stackexchange.com/questions/14877/central-limit-theorem-for-sample-quantiles) is Thm 4.1 in [Statistics and Data Analysis for Financial Engineering](https://www.springer.com/gp/book/9781461427490#otherversion=9781441977861) and gives you the $/n$ relationship.
Comment: How do you define sample median for an even-sized sample?
Answer: For definiteness, consider odds $n$, say $2m+1$.
This is an additional comment more than an answer (the second comment by @LinAlg refers to a Theorem that gives the complete answer anyway), to grasp intuition about about the 1/n factor
Start with the simplest case, that of iid uniform random variables.
Then the ordered statistics of such random variables are well known to be beta random variables, and the median itself will be Beta($m$, $m+1$) if I am not mistaken, the variance of which (check wikipedia) is
$$\frac{m(m+1)}{(2m+1)^2 \times 2(m+1)}= \frac{m}{2(2m+1)^2} \sim \frac{1}{8m}$$
Now you can map your iid uniform to iid Gaussian using the inverse distribution function (in fact, since the Beta concentrates around 1/2, we will only need the derivative of the function at this point). This way, you can even work out the constant in front of $1/m$, but doing this rigorously is parhaps not that easy I assume.
Answer: This is not an answer, but it's too long for a comment.
Clearly, the answer must scale proportionally to $\sigma^2$, so let's just assume $\sigma=1$.
Sampling $x_1, \ldots, x_n$ i.i.d. from a standard Gaussian is equivalent to sampling a random Gaussian vector $\vec{x} \in \mathbb{R}^n$ with mean $\vec{0}$ and identity covariance matrix. The median coordinate $\mathrm{Med}(\vec{x})$ satisfies $$\mathrm{Med}(\vec{x}) = ||\vec{x}|| \mathrm{Med}(\hat{x})$$ where $\hat{x} = \frac{\vec{x}}{||\vec{x}||}$ is the corresponding unit vector.
For Gaussians, the radius and unit vector are independent, so the calculation factors:
$$\mathbb{E}_{\vec{x} \sim N(\vec{0}, I)}[\mathrm{Med}(\vec{x})^2] = \mathbb{E}_{r,\ \hat{x} \sim \mathrm{unif}(S^{n-1})}[r^2 \mathrm{Med}(\hat{x})] = \mathbb{E}_r[r^2] \mathbb{E}_{\hat{x} \sim \mathrm{unif}(S^{n-1})}[\mathrm{Med}(\hat{x})^2].$$
Here $r$ is just the norm of $\vec{x}$ so $\mathbb{E}_r[r^2] = \mathbb{E}_{\vec{x}}[||\vec{x}||^2] = n$. The distribution of $\hat{x}$ is uniform on the sphere by symmetry.
I don't know how to calculate this integral over the sphere though. You can do obvious things like dividing by $n!$ and restricting to the sector $U_0 = \{x_1 \leq x_2 \leq \cdots \leq x_n\} \subset S^{n-1}$:
$$\mathbb{E}_{\hat{x} \sim \mathrm{unif}(S^{n-1})}[\mathrm{Med}(\hat{x})^2] = n! \int_{\hat{x} \in U_0} (x_{(n+1)/2})^2 d\mu(\hat{x}),$$
but already for $n=5$ Mathematica doesn't manage to compute the integral.
Answer: WLOG, assume that $\sigma = 1$.
We have a random sample $X_1, X_2, \cdots, X_n$ of size $n$ from $X\sim N(0, 1)$.
The probability density function of $X$ is $f(x) = \frac{1}{\sqrt{2\pi}}\mathrm{exp}(-\frac{x^2}{2})$.
The cumulative distribution function of $X$ is
$\Phi(x) = \int_{-\infty}^x \frac{1}{\sqrt{2\pi}}\mathrm{exp}(-\frac{t^2}{2}) dt$.
The order statistics $X_{(1)} \le X_{(2)} \le \cdots \le X_{(n)}$ are obtained
by ordering the sample $X_1, X_2, \cdots, X_n$ in ascending order.
The probability density function of the $k$-th order statistic $X_{(k)}$ is
$$f_k(x) = \frac{n!}{(k-1)!(n-k)!}[\Phi(x)]^{k-1}[1-\Phi(x)]^{n-k}f(x), \quad -\infty < x < \infty.$$
The joint probability density function of $k$-th and $(k+1)$-th order statistics $X_{(k)}$ and $X_{(k+1)}$ is
$$f_{k, k+1}(x, y) = \frac{n!}{(k-1)!(n-k-1)!}[\Phi(x)]^{k-1}[1-\Phi(y)]^{n-k-1} f(x) f(y),
\quad x \le y.$$
If $n$ is odd, we have $\mathrm{Med}(X_1, X_2, \cdots, X_n) = X_{(n+1)/2}$ and hence
\begin{align}
&\mathrm{E}[\mathrm{Med}(X_1, X_2, \cdots, X_n)^2]\\
=\ & \int_{-\infty}^\infty x^2 f_{(n+1)/2}(x) dx \\
=\ & \int_{-\infty}^\infty x^2 \frac{n!}{(\frac{n-1}{2})!^2}[\Phi(x)- \Phi(x)^2]^{(n-1)/2}\frac{1}{\sqrt{2\pi}}\mathrm{exp}(-\frac{x^2}{2}) dx.
\end{align}
If $n$ is even, we have $\mathrm{Med}(X_1, X_2, \cdots, X_n) = \frac{1}{2}(X_{n/2} + X_{n/2+1})$ and hence
\begin{align}
&\mathrm{E}[\mathrm{Med}(X_1, X_2, \cdots, X_n)^2]\\
=\ & \int_{-\infty}^\infty \int_{-\infty}^\infty \frac{1}{4}(x+y)^2 f_{n/2, n/2+1}(x, y)\  1_{x < y}\ dx dy\\
=\ & \int_{-\infty}^\infty \int_{-\infty}^\infty \frac{1}{4}(x+y)^2 \frac{n!}{(n/2-1)!^2}[\Phi(x)]^{n/2-1}[1-\Phi(y)]^{n/2-1} f(x) f(y)  1_{x < y} dx dy
\end{align}
where $1_{x < y}$ is the indicator function.
For both cases, since $\mathrm{E}[\mathrm{Med}(X_1, X_2, \cdots, X_n)] = 0$,
we obtain $$\mathrm{Var}[\mathrm{Med}(X_1, X_2, \cdots, X_n)] = \mathrm{E}[\mathrm{Med}(X_1, X_2, \cdots, X_n)^2].$$
Numerically verified: I used Maple software to calculate the integrations. I also used Matlab to do Monte Carlo simulation (i.e., generate many group of normal distribution data, calculate median of each group, average them).


How does this SQL query return results with same id_product?

Question: I am facing a complex SQL query in some code, which is suppose to return products without duplicates (by the use of DISTINCT keywork at the beginning), here is the query:
SELECT DISTINCT p.`id_product`, p.*, product_shop.*, pl.* , m.`name` AS manufacturer_name, x.`id_feature` , x.`id_feature_value`  , s.`name` AS supplier_name
FROM `ps_product` p
    INNER JOIN ps_product_shop product_shop
        ON (product_shop.id_product = p.id_product AND product_shop.id_shop = 1)
    LEFT JOIN `ps_product_attribute` y ON (y.`id_product` = p.`id_product`)
    LEFT JOIN `ps_product_attribute_combination` ac ON (y.`id_product_attribute` = ac.`id_product_attribute`)
    LEFT JOIN `ps_product_lang` pl ON (p.`id_product` = pl.`id_product`  AND pl.id_shop = 1 )
    LEFT JOIN `ps_manufacturer` m ON (m.`id_manufacturer` = p.`id_manufacturer`)
    LEFT JOIN `ps_feature_product` x ON (x.`id_product` = p.`id_product`)
    LEFT JOIN `ps_supplier` s ON (s.`id_supplier` = p.`id_supplier`)
    LEFT JOIN `ps_category_product` c ON (c.`id_product` = p.`id_product`)
WHERE pl.`id_lang` = 1 AND c.`id_category` = 18 AND  p.`price` between 0 and 1000
  AND product_shop.`visibility` IN ("both", "catalog") AND product_shop.`active` = 1
ORDER BY p.`id_product` ASC LIMIT 1,4

But it returns 4 product with 2 products with same "id_product" (11941)
What I need is to return 4 products but of different ids each.
Anyone ?
Thanks a lot
Aymeric
[EDIT]
The result of this query shows 4 rows, with 2 having the same exact columns values EXCEPT for the id_feature_value column which 36 for one and 38 for the other.
Comment: `DISTINCT` applies to the whole *record*, not just a single field. So you will not get the exact same record more than once, but any number of fields can  have identical values in otherwise different records.
Comment: Because the `Distinct` looks for the rows where each column are unique. For example, a table with the `Fruit|Cost` columns with the `Apple|3$` and `Apple|4$` will return both rows with `SELECT DISTINCT Fruit, Cost`.
Comment: Please add sample data to your question which helps to get the problem across to us.
Comment: I edited my post. So what I need is only the id_product to be unique, should I remove some stuffs on after the DISTINCT keyword ?
Comment: Which dbms are you using? If a id_product has several rows, what do you want to be returned in one row?
Comment: *id_product* is a name of a column in the *ps_product* table and in this table there are no 2 rows with the same *id_product*, Dbms is MariaDB
Comment: But the result has two rows with the same id_product? Or what is the problem?
Answer: SELECT DISTINCT gets all the distinct combinations of all selected fields in your query, not just the first field.
Now, you could solve that by using GROUP BY to select only distinct values of id_product specifically, like:
SELECT p.`id_product`, p.*, product_shop.*, pl.* , m.`name` AS manufacturer_name, x.`id_feature` , x.`id_feature_value`  , s.`name` AS supplier_name
FROM `ps_product` p
    INNER JOIN ps_product_shop product_shop
        ON (product_shop.id_product = p.id_product AND product_shop.id_shop = 1)
    LEFT JOIN `ps_product_attribute` y ON (y.`id_product` = p.`id_product`)
    LEFT JOIN `ps_product_attribute_combination` ac ON (y.`id_product_attribute` = ac.`id_product_attribute`)
    LEFT JOIN `ps_product_lang` pl ON (p.`id_product` = pl.`id_product`  AND pl.id_shop = 1 )
    LEFT JOIN `ps_manufacturer` m ON (m.`id_manufacturer` = p.`id_manufacturer`)
    LEFT JOIN `ps_feature_product` x ON (x.`id_product` = p.`id_product`)
    LEFT JOIN `ps_supplier` s ON (s.`id_supplier` = p.`id_supplier`)
    LEFT JOIN `ps_category_product` c ON (c.`id_product` = p.`id_product`)
WHERE pl.`id_lang` = 1 AND c.`id_category` = 18 AND  p.`price` between 0 and 1000
  AND product_shop.`visibility` IN ("both", "catalog") AND product_shop.`active` = 1
GROUP BY p.`id_product`
ORDER BY p.`id_product` ASC LIMIT 1,4

However, the problem now is that your query has multiple different values of all the other fields you are selected to choose from, and no deterministic way to pick from them. Even though the id_product is unique in it's table, it's not unique in the result set because in at least one of your JOINs there is a one-to-many relationship, meaning there are several rows that match the JOIN conditions.
On older versions of MySQL, it will just pick the first value it finds in this case, but on SQL Server it will actually error out and tell you that the remaining fields either have to be mentioned in the GROUP BY clause, or they have to be aggregated. So, you've got a few ways you can go from here:

You are on an old version of MySQL and you don't particularly care which values are returned for the rest of the fields, so leave the query as I've posted and use that. I wouldn't recommend this, as it's undefined behaviour so in theory it could change at MySQL's whim. All the values returned will be from the same result row though.
Add aggregate functions, such as MIN() or MAX() to the rest of the remaining fields in the select clause. This will reduce the possible values for the fields down to one, but you will probably end up with a mixture of values from different rows.
Remove any one-to-many JOINs from your query so that you only ever get one row back in the result set for each individual id_product. Then, fetch the remaining data you need in a separate query.

There may be other alternative solutions, but it depends a lot on which values you want returned for the rest of the rows and what RDBMS you are using. For example, on SQL Server you could potentially make use of PARTITION BY to select the first row for each distinct id_product deterministically.
Comment: Note that the above GROUP BY is invalid and won't execute on newer MySQL versions (unless in compatibility mode.)
Comment: Thanks @jarlh, wasn't aware that newer MySQL versions prevent this. Will update my answer.


How do I format my output in Java for this specific instance to add spaces?

Question: Here is what I'm trying to accomplish. When you enter numbers in this format
1 2 2 3 3 4 4 5 6

you get
1 1 2 2 3 2 4 2 5 1 6 1

In other words it tells you how many of each string you have. The problem is I can't figure out how to get there to be spaces in between the output. This is the code:
import java.util.Scanner;

public class RunLengthEncoding {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter a sequence of integers separated by spaces:");
        String input = scan.nextLine();
        System.out.println("Input: " + input);
        String c = " ";

        char ch = 0;
        int count = 1;

        for (int x = 0; x < input.length(); x++)
            if (input.charAt(x) != ' ') {
                if (ch == input.charAt(x)) {
                    count = count + 1;

                } else {
                    c = c + ch;
                    if (count != 1) {
                        c = c + count;
                    }

                    ch = input.charAt(x);
                    count = 1;
                }
            }

        c = c + ch;

        if (count != 1) {
            c = c + count;
        }

        System.out.println("encoder output:");
        System.out.println(c);
        System.out.println("\t");
    }
}

Answer: Everywhere, where you update the String just add a space in between the original string and the count variable.
    c = c + " " +ch;

A few tweaks could be made to this code such as using StringBuilder or using the += operation rather than c = c + " " + ch; since that minimizes the line to only c+=" " + ch; As well as updating count using count++
Comment: Omg, thank you so much for not just the help but the suggestions for tweaking the code up too!
Answer: I am using StringBuilder to build my output.  I am also using another variable to keep track of the last iteration's char to determine if I should keep counting or if I should move on to displaying counts.
This is my take on it:
import java.util.Scanner;

public class RunLengthEncoding  {
    private final static String BLANK_SPACE = " ";

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter a sequence of integers separated by spaces:");
        String input = scan.nextLine();
        System.out.println("Input: " + input);
        StringBuilder outputString = new StringBuilder();

        char ch = 0;
        int count = 1;
        char lastChar = 0;

        for (int x = 0; x < input.length(); x++) {
            // get first input in array
            ch = input.charAt(x);

            // if this is the first item we have fetched, there is no count yet - move on to the next input
            if( x == 0 ){
                lastChar = ch;
                continue;
            }

            if (ch != ' ') {
                if (ch == lastChar) {
                    count++;

                } else {
                    outputString.append(lastChar);
                    outputString.append(RunLengthEncoding.BLANK_SPACE);
                    outputString.append(count);
                    outputString.append(RunLengthEncoding.BLANK_SPACE);
                    count = 1;
                }
                lastChar = ch;
            }
        }
        outputString.append(lastChar);
        outputString.append(RunLengthEncoding.BLANK_SPACE);
        outputString.append(count);

        System.out.print("Encoder output: ");
        System.out.println(outputString);
    }
}

It produces this output:

Enter a sequence of integers separated by spaces:1  2 2 3 3 4 5 5 6 6
  6 7
Input: 1  2 2 3 3 4 5 5 6 6 6 7
Encoder output: 1 1 2 2 3 2 4 1 5
  2 6 3 7 1


Parse text files from multiple folders and create new ones [shell]

Question: I have this folder structure...
171219_NB501241_0070_AHCHYNBGX5
├── fastq
│   ├── Reports
│   ├── Stats
│   ├── Undetermined_S0_R1_001.fastq.gz
│   └── Undetermined_S0_R2_001.fastq.gz
├── Logs
│   └── Logs.zip
├── Recipe
│   └── NS2932577-REAGT.xml
├── RTAComplete.txt
├── RTAConfiguration.xml
└── samplesheet.R70.csv
180201_NB501241_0088_AHJ2GHBGX5
├── fastq
│   ├── Reports
│   ├── Stats
│   ├── Undetermined_S0_R1_001.fastq.gz
│   └── Undetermined_S0_R2_001.fastq.gz
├── Logs
│   └── Logs.zip
├── Recipe
│   └── NS2951235-REAGT.xml
├── RTAComplete.txt
├── RTAConfiguration.xml
└── samplesheet.R88.csv

... there's a text file inside Stats from which I want to read some specific lines and generate a new text file within each fastq folder (17121.../fastq/).
Running these code lines...
for i in 70 88
>do cat *0${i}*/fastq/Stats/DemultiplexingStats.xml | grep -e "<Sample name" -e "<BarcodeCount" >> *0${i}*/fastq/rawcounts2
>done

... I'm having this error and I don't have any idea about what I'm missconsidering (if text redirection goes at the loop's end works well, but I want an specific file for each folder):
-bash: *070*/fastq/rawcounts2: No such file or directory
-bash: *088*/fastq/rawcounts2: No such file or directory

Thanks.
Comment: use find with -exec instead of for
Answer: Assumptions:

could be more than one file and/or directory matching the pattern *0${i}*
matching directories may not contain the source file (DemultiplexingStats.xml)
OP has confirmed the grep command returns the desired results (otherwise OP may want to provide a sample of the source file and the matching target file)

Modifying OP's current code:
for d in *070* *088*
do
    [ ! -d "${d}" ] && continue

    srcfile="${d}"/fastq/Stats/DemultiplexingStats.xml
    tgtfile="${d}"/fastq/rawcounts2

    [ ! -f "${srcfile}" ] && echo "WARNING: cannot find file '${srcfile}'. Skipping." && continue

    grep -e "<Sample name" -e "<BarcodeCount" "${srcfile}" >> "${tgtfile}"
done

Comment: Yes, it's working. I'd say the only problem is how I'm calling the folders... I'm a bit naive with shell, what's the difference between calling a folder without _*_ and add them later (as I did it) or using _*_ right in the beginning? (if I change my loop to `for i in *folder*...` format, it works nicely, but not if only `for i in folder...`). Thanks, markp-fuso.
Answer: Try the following:
find . -path "*/fastq/Stats/DemultiplexingStats.xml" -execdir grep -e "<Sample name" -e "<BarcodeCount" '{}' >> ../rawcounts2 \;

FInd all files ending with "/fastq/Stats/DemultiplexingStats.xml" and then within the directory of the found files, execute the grep commands on the files found and output to a rawcounts2 file in a directory one level up from the current one.
Comment: Thanks for your response, Raman. That's works nicely but I forgot to clarify that I want a _rawcounts2_ not in a previous level but a **specific and individual** one inside each `fastq` folder (each `1712.../fastq/` would have one). Thanks.


Injective function from $\Bbb N^3 \to \Bbb N$?

Question: What is an injective function from $\Bbb N^3 \to \Bbb N$?
I imagine I just want to create a list, essentially to show that this is countable. But I can't come up with such a list. Any ideas?
Comment: Use distinct primes $p_1, p_2, p_3$ and map $(n_1, n_2, n_3) \mapsto p_1^{n_1}p_2^{n_2}p_3^{n_3}$. By uniqueness of prime factorisation this is injective!
Comment: Does your $\Bbb N$ include $0$?
Comment: @SEWillB this should be the answer! (i.e. you can post it)
Answer: As requested, I shall post my comment as an answer. We can use distinct primes $p_1, p_2, p_3$ and the map $(n_1, n_2, n_3) \mapsto p_1^{n_1}p_2^{n_2}p_3^{n_3}$
Then we get injectivity by uniqueness of prime factorisation.
I hope that helps!
Answer: One approach is to take advantage of the Cantor Pairing Function that provides a bijection from $\mathbb N^2$ to $\mathbb N$:
$$
\begin{align}
\pi(x,y)&=T_{(x+y)}+y\\
&=\frac12(x+y)(x+y+1)+y
\end{align}
$$
where $T_n$ denotes the $n$-th triangular number. From this you can form the bijection from $\mathbb N^3$ to $\mathbb N$ given by
$$
f(x,y,z)=\pi(\pi(x,y),z)
$$
Note that $0$ is included in $\mathbb N$ in this version of $\pi$.

Or we could build a function similar to that of Cantor adding an extra dimension:
$$
\begin{align}
g(x,y,z)&=P_{(x+y+z)}+T_{(x+y)}+x\\
&=\binom{x+y+z+2}{3}+\binom{x+y+1}{2}+x
\end{align}
$$
where $P_n$ denotes the $n$-th tetrahedral number. Again with $0$ included in $\mathbb N$. This provides another bijection.


systemd service reports "unknown port"

Question: On a CentOS 7 server,I'm creating a new systemd service from scratch for a new service, prometheus-slurm-exporter. (It's an application that exports data from the SLURM scheduler on an HPC cluster.) By default it uses Port 8080, but since that port is already in use by another service, I've set it use Port 9090 instead. Run from the command line, the command looks like this:
/opt/prometheus-slurm-exporter/bin/prometheus-slurm-exporter --listen-address="0.0.0.0:9090"

It runs fine from the command line, but I want to create a systemd service from it, so I've created the following file, /etc/systemd/system/prometheus-slurm-exporter.service:
[Unit]
Description=SLURM Prometheus Exporter for Grafana
After=network.target syslog.target

[Service]
ExecStart=/opt/prometheus-slurm-exporter/bin/prometheus-slurm-exporter --listen-address="0.0.0.0:9090"

[Install]
WantedBy=multi-user.target

After running systemctl daemon-reload followed by systemctl start prometheus-slurm-exporter, the service fails, reporting an unknown port:
Sep 30 12:21:14 ada prometheus-slurm-exporter: time="2021-09-30T12:21:14-04:00" level=info msg="Starting Server: \"0.0.0.0:9090\"" source="main.go:59"
Sep 30 12:21:14 ada prometheus-slurm-exporter: time="2021-09-30T12:21:14-04:00" level=fatal msg="listen tcp: address tcp/9090\": unknown port" source="main.go:62"
Sep 30 12:21:14 ada systemd: prometheus-slurm-exporter.service: main process exited, code=exited, status=1/FAILURE
Sep 30 12:21:14 ada systemd: Unit prometheus-slurm-exporter.service entered failed state.
Sep 30 12:21:14 ada systemd: prometheus-slurm-exporter.service failed.

Why is it running from the command line but not as a systemd service, and why can't systemd recognize Port 9090?
Comment: Try `--listen-address=:9090`
Answer: I've answered my own question. It seems you can't pass command line arguments to ExecStart. Instead, I need to use
EnvironmentFile=-/etc/default/prometheus-slurm-exporter
ExecStart=/opt/prometheus-slurm-exporter/bin/prometheus-slurm-exporter $OPTIONS

And in the environment file, I have
OPTIONS=--listen-address="0.0.0.0:9090"

Works fine now.
Answer: Old but answering in case anyone else hits this - you can pass command line arguments but quoting is not as expected: https://github.com/systemd/systemd/issues/624. Without quotes e.g. this works fine:
ExecStart=/usr/local/bin/prometheus-slurm-exporter --listen-address=0.0.0.0:9341

systemd service reports "unknown port"


Como colocar default em parâmetros quando se especifica o tipo do objeto?

Question: Quando defino funções, costumo usar o recurso de especificar o tipo de objeto que pode ser utilizado como argumento e qual objeto a função deve retornar. Veja exemplo a seguir:
def count_elements(lista_a: list, lista_b:list)->int:
    result = len(lista_a)+len(lista_b)
    return result

count_elements([1,2,3],[4,5,6])

Output:
6

Ocorre que quando tento estabelecer valores padrões, o python retorna a mensagem invalid syntax. Eu tentei dessa forma, sem sucesso:
def count_elements(lista_a: list, lista_b = [1,2,3]:list)->int:
    result = len(lista_a)+len(lista_b)
    return result

É possível estabelecer argumento default e especificar o tipo de objeto ao mesmo tempo?
Answer: A ordem da annotation (a marcação de tipo) e os valores default é ao contrário do que você está tentando fazer: primeiro o nome do parâmetro, o sinal de :, a anotação, e aí sim o sinal de = seguido do valor padrão:
def count_elements(lista_a: list, lista_b: list = [1,2,3])->int:
    result = len(lista_a)+len(lista_b)
    return result

Esse código tem um outro erro, dessa vez bem mais sútil, então aproveito para comentar: nunca se deve colocar uma lista, ou outro objeto mutável como valor padrão de um parâmetro.
Isso por que os objetos usados como valor padrão são criados uma única vez, quando a função é criada, e re-utilizados em todas as chamadas aquela função  - então se a função altera a lista, numa segunda chamada à função, a lista aparece alterada:
# exemplo do problema no terminal interativo:

>>> def aumenta_lista(lista=[]):
...     lista.append(len(lista))
...     return lista
...
>>> aumenta_lista()
[0]
>>> aumenta_lista()
[0, 1]
>>> aumenta_lista()
[0, 1, 2]

O correto nesses casos é usar None para dispensar quem chama a função de enviar o parâmetro, e criar a lista dentro da função, usando um if:
def count_elements(lista_a: list, lista_b: list=None)->int:
    if lista_b is None:
        lista_b = [1, 2, 3]
    result = len(lista_a)+len(lista_b)
    return result

Isso garante que a  lista_b vai ser criada dentro da função cada vez que for chamada. MAS veja, que agora o parâmetro padrão é um None, que não é uma lista!  Então, para a tipagem ficar correta nesses casos, e ser aprovada por ferramentas de verificação, é necessário dizer que esse parâmetro tem que poder ser OU uma lista OU um None.
O módulo typing da biblioteca padrão tem a classe Optional para esses casos - o correto então é assim:
import typing as T

def count_elements(lista_a: list, lista_b: T.Optional[list] = None)->int:
    if lista_b is None:
        lista_b = [1, 2, 3]
    result = len(lista_a)+len(lista_b)
    return result

(O módulo Typing tem várias classes que são feitas para serem usadas com a sintaxe de [ ], para detalhar mais coisas sobre a anotação de tipo - vale a pena depois ver a documentação de como ele é usado)


Add Input to Each Column of HTML Table

Question: I am trying to add an input field to each cell of my HTML table when I add a new row. The problem is that each time I click the button it only adds an input field to the first column. If I change the index number it only works for either the first or last column, but no columns in between.

    Item
    Ounces (Oz)
    Grams (g)
    Fluid Ounces (FOz)
    Milliliters (mL)
    Drops
    Completed

Click button to test funtionality.

<button onclick="AddRow()">Click Me</button>

Answer: You need to be creating the input and appending it to the cell within the loop that creates the cells so that more than one will be created.

/* This is only here for display purposes in the Stack Overflow environment */
input { width:5em; }

    Item
    Ounces (Oz)
    Grams (g)
    Fluid Ounces (FOz)
    Milliliters (mL)
    Drops
    Completed

Click button to test funtionality.

<button onclick="AddRow()">Click Me</button>

Comment: Thank you so much! I also figured out I could do this with adding the element via HTML. But this seems more intuitive for what I was trying to do! Thank you!
Comment: Now, is there a way I can make the first and last column text input while the middle columns are number?
Comment: @TaylorLarrechea` Yes, just check the column index within the loop before you create the element and if the index isn't `0` or `columnNumber-1` (the first and last column indexes), set `newInput.type="number"`, otherwise, don't (since `type="text"` is the default). I'll update the answer to show this and consider marking this as "the" answer by clicking the checkmark at the top left of the answer.
Answer: Clone the input or simplify the script
I made the HTML valid and use an eventListener as recommended

const tb = document.getElementById("tb");
const columnNumber = document.querySelectorAll("#table thead tr th").length - 1;
const inp = '<input type="text" placeholder="Raw Good Name" class="TableInput"/>	';
let cnt = 1;
document.getElementById("add").addEventListener("click",() => {
  tb.innerHTML += `

    ${cnt++}
    ${[...Array(columnNumber).keys()].map(i => inp).join("")}

`
})
.right {
  text-align: right;
}

      Item
      Ounces (Oz)
      Grams (g)
      Fluid Ounces (FOz)
      Milliliters (mL)
      Drops
      Completed

Click button to test funtionality.

<button type="button" id="add">Click Me</button>

Add Input to Each Column of HTML Table


how to read quarter notes and half notes in 3/4 time?

Question: I have a question about reading sheet music for pieces in 3/4 time signature. Attached is a bar in the bass clef from Waltz No. 2, Shostakovitch which has one dotted half note (D) and two quarter notes (F-A, F-A). 3/4 time signature means each bar has three quarter notes. If a half note is worth two quarter notes, then how can you ever have one half note and a quarter note in the same bar in 3/4 time? In this case it's a dotted half note, meaning it gets three quarter notes worth of time. Does this mean that the note D should be held down for the whole duration of the bar? If that's the intent, why isn't it notated with a tie to the next bar? If not, can someone please explain how half notes and quarter notes work in 3/4? thanks.
Comment: There must be many dupes to this question!
Comment: and the position of the notes looks quite obvious, anyway. It looks like an arithmetical problem of addition.
Answer: In the highlighted measure, there are 2 (actually 3) voices. The dotted half is held for three beats started on beat #1. The other voice (or two depending on how one wants to name things) has a quarter rest on beat #1 and a quarter note third (F & D) on beats #2 and #3. This is a typical waltz pattern.
Measures 1-4 have the same pattern in the right hand (treble). There is a quarter rest then two quarter notes (adding up to three counts.) The last two measures have the same pattern in the bass but the bass line is there too. The accompaniment is compressed to the bass clef. Normally, the left hand plays all the notes but the dotted half is often sustained with the damper pedal.


Implement a class to find invocation time of methods in C#

Question: I have a following situation
public interface IPay
{
  void IncreasePay();
  void DecreasePay();
}

public class PayCalculation: IPay
{
  private int Pay;
  public PayCalculation( int Pay)
  {
    Pay = Pay;
  }
  public void IncreasePay()
  {
    Pay++;
  }
  public void DescreasePay()
  {
    Pay--;
  }
}

Now, I want to implement a class to print how long each Increase &DecreasePay method takes to invocation in milliseconds which should fit with existing clients of IPay.
I was trying to work myself with Stopwatch, but do not know how to implement it in a class without affecting existing clients...
Could some one please help me with the code....
Answer: You can use an aspect oriented approach, to implement your own attributes and add it to the method concerned.
[OnTransaction]
public void IncreasePay()
{
    Pay++;
}

[Serializable]
public class OnTransactionAttribute : OnMethodBoundaryAspect
{
    public override void OnEntry(MethodExecutionArgs args)
    {
        Log(DateTime.Now); // or other way such as StopWatch, whatever ...
    }
}

This way,  you will get notified every time IncreasePay() is called. Similarly, you can create another attribute for DescreasePay() and do some logic therein. Here OnMethodBoundaryAspect is an attribute defined in PostSharp, which is free for this attribute class. You can of course do it yourself.
Note that you don't need to touch any internal logic of IncreasePay() or DescreasePay(), which is very useful and flexible.
Comment: Links included! You will love it! Good luck.
Comment: Sorry could you please explain these, I haven't come across aspect oriented stuff. Also, just saw using DateTime is not a efficient method but Stopwatch or performcounter
Comment: JUST an EXAMPLE, not the every bit of your solution is included!
Comment: Oh Thank you David, helps me to know more about the Aspect oriented thing. Will study further on these terms. :)
Comment: Thank you very much David :) Will surely study those links now :)
Answer: You could create a wrapper class that also implements IPay and have it capture the amount of time it took.
public class PayWrapper : IPay
{
    private readonly IPay _wrapped;
    public PayWrapper(IPay wrapped)
    {
        if (wrapped == null) throw new ArgumentNullException(nameof(wrapped));
        _wrapped = wrapped;
    }

    public void DecreasePay()
    {
        Stopwatch sw = new Stopwatch();
        sw.Start();
        _wrapped.DecreasePay();
        sw.Stop();
        Console.WriteLine(sw.Elapsed);

    }

    public void IncreasePay()
    {
        Stopwatch sw = new Stopwatch();
        sw.Start();
        _wrapped.IncreasePay();
        sw.Stop();
        Console.WriteLine(sw.Elapsed);
    }
}

Then when a class gets an IPay, it can use the wrapper like this:
public class ConsumerOfPay
{
    private IPay _pay;
    public ConsumerOfPay(IPay pay)
    {
        _pay = new PayWrapper(pay);
    }
}

Comment: Hi John, could you please help me understand the 2nd part. Which class is that? Ideally it should implement the IPay interface right in ConsumerOfPay?


How to select these elements

Question: I'd like to handler all elements with the attribute rel inside of an a elements that start with string lightbox.
How can I do it with jQuery?
Answer: With the attribute-starts-with selector:
$('a [rel^="lightbox"]')

Comment: @RoToRa - nope, OP wants "elements ... **inside** ... of a elements". Though, it is a little ambiguously worded so I may have interpreted wrong :)
Comment: You need to remove the space between `a` and `[´.
Answer: you need startswith selector
 $('a[rel^="lightbox"]')

Answer: Use the attribute starts with selector.
$('a [rel^="lightbox"]')

EDIT: having re-read your question, it sounds like this may be what you want:
$('a[id^="lightbox"] [rel]')

This selects all elements that have the attribute rel and are within an a tag that has an ID starting with lightbox.
Comment: @markzzz: Ah, you accepted whilst I was editing, guess I was right first time! To be fair though I think @Box9's answer was first.
Answer: Just to be different... if it is a prefix (i.e. "lightbox-") you can use the |= selector.
$('a[rel|=lightbox]')

How to select these elements


SELECT DISTINCT em coluna do tipo JSON no postgresql

Question: Tenho uma tabela que possui 2 colunas, id (int auto_increment) e resp (json).
Nessa tabela eu tenho valores duplicados na coluna resp, algo assim:

id | resp
--------------------------------------------
1  | {"nome": "Jonh Doe", "idade": 20}
2  | {"nome": "Jonh Doe", "idade": 20}
3  | {"nome": "Maria Claire", "idade": 38}
4  | {"nome": "James Connor", "idade": 50}

Eu precisaria apenas fazer um famoso e tradicional SELECT DISTINCT resp FROM tabela, porém por conta da coluna resp ser do tipo JSON, não consigo fazer o DISTINCT, o PostgreSQL retorna a seguinte mensagem:
ERROR:  could not identify an equality operator for type json

Já pesquisei algumas soluções e tentei as seguintes, porém não funcionaram:
Tentativa 1:
SELECT
  DISTINCT field
FROM (
  SELECT jsonb_object_keys(resp) AS field
  FROM public.tabela
    ) AS subquery
--------------
ERROR: function jsonb_object_keys(json) does not exist

Tentativa 2:
SELECT
  DISTINCT field
FROM (
  SELECT jsonb_array_elements(resp) AS field
  FROM public.tabela
    ) AS subquery
--------------
ERROR: function jsonb_array_elements(json) does not exist

Tentativa 3:
SELECT
  DISTINCT field
FROM (
  SELECT json_array_elements(resp) AS field
  FROM public.tabela
    ) AS subquery
--------------
ERROR: could not identify an equality operator for type json

Answer: No postgresql você pode SIM agrupar por colunas do json, você precisa apenas especificar as colunas que devem servir para agrupamento. Neste post (en) dá pra ver como; sua consulta ficaria assim:
select val->>'nome' as field, val->>'idade' as age, count(*) as total
from tabelateste
group by val->>'nome', val->>'idade'

Olha aqui um fiddle funcionando.
Comment: fiz um teste com alguns campos e até então funcionou, logo menos eu vou tentar fazer com todos os campos possíveis do JSON e retorno aqui com uma resposta. Agradeço sua disponibilidade em me auxiliar.
Comment: Olá @rLinhares peço desculpas por não responder antes. Eu precisei fazer do seguinte modo: Criei um `SELECT` com um `ROW_NUMBER() OVER()` e particionei por umas 15 colunas obrigatórias, ai com isso eu conseguiria identificar os casos distintos dos repetidos, sabendo quais são (No caso, seria os casos com ROW_NUMBER = 1) eu inseri esses em uma outra tabela auxilar, dropei a principal e criei novamente e voltei os dados pra principal. Desse modo eu consegui filtrar apenas os distintos.
Mas para o ROW_NUMBER() eu precisei indicar coluna por coluna conforme você colocou na resposta.
Comment: Realmente funcionou @rLinhares, mas e se por ventura eu não tiver os mesmo itens no JSON? Existe JSON que possuem 5 itens e outros que possuem 20 itens. Exemplo: "nome, idade, sexo, dataNascimento, rg, cpf" e outros JSON que possuem apenas "nome, idade"
Comment: de qualquer forma você vai especificar os campos.. se bastam `nome` e `idade`, ele vai comparar só por eles.. se não existem, acredito que devem ser considerados como diferentes, que o que acontece em comparações que não existe (pra testar é só ir lá no _fiddle_ e deletar a idade de um "Jonh Doe", por exemplo);
Comment: @D.Watson deu certo? conseguiu resolver??
Comment: @D.Watson algum retorno? o ideal é que a pergunta não fique sem resposta (aceita). Se precisar de alguma melhoria, dá um _alô_..


Explaination concerning the polygonal generalized Schoenflies problem

Question: I'm having trouble understanding the status of the generalized polygonal Schoenflies problem : The french and the english version in wikipedia seem (at least to me) to state different things, as there might be problems with dimensions $d\le 5$. Moreover, all relevant litterature seem to date from the 1960s.
Here is the english wikipedia page.
https://en.wikipedia.org/wiki/Schoenflies_problem#Generalizations
My question is the following : Let us assume there is a piecewise affine injective map from $S^n$ to $\mathbb{R}^{n+1}$. Can it be extended to a injective piecewise affine map from the ball to what should be called the 'interior' of the polygon ?
Thanks
Comment: From $S^n$ to $R^{n+1}$, not to $R^n$! Also, the map of $B^{n+1}$ should be injective. This is a major open problem in the case $n=3$. The answer is nobody knows.
Comment: Thanks that confirms what the English Wikipedia says. If you write it as an answer, I'll accept it.
Answer: The remaining (major) open problem (as far as Schoenflies is concerned) is the following:
Problem. Let $f: S^3\to R^4$ be a PL  embedding. Does $f$ extend to a PL embedding $B^4\to R^4$?
Since in dimensions $\le 6$ PL and DIFF categories are equivalent, you can replace "PL" with "smooth" in this problem. As for which way it will go, it's anybody's guess.
See also this question and this one.
Edit. (Per PVAL's comments): While what I said about dimension 4 is correct, in higher dimensions one has to be more careful in stating the known result ("Alexander-Schoenflies" Theorem in higher dimensions). The precise formulation of that theorem is the following (where $k\ne 3$):
Theorem A (PL category). Let $f: S^k \to E^{k+1}$ be a locally flat PL embedding. Then $f$ is PL isotopic to an embedding whose image is the standard round sphere.
Theorem B (Smooth category). Let $f: S^k \to E^{k+1}$ be a smooth embedding. Then $f$ is smoothly isotopic to a diffeomorphism to the standard round sphere in $E^{k+1}$.
Comment: If there does exist a counterexample in dimension 4, then $S^4=B_1 \cup B_2$ where $B_i$ are exotic $B^4$. My understanding is that we could possibly (there might be a proof that such a thing exists given 4D Schoenflies is false but I don't know it) have a PL map $S^4\to B^5$ where the link of a vertex of a point is $B_i$ and we do not know how to rule this out. My understanding is that a similar thing can happen in higher dimensions. In other words, if Schoenflies in dim 4 is false it is plausible that there exists non locally flat PL embeddings in dim >4.
Comment: @Moishe Cohen : I asked a follow-up question at https://math.stackexchange.com/questions/2677526/does-nodes-of-a-polygon-and-cell-relationships-determine-the-shape-of-the-polygo ? If you would be se kind as to have a look, I would be very thankful.
Comment: @PVAL-inactive: You are right, in higher dimensions one needs to be more careful when stating the result. Incidentally, did you ever consider removing "inactive" from your user name?
Comment: @MoisheCohen For now my profile/name is representative of the person I want to be, rather than the person I am (not sure if I am joking or serious).


$FM$ is tangent to $\omega$

Question: Let $\omega$ be a circle and $A, B, C, D\in \omega$ s.t.  $AB||CD$ and $AD\cap BC=\{F\}$, $AC\cap  BD=\{E\}$, Let $M,N\in \omega$ s.t. $MN||AB||CD$,  $E\in MN$.
Show that $FM$ is tangent to $\omega$.
I tried to prove it with the power of point $F$ relative to $\omega$.
Answer: Comment: Join F to center of circle O and extend it to meet the circle $\omega$ at H. FO intersect $\omega$ at G. If $FG=r_{\omega}$ due to statement we have to have:
$FM^2=FG\times FH=r\times 3r=3r^2$
Also if FM is tangent to $\omega$ then MO must be perpendicular to MF, in this case in right angle triangle FMO we have:
$FM^2=FO^2-MO^2=(2r)^2-r^2=3r^2$
Note that quadrilateral ABCD is isosceles trapezoid.
Update: This is particular case. Other configuration also meet the conditions of statement. To show this draw a circle it's diameter is FO. You have to show this circle passes points M and N, that is MN is common chord of two circles. For this extend MN from for example N. Take an arbitrary point like P on it and draw tangents to circles from P. If you prove these tangents are equal, then MN is radical axis of two circles(see Wiki for radical axis) and MN is common chord; that results in $\angle FMO=90^o$ and FM is tangent to $\omega$
Comment: I made a GeoGebra model which indicates that $FG=r$ is not a necessary condition.

$FM$ is tangent to $\omega$


Calculating the Maximum Likelihood Estimate

Question: I'm trying to understand MLE, but struggling with a question/example, so was hoping for an explanation if someone can help.
There's a ring toss game which is repeated until it's succeeds for the first time. Each time the game is played, it succeeds with the probability p; and each attempt is independent.
I have the following probability function of X.
$\ f(x)=p(1−p)^{x-1}$
I'm trying to work out the MLE of p (given a single observation x of X). Would someone know how to go about this?
What I'm struggling with here is that the number of attempts, as it isn't fixed and instead is just 'n'.
Answer: Your likelihood function is
$$
L(p \mid x) = p \left(1 - p\right)^{x - 1}.
$$
Differentiating with respect to $p$,
$$
\begin{aligned}
\frac{d L}{d p}(p \mid x)
&= \left(1 - p\right)^{x - 1} - p (x - 1) \left(1 - p\right)^{x - 2} \\
&= (1 - p)\left(1 - p\right)^{x-2} -  (p x - p) \left(1 - p\right)^{x - 2} \\
&=  (1 - p - p x + p) \left(1 - p\right)^{x - 2} \\
&=  (1 - p x) \left(1 - p\right)^{x - 2}.
\end{aligned}
$$
Setting this equal to zero (since the derivative of $L(p \mid x)$ at $p$ is zero if $L(p \mid x)$ is at a maximum), we get
$$
(1 - p x) \left(1 - p\right)^{x - 2} = 0.
$$
Assuming $p < 1$, it follows that $\left(1 - p\right)^{x - 2} \neq 0$, so $1 - p x = 0$, and hence $p = 1 / x$.
Thus, the maximum likelihood estimate of $p$ is
$$
\hat{p} = \frac{1}{x}.
$$
Comment: You should avoid giving out questions to homework questions.  Instead, consider giving hints.
Comment: @Ben sure, but this case is so easy there's no need to take logs in my opinion
Comment: Agree - either method is fine in this case.
Comment: Just to improve this answer, may I recommend that you use $\hat{p}$ to denote the estimator, rather than $p$.  Also, it would be worth flagging what happens to the MLE when $x=0$, since in that case, your expression for the estimator is undefined.
Comment: @StatsStudent I think sometimes it's useful to see an entire answer worked out so that you can learn how to approach similar problems
Comment: I agree.  But surely this isn't the student's first time being introduced to the material.  The OP didn't even attempt to comply with the site's self-study "policies" by telling you what he/she has tried.  Not a big deal.  Just keep it in mind for future homework questions.
Comment: @Ben thanks for the suggestion for using $\hat{p}$! Regarding the $x = 0$ case: I don't think that's possible given the wording of the question. I interpreted $x$ as the number of trials until a success (including the success) which makes $x$ at least $1$
Comment: In general, for multiple realizations of $X$, the likelihood should involve a product, and thus, the log likelihood will involve a sum. Writing down the log of the likelihood function prior to differentiating will make things much easier...
Comment: @compbiostats the question says "given a single observation x of X"
Comment: Even with one observation, the likelihood is still a product of two terms in $p$, so maximising the log-likelihood is simpler.
Comment: @ArtemMavrin Whoops... I see that now :) I've edited my previous comment to reflect this.
Comment: Thanks, that matches what one of mates told me the answer was. That makes senses now seeing the working out.
Comment: @ArtemMavrin Thanks for showing it worked out. Really obvious now seeing this, and I can see where I was going wrong as I was just over complicating it in my attempts
Comment: @StatsStudent thank you for the feedback. I will keep that in mind in the future
Comment: @Artem Mavrin: I think you're right about $x$ - I stand corrected.
Answer: Since you have a single observation, you have $n=1$.  So the likelihood function for the observed data is:
$$L_x(p) = p(1-p)^{x-1} \quad \quad \quad \text{for all } 0 \leqslant p \leqslant 1.$$
As the name suggests, the maximum-likelihood estimator is the value that maximises the likelihood function:
$$\hat{p}(x) = \underset{0 \leqslant p \leqslant 1}{\text{arg max }} L_x(p)$$
In this particular case, this is just a basic calculus problem, where you are trying to maximise the likelihood function with respect to a continuous argument variable.  Since the likelihood function is a product of non-negative parts that depend on $p$, it is usual to find the maximising value by maximising the log-likelihood function (i.e., the logarithm of the likelihood function).  If you apply standard calculus methods to maximise this function, you will be able to derive the maximum-likelihood estimator $\hat{p}$.


How to create a button that sets a node value

Question: I would like to create a set of buttons or text links on my site that set the value of a node field and/or create additional nodes.  Currently, I am using a combination of flags and rules to do this (when a flag is set, do the following...) This works fine, but it feels a bit cumbersome.  The flag has no other purpose other than triggering an action.  Is there a module specifically for doing this (including ajax) or is there another simpler way to perform this activity?
Answer: There is a Field Button module that creates and renders a button.  You can then write a rule that is triggered by button clicks.  This works great if you only need one or two buttons on a page.  However, this module has trouble figuring out which node the button belongs to (and therefor may not be a good option for lists of nodes & buttons rendered by views.)
Another option is the Rules Link module.  This module does roughly the same thing.  It  is not as pretty, but it has better rule integration.


A,B,C,D,E,F,G and H in boxes in piano sheet music, how do I play it?

Question:
Sorry I probably just too new but all of those letters are in piece I want to play. What is that letter and how should I play it?
Comment: They are rehearsal marks and they are especially pretty useful for music written for two or more musicians. They don't make much sense in solo music if you are not heavily practicing a giant solo piece with a trainer.
Answer: Both are right, these marks are to denote the section you are playing and you don't play anything specifically for them. The proper name for these marks are rehearsal marks.
In an sense you can look at them as practice checkpoints as they are typically where you would want to start playing if you needed more practice on that section instead of playing the whole piece. It is much easier to reference a section by letter rather than measure number which can not only be hard to spot, but can lead to problems if you need to count the measures on your score as sometimes counting is hard.
Answer: Those letters are just section identification. They are not meant to indicate notes to play. You might use them in a rehearsal where someone says "Ok let's all play section C now".
Answer: They aren't played.
They are used to identify parts of the composition. This way you are able to communicate about the piece by using the letters.


C Programming: How to add up divisors of an integer n

Question: I was wondering, how can I add up the divisors displayed once I run my code?
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int n, i;
    scanf("%d", &n);

    for(i = 1; i < n; i++)
    {
        if(n % i == 0)
        {
            printf("%d\n", i);
        }
    }
    return 0;
}

If I were to enter, say, 25, it would print out 1, 5. I was wondering how to add up the two numbers 1 and 5?
Comment: I didn't say `add(n)`.
Answer: Could it be as simple as this? You will want to use a simple increment operator (+=), to increment the variable sum.
int main(void)
{
    int n, i, sum = 0;
    if( scanf("%d", &n)!= 1){
        fprintf(stderr,"Error in input\n");
        exit(EXIT_FAILURE);
    }

    for(i = 1; i < n; i++)
    {
        if(n % i == 0)
        {
            printf("%d\n", i);
            sum += i;
        }
    }
    printf("Sum of divisors: %d\n", sum);
    return 0;
}

Comment: Important nit: always, always validate ALL user input. (yes, I know this is a short example, but `if (scanf ("%d", &n) != 1) { /* handle error */ }`)
Answer:
How to add up divisors of an integer n?

Iterating n times as with for(i = 1; i < n; i++) can take a long time when n is some high value, especially if code used 64-bit integers.  Instead only iterate sqrt(n) times - much faster
int factor_count(int number) {
  if (number <= 1) {
    return TBD_Code(number);  // OP needs to define functionality for these cases.
  }
  int sum = 1;
  int quotient;
  int divisor = 1;
  do {
    divisor++;
    quotient = number/divisor;
    int remainder = number%divisor;
    if (remainder == 0) {
      sum += divisor;
      if (quotient > divisor) sum += quotient;
    }
  } while (divisor < quotient);
  return sum;
}

Additional improvements noted here.


Resgatar valor de uma string em uma array

Question: Como faço para pegar uma string dentro de uma array como a do exemplo a baixo:

<code>array(2) {
    ["data"]=> array(1) {
        ["charges"]=> array(1) {
            [0]=> array(8) {
                ["code"]=> int(433528162)
                ["reference"]=> string(0) ""
                ["dueDate"]=> string(10) "22/04/2019"
                ["checkoutUrl"]=> string(100) "https://www.boletobancario.com/boletofacil/checkout/6E13300AFACDEE50594094562346gsfgwertE683D98BBE076EF"
                ["link"]=> string(142) "https://www.boletobancario.com/boletofacil/charge/boleto.pdf?token=22904578:m:0bcf68c9aefc1f558218562a9efbad42bbefeabe82b248a437d66344950ba460"
                ["installmentLink"]=> string(140) "https://www.boletobancario.com/boletofacil/charge/boleto.pdf?token=43188162:562c5278b4ac529291a711d461a721311b86da6ed1f0e02ba0e85848e0f37821"
                ["payNumber"]=> string(54) "34190001275"
                ["billetDetails"]=> array(4) {
                    ["bankAccount"]=> string(12) "06"
                    ["ourNumber"]=> string(14) "102-4"
                    ["barcodeNumber"]=> string(44) "34196786700000012751094318816240655464808000"
                    ["portfolio"]=> string(3) "109"
                }
            }
        }
    } ["success"]=> bool(true)
} </code>

A que quero resgatar é a ["checkoutUrl"] para fazer um redirecionamento;
Answer: Ola! para pegar o valor vc precisa acessar as chaves do array. Assuma que a variável $array é onde está guardado o valor do array acima. Neste caso:
<code>$checkoutUrl = $array["data"]["charges"][0]["checkoutUrl"];
</code>
Veja o exemplo abaixo:
<code>        $array = [
        'data' => [
            'charges' => [
                0 => [
                    'code' => 433528162,
                    'reference' =>'',
                    'dueDate' => '22/04/2019',
                    'checkoutUrl' => 'https://www.boletobancario.com/boletofacil/checkout/6E13300AFACDEE50594094562346gsfgwertE683D98BBE076EF',
                    'link' => 'https://www.boletobancario.com/boletofacil/charge/boleto.pdf?token=22904578:m:0bcf68c9aefc1f558218562a9efbad42bbefeabe82b248a437d66344950ba460',
                    'installmentLink' => 'https://www.boletobancario.com/boletofacil/charge/boleto.pdf?token=43188162:562c5278b4ac529291a711d461a721311b86da6ed1f0e02ba0e85848e0f37821',
                    'payNumber' => '34190001275',
                    'billetDetails' => [
                        'bankAccount' => '06',
                        'ourNumber' => '102-4',
                        'barcodeNumber' => '34196786700000012751094318816240655464808000',
                        'portfolio' => '109',
                    ]
                ]
            ]
        ],
        'success' => true
    ];

    echo $array['data']['charges'][0]['checkoutUrl'];
</code>


Law of Random Variable is Always a Measure?

Question: I have a conceptual question regarding the law of a random variable in probability theory.
Suppose we begin with a probability space $(\Omega,F,P)$. We also endow a measurable space of reals with its Borel $\sigma$-algebra, $(\mathbb{R},B(\mathbb{R}))$.
Given $X$ is a real-valued random variable, we define the distribution measure of law of $X$ as
$$P_X(B)=P(X^{-1}(B))=(P\circ X^{-1})(B)-P(\omega:X(\omega)\in B)=P(X\in B).$$
Then, the law of $X$ is entirely characterized by its cumulative distribution function such that:
$$F_X(x)=P_X((\infty,x])=P(X\leq x).$$
My understanding is:
$P:F\rightarrow [0,1]$.
$P_X:B(\mathbb{R})\rightarrow[0,1].$
Hence, the law of $X$ is a probability density on the measruable space $(\mathbb{R},B(\mathbb{R})).$
(1) Does this mean any two random variables that are from distinct distributions have their own probability distribution on the space $(\mathbb{R},B(\mathbb{R}))$? In other words, is there distinct laws for each distinct random variable?
(2) A random variable is just a measurable function from one measurable space to another, say $(E,A),(F,B)$. Is it possible for the law of $X$ not be a non-negative and $\sigma$-finite measure defined on $(F,B)$. In other words, does the way we define and characterize the law of $X$ in probability have to do with some "nice" properties of reals or the Borel sigma algebra of reals?
Answer: (1) Yes, by definition $X\stackrel{d}{=} Y$ ($X$ is equal to $Y$ in distribution) iff the laws of $X$ and $Y$ coincide, that is $P_X = P_Y$.
But it is possible that $X \neq Y$ yet $P_X = P_Y$. For example, if $X\sim\mathcal{N}(0,1)$, then $-X \sim \mathcal{N}(0,1)$ as well but $X \neq -X$.
(2) A random variable is by definition a measurable function $X:(\Omega, \mathcal{F}) \to (E, \mathcal{E})$ where $(\Omega, \mathcal{F}, P)$ is a probability space. In this case, the law of $X$ is a measure (this is a special case of image measure)
$$P_X: \mathcal{E} \to [0,1]$$
and in particular, $P_X$ is positive and finite, so also $\sigma$-finite.


The call "nets" in tennis, details

Question: Question: If I used up my first serve, then am serving my second serve, and the ball hits the net and into the correct sector(meaning if the ball would hit that surface directly without hitting the net on the way, akka a valid serve) that is called "nets" ? The rule would have to be , me serving the first serve again, even though "I've already served the first serve" am I correct? What if nets happens again, be it on the first or second serve, do we have the same situation?
Answer: The rule you're looking for is: ITF Rule 23 – "The Let"

In all cases when a let is called, except when a service let is called on a second service, the whole point shall be replayed.

The situation outlined in the question would be a 'service let' on the 2nd service as the ball touched the net before crossing it.  As a result you would remain on 2nd serve.
If something else had caused the let (for example a stray ball from another court) then the point would be replayed from 1st service.
Umpires often clarify the call by reiterating which service is being played.  For example "Let - 2nd Service" for the sake of clarity.
Comment: @JimLowe: *"But, correct me if i'm wrong in the ATP tour, i think I've seen the first serve replayed after a second serve let?"* No, once the first serve is gone, it's gone.
Comment: But, correct me if i'm wrong in the ATP tour, i think I've seen the first serve replayed after a second serve let?
Comment: The ITF rule looks pretty clear.  I can't see that an ATP umpire would make a mistake like that but they're only human - if they did a player at that level ought to pick up on it and say something.

The call "nets" in tennis, details


Proving $x^n - y^n = (x-y)(x^{n-1} + x^{n-2} y + ... + x y^{n-2} + y^{n-1})$

Question: In Spivak's Calculus 3rd Edition, there is an exercise to prove the following:
$$x^n - y^n = (x-y)(x^{n-1} + x^{n-2} y + ... + x y^{n-2} + y^{n-1})$$
I can't seem to get the answer. Either I've gone wrong somewhere, I'm overlooking something, or both. Here's my (non) proof:
$$\begin{align*}
x^n - y^n &= (x - y)(x^{n-1} + x^{n-2}y +\cdots+ xy^{n-2} + y^{n-1}) \\
          &= x \cdot x^{n-1} + x \cdot x^{n-2} \cdot y + \cdots + x \cdot x \cdot y^{n-2} + x \cdot y^{n-1}\\
&\qquad + (-y) \cdot x^{n-1} + (-y) \cdot x^{n-2} \cdot y + \cdots + (-y) \cdot x \cdot y^{n-2} + (-y) \cdot y^{n-1}\\
          &= x^n + x^{n-1} y + \cdots + x^2 y^{n-2} + x y^{n-1} - x^{n-1}y - y^2 x^{n-2}  - \cdots- x y^{n-1} - y^n \\
          &= x^n + x^2 y^{n-2} - x^{n-2} y^2 - y^n  \\
          &\neq x^n - y^n
\end{align*}$$
Is there something I can do with $x^n + x^2 y^{n-2} - x^{n-2} y^2 - y^n$ that I'm not seeing, or did I make a mistake early on?
EDIT:
I should have pointed out that this exercise is meant to be done using nine of the twelve basic properties of numbers that Spivak outlines in his book:

Associate law for addition
Existence of an additive identity
Existence of additive inverses
Commutative law for additions
Associative law for multiplication
Existence of a multiplicative identity
Existence of multiplicative inverses
Commutative law for multiplication
Distibutive law
Comment: Alternatively, you can use induction by writing $x^n-y^n = x(x^{n-1}-y^{n-1}) + (x-y)y^{n-1}$.
Comment: Write out your expanded expression in two rows multiplying first by $x$ to get the first row and then by $-y$ to get the second row. If you write the second row so that expressions with the same power of $x$ are underneath each other, and do an extra term or two at the beginning and the end, you should detect quite easily what has gone wrong.
Comment: I'll give this a try and let you know how it goes.
Comment: Be carefull the ... from the first and second part are not the same thing ;) So you cannot cancel ... by ....
Comment: Another possibility is to write $x^n-y^n = x^n\left(1-\left(y/x\right)^n\right)$ (the case $x=0$ is trivial) and then use the geometric sum formula.
Comment: See the question [Algebraic Identity $a^{n}-b^{n} = (a-b) \sum\limits_{k=0}^{n-1} a^{k}b^{n-1-k}$](http://math.stackexchange.com/q/11618/752). You can apply [Ruffini's rule](http://en.wikipedia.org/wiki/Ruffini's_rule).
I have applied it in [my anwer](http://math.stackexchange.com/a/11684/752).
Comment: Use synthetic divison
Answer: You have everything right except the last line.
Maybe it is easier to do in this order:
$$(x−y)\left(x^{n−1}+x^{n−2}y+\cdots+xy^{n−2}+y^{n−1}\right)=\\
=x\cdot x^{n-1}-y\cdot x^{n-1} +x\cdot x^{n−2}y-
y\cdot x^{n−2}y+x\cdot x^{n−3}y^2-\cdots\\  \cdots -y\cdot x^2y^{n-3} +x\cdot xy^{n-2}-y \cdot y^{n-1}$$
The second term $y\cdot x^{n-1}$ is the same as the third term $x\cdot x^{n−2}y$  except the sign, similarly the 4th and the 5th terms are canceled... So the only terms left are: $x\cdot x^{n-1}$ and $y\cdot y^{n-1}$.
Comment: This leaves me in the exact same position that I'm in now ..
Comment: In your opening post, you (mistakenly) had two terms in addition to the ones grozhd points out are left
Comment: This could have been better explained, although I see what you did now. You added an extra term before the $...$ and multiplied it by $x$. Then you added another term after the $...$ and multiplied it by $(-y)$.

Thanks!
Comment: ohhhh I see why you started with $-y*x^2y^n-3$ after the ellipsis and not the $x*x^2y^n-3$... it's because $$-y*x^2y^n-3$$ cancels with the 2nd to last term because they are =
Answer: I think it would be easier for you to recall
$$\left(1+x+x^2+\cdots+x^{n-1}\right)(x-1) = x^n-1$$
and put $x=\dfrac{b}{a}$
$$\eqalign{
  & \left( {1 + \frac{b}{a} + \frac{{{b^2}}}{{{a^2}}} +  \cdots  + \frac{{{b^{n - 1}}}}{{{a^{n - 1}}}}} \right)\left( {\frac{b}{a} - 1} \right) = \frac{{{b^n}}}{{{a^n}}} - 1  \cr
  & \left( {1 + \frac{b}{a} + \frac{{{b^2}}}{{{a^2}}} +  \cdots  + \frac{{{b^{n - 1}}}}{{{a^{n - 1}}}}} \right)\left( {\frac{{b - a}}{a}} \right) = \frac{{{b^n} - {a^n}}}{{{a^n}}}  \cr
  & {a^{n - 1}}\left( {1 + \frac{b}{a} + \frac{{{b^2}}}{{{a^2}}} +  \cdots  + \frac{{{b^{n - 1}}}}{{{a^{n - 1}}}}} \right)\left( {b - a} \right) = {b^n} - {a^n}  \cr
  & \left( {{a^{n - 1}} + b{a^{n - 2}} + {b^2}{a^{n - 3}} +  \cdots  + {b^{n - 1}}} \right)\left( {b - a} \right) = {b^n} - {a^n} \cr} $$
A little bit "tidier", so that we know what happens in between the dots...
$$\eqalign{
  & {x^n} - 1 = \left( {x - 1} \right)\sum\limits_{k = 0}^{n - 1} {{x^k}}   \cr
  & \frac{{{b^n}}}{{{a^n}}} - 1 = \left( {\frac{b}{a} - 1} \right)\sum\limits_{k = 0}^{n - 1} {\frac{{{b^k}}}{{{a^k}}}}   \cr
  & \frac{{{b^n} - {a^n}}}{{{a^n}}} = \left( {\frac{{b - a}}{a}} \right)\sum\limits_{k = 0}^{n - 1} {\frac{{{b^k}}}{{{a^k}}}}   \cr
  & {b^n} - {a^n} = \left( {b - a} \right)\sum\limits_{k = 0}^{n - 1} {{b^k}{a^{n - k - 1}}}  \cr} $$
Answer: Here is the inductive step, presented more conceptually
$$\rm\frac{x^{n+1}-y^{n+1}}{x-y}\: =\ x^n\: +\ y\ \frac{x^n-y^n}{x-y}$$
So, intuitively, proceeding inductively yields
$$\rm\:x^n + y\: (x^{n-1} + y\: (x^{n-2} +\:\cdots\:))\ =\ x^n + y\: x^{n-1} + y^2\: x^{n-2} + \:\cdots $$
Use this intuition to compose a formal proof by induction.
Comment: It should be possible to prove this using the basic properties of numbers discussed in Spivak's book: Associative law for addition, Existence of an additive identify, Existence of additive inverses, Commutative law for addition, Associative law for multiplication, Existence of a multiplicative identity, Existence of multiplicative inverses, Commutative law for multiplication, and Distributive law.
Answer: Your method is sound, you just made a sort of arithmetic mistake. When cancelling or otherwise combining two sequences, try explicitly lining things up to make sure you do it right:
$$  \begin{align} x^n &+& x^{n-1} y &+& x^{n-2} y^2 &+& \cdots + x y^{n-1} &
\\ &-& x^{n-1} y &-& x^{n-2} y^2 &+& \cdots - x y^{n-1} &+&  y^n
\end{align}
$$
I've found that, when  shorthand starts becoming awkward and/or error prone, that it really is helpful to switch to summation notation. So, you are trying to prove
$$ x^n - y^n = (x-y) \sum_{k=0}^{n-1} x^k y^{n-1-k} $$
and the first stem of your work would be
$$ \cdots = \left( \sum_{k=0}^{n-1} x^{k+1} y^{n-1-k} \right)
- \left( \sum_{k=0}^{n-1} x^{k} y^{n-k} \right)$$
and now, we can change the index to line things up: I'm substituting k = j-1:
$$ \cdots = \left( \sum_{(j-1)=0}^{n-1} x^{(j-1)+1} y^{n-1-(j-1)} \right)
- \left( \sum_{k=0}^{n-1} x^{k} y^{n-k} \right)$$
and simplifying
$$ \cdots = \left( \sum_{j=1}^{n} x^{j} y^{n-j} \right)
- \left( \sum_{k=0}^{n-1} x^{k} y^{n-k} \right)$$
and now replacing $j$ with $k$.
$$ \cdots = \left( \sum_{k=1}^{n} x^{k} y^{n-k} \right)
- \left( \sum_{k=0}^{n-1} x^{k} y^{n-k} \right)$$
(can you take it from here?)
Comment: I don't follow, can you explain?
Answer: The $x^2 y^{n-2}$ term from $x \cdot x y^{n-2}$ is cancelled by the term from $(-y) \cdot
x^2 y^{n-3}$.  Similarly, the $(-y) \cdot x^{n-2} y$ is cancelled by the $x \cdot x^{n-3} y^2$.
Answer: Since powers of x and y is always greater than or equal to zero, You can prove it by mathematical induction.
Answer: Sorry but I don't speak English well but I will try to write as correctly as possible.
Your demonstration is correct, but your idea of cancellation is incorrect.
$x^n−y^n=(x−y)(x^\left(n−1\right)+x^\left(n−2\right)y+⋯+xy^\left(n−2\right)+y^\left(n−1\right))$
When we multiply first for 'x' to our terms of the second parenthesis let's notice that all terms that contains 'x' go up one grade, this by exponent laws.
When we multiplies for 'y' to our terms of the second parenthesis let's notice that all terms that contains y go up one grade but the terms that contains x remain the same.
Therefore at the moment to cancel our terms, "ellipsis" of the formula cancel the terms left over in your demostration.
This is your result  $x^n+x^2y^\left(n−2\right)−x^\left(n−2\right)y^2−y^n$ the extra term $+x^2y^\left(n−2\right)$is "cancel" by the "ellipsis" because the term that is not visible but is in the "ellipsis" in the second parenthesis is
$(x^\left(n−1\right)+x^\left(n−2\right)y+⋯ (x^2y^\left(n-3\right)) ⋯+xy^\left(n−2\right)+y^\left(n−1\right)$ because on the left one degree goes up the 'x' and one degree goes down the y and cancel your term. Analogously the other extra term $-x^\left(n−2\right)y^2$ is cancel by the other "ellipsis" that came out of the first multiplication by x.
$x^n−y^n=(x−y)(x^\left(n−1\right)+x^\left(n−2\right)y+⋯+xy^\left(n−2\right)+y^\left(n−1\right))$
Dem.
By distributive law we have
$x(x^\left(n-1\right)+x^\left(n-2\right)y+...+xy^\left(n-2\right)+y^\left(n-1\right))$
$-y(x^\left(n-1\right)+x^\left(n-2\right)y+...+xy^\left(n-2\right)+y^\left(n-1\right))$   from where

$\quad x^n+x^\left(n-1\right)y+.........+x^2y^\left(n-2\right)+xy^\left(n-1\right)$
$\qquad -(x^\left(n-1\right)y+x^\left(n-2\right)y^2+.........+xy^\left(n-1\right)+y^n)$ therefore
$x^n-y^n$
Comment: Thank you. I also had the idea of cancellation. Thank you for explaining that the ellipsis has it's own rules
Answer: Since $x^{n-1} + x^{n-2} y + \dots + x y^{n-2} + y^{n-1}$ is a geometric series with $n$ terms and a common factor of $y/x$, it equals
$$
\frac{x^{n-1}\left(1-\left(\frac{y}{x}\right)^n\right)}{1-\frac{y}{x}}=\frac{x^{n}\left(1-\left(\frac{y}{x}\right)^n\right)}{x-y}=\frac{x^n-y^n}{x-y} \, ;
$$
multiplying through by $(x-y)$ gives the desired result.
Answer: Using Induction Hypothesis
Let n =k
Then ,
x^k -y^k = (x-y)(x^(k-1) +x^(k-2) y ....+y^k-1)
Let n= (k-1)
Then by Induction Hypothesis,
(x-y){x(x^(k-1) +x^(k-2) y) +y^k }
=» (x-y)(x^k +x^(k-1) y ... +y^k
Hence the formula is true for k+1 whenever true for k .
Therefore by Principle of Induction The formula is true for Positive Integers n≥2 .
Reference = Challenges and Thrills of Pre College Mathematics .
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


How to reuse type constraints, and parameters, of a parent function in inner functions in Haskell?

Question: I'm trying to refactor this tutorial exercise answer below, but I'm having trouble.
First, I would like to use the arr parameter declared in the outer function in the inner functions. I assume it would be in scope, just as it would in Javascript.
So this:
maxIndex :: (Ix sourceIndexType, Ord sourceElementType) => Array sourceIndexType sourceElementType -> sourceIndexType
maxIndex arr = findLargestIndexOfElement arr (findLargestElement arr)
    where
        findLargestElement :: (Ix sourceIndexType, Ord sourceElementType) => Array sourceIndexType sourceElementType -> sourceElementType
        findLargestElement arr = maximum $ elems arr
        findLargestIndexOfElement :: (Ix sourceIndexType, Ord sourceElementType) => Array sourceIndexType sourceElementType -> sourceElementType -> sourceIndexType
        findLargestIndexOfElement arr element = fst $ foldr1 (\(itemk,itemv) (acck, accv) -> if element==itemv then (itemk,itemv) else (acck,accv)) (assocs arr)

becomes
maxIndex :: (Ix sourceIndexType, Ord sourceElementType) => Array sourceIndexType sourceElementType -> sourceIndexType
maxIndex arr = findLargestIndexOfElement arr findLargestElement
    where
        findLargestElement :: sourceElementType
        findLargestElement = maximum $ elems arr
        findLargestIndexOfElement :: sourceElementType -> sourceIndexType
        findLargestIndexOfElement element = fst $ foldr1 (\(itemk,itemv) (acck, accv) -> if element==itemv then (itemk,itemv) else (acck,accv)) (assocs arr)

but Haskell doesn't seem to be able to access any higher level definitions from an inner function. Am I right in my understanding? Haskell isn't able to do this?
The next simplification I want to do is reuse my parameters' type constraints. So the original code would become:
maxIndex :: (Ix sourceIndexType, Ord sourceElementType) => Array sourceIndexType sourceElementType -> sourceIndexType
maxIndex arr = findLargestIndexOfElement arr (findLargestElement arr)
    where
        findLargestElement :: Array sourceIndexType sourceElementType -> sourceElementType
        findLargestElement arr = maximum $ elems arr
        findLargestIndexOfElement :: Array sourceIndexType sourceElementType -> sourceElementType -> sourceIndexType
        findLargestIndexOfElement arr element = fst $ foldr1 (\(itemk,itemv) (acck, accv) -> if element==itemv then (itemk,itemv) else (acck,accv)) (assocs arr)

but this change also makes Haskell error. It completely ignores that sourceIndexType in any of the functions is the same type. I may as well call them all paramType1 paramType2 blue58. How do I make Haskell understand I'm using the same type for each??
Thanks.
Answer: Haskell type variables have by default only a single type-signature as their scope, even when -XScopedTypeVariables is enabled. To make the whole function to which this is the signature as the scope, you need to explicitly quantify the type variables.
{-# LANGUAGE ScopedTypeVariables, UnicodeSyntax #-}

maxIndex :: ∀ sIt sEt. (Ix sIt, Ord sEt) => Array sIt sEt -> sIt
maxIndex arr = findLargestIndexOfElement arr largestElement
  where
    largestElement :: sEt
    largestElement = maximum $ elems arr
    findLargestIndexOfElement :: sEt -> sIt
    findLargestIndexOfElement element
        = fst $ foldr1 (\(itemk,itemv) (acck, accv)
                          -> if element==itemv then (itemk,itemv)
                                               else (acck,accv))
                       (assocs arr)

Comment: Thank you, this code doesn't seem to compile though
Comment: Well, so what's the error?
Comment: If it's something unicode related, use `forall` instead of the upside-down A


Criar documento WORD de dados com Java - Genexus 9.0

Question: Estou com uma aplicação Genexus 9.0 VFP WIN e tenho que converter para Genexus 9.0 JAVA WEB.
Tenho no sistema com VFP WIN funcionando perfeitamente onde é gerado um arquivo .DOC e através de comandos dbase Exemplo:
<code>dbase obj.ActiveDocument.MailMerge.Fields.Add(obj.Selection.Range, gx_msg)
dbase obj.Selection.TypeParagraph)
dbase obj.Selection.MoveRight(12)
</code>
É gerado um documento e abre este documento em formato de visão de dados no WORD.
Alguém pode me dizer se existe os mesmos comando equivalentes em java?
Ou posso criar uma rotina externa em JAVA para fazer este processo?
Answer: Eduardo,
Acredito que a melhor alternativa seja começar a utilizar os tipos de dados WordDocument, que são nativos e suportados pela GeneXus.
Podes obter mais informações nesse link:
http://wiki.genexus.com/commwiki/servlet/wiki?2101,Generating+Excel+and+Word+Documents,
Comment: Bom dia Sandro, tudo bem?
Já tentei, o problema é que estou usando Genexus 9.0 java WEB e pelo que andei consultando não funciona. Vi várias pessoas reclamando.
Eu estou fazendo uma conversão do GX 9.0 VFP WEB para GX 9.0 Java WEB e tenho várias rotinas paradas por causa deste problema.
Por isso estava pensando fazer alguma coisa por fora.
Comment: Eduardo, não há restrição alguma quanto a ser web, exceto pelos componentes que provavelmente terá que botar na pasta lib do tomcat...
Já fizemos isso em projetos, mas como faz algum tempo, não lembro exatamente quais são, mas sim, é possível...

Mais informações: https://www.genexus.com/developers/websac?en,,,18847;;
Comment: Muito obrigado.
Comment: Se a resposta foi satisfatória, agradeço se puder votá-la para que outras pessoas que tenham a mesma dúvida possam ser ajudadas.


How do I render a form with JavaScript?

Question: I'm trying to render a Drupal 8 modal dialog form through JavaScript, so it can appear on multiple pages across my site. In the controller class, I create an AjaxResponse object with an openModalDialogCommand for the modal form. I want to render the modal dialog through JavaScript, so that I can control in which pages it displays.
$(document).ready(function() {
  $('body').append('

');
  console.log(Drupal);
  jQuery('#ao-interstitial-modal').load('/aao_additions/modal_form');
});

This the JavaScript code I write so far, but it renders a textarea in the body tag with the AJAX command object as text inside it.
What do I need to do to render the form as a dialog popup?
Comment: You shouldn't need any JavaScript for that. But please edit your question and try to explain exactly what you are trying to do and why? What form? Where on the page exactly? Do you have any sample use case?
Answer: Loading a form via ajax is no different then loading any other page with ajax. The quick answer is that you should create a route to display the form and then call that route via ajax but for a detailed description you should take a look here: https://www.drupal.org/node/2046693

How do I render a form with JavaScript?