Prove $Z_n = X_n1_{n \le T} + Y_n1_{n+1\ge T}$ is a martingale

Question: Given a filtered probability space $(\Omega, \mathscr F, \{\mathscr F_n\}, \mathbb P)$, let $X = (X_n)_{n \in \mathbb N}$ and $Y = (Y_n)_{n \in \mathbb N}$ be $(\{\mathscr F_n\}, \mathbb P)-$martingales and $T$ be a $\{\mathscr F_n\}$-stopping time s.t. $X_T = Y_T$
Prove $Z_n = X_n1_{n \le T} + Y_n1_{n-1\ge T}$ is a $(\{\mathscr F_n\}, \mathbb P)-$martingale.

What I tried:

Integrable:

$X_n, Y_n, 1_{n \le T}, 1_{n-1\ge T}$ are integrable

Adapted to $\{\mathscr F_n\}$:

$X_n, Y_n, 1_{n \le T}, 1_{n-1\ge T}$ are adapted because $X$ and $Y$ are martingales and $T$ is a stopping time

$$E[Z_n | \mathscr F_{m}] = Z_{m}$$

Not sure I can do that directly, but I guess can make use of:
$$E[Z_n | \mathscr F_{m}] = E[E[Z_n|\mathscr F_{n-1}] | \mathscr F_{m}] = E[Z_{n-1} | \mathscr F_{m}] = ... = E[Z_m | \mathscr F_{m}] = Z_m$$
by showing that $Z_{n-1} = E[Z_n|\mathscr F_{n-1}]$:
$$E[Z_n | \mathscr F_{n-1}] = E[X_n1_{n \le T} + Y_n1_{n-1\ge T} | \mathscr F_{n-1}]$$
$$= E[X_n1_{n \le T} | \mathscr F_{n-1}] + E[Y_n1_{n-1\ge T} | \mathscr F_{n-1}]$$
$$= 1_{n \le T} E[X_n | \mathscr F_{n-1}] + 1_{n-1\ge T}E[Y_n | \mathscr F_{n-1}]$$
$$= 1_{n \le T} X_{n-1} + 1_{n-1\ge T}Y_{n-1}$$
$\because Y_{n-1}1_{T=n-1} = Y_{T}1_{T=n-1} = X_{T}1_{T=n-1} = X_{n-1}1_{T=n-1}$, we have
$$= 1_{(n-1) \le T} X_{n-1} + 1_{n-2\ge T}Y_{n-1}$$
Is that right?
Comment: Is there any relationship between the two martingales? I don't think this is true as currently stated. For example take $T$ constant, and let $X_n=1$ for all $n$, $Y_n=2$ for all $n$.
Answer: Your argument is basically correct.
Two comments, points where you could make your argument clearer or make your job easier :

Integrability: the product of two integrable random variables is not necessarily integrable, however in this case $1_{n \le T}$ and $1_{n-1\ge T}$ are bounded (by 1) so the products $X_n1_{n \le T}$ and $Y_n1_{n-1\ge T}$ are integrable.
Martingale property. This would often be stated as $Z_{n-1} = E[Z_n|\mathscr F_{n-1}]$ (as in Williams' book "Probability with Martingales", Section 10.3), so you don't need to start from the more general property $E[Z_n | \mathscr F_{m}] = Z_{m}$  (for all $n>m$).
Comment: Good point. Maybe there are other texts that use the more general martingale property definition... but Williams' definition makes your work slightly easier.
Comment: Thanks S. Catterall. ^-^ Integrability: I knew that. Apologies for not making clear. 2 Ah, forgot about that. Guess it depends on the text.


Inverse of $\psi(t,s)=(e^t,se^{2t})$

Question: I am trying to solve a problem involving finding the inverse of this map
$$\psi:\mathbb{R}^2\to \mathbb{R}^2$$
$$\psi(t,s)=(e^t,se^{2t})$$
Here is what I am thinking
Let $x=e^t$ and $y=se^{2t}$.
Exchange $x,y$ and $s,t$.
$t=e^x$ and $s=ye^{2x}$.
Solving for $x$ and $y$,
$x=\ln (t)$ and $y=e^{s-2\ln (\ln(t))}$
Hence
$\psi^{-1}(x,y)=(\ln (x), e^{y-2\ln (\ln(x))})$
I computed $\psi\circ \psi^{-1} $ but didn't get the identity, so I guess there is a mistake. Any help would be appreciated. Thank you.
Comment: I think you have $\log\log$ where you just want $\log$.
Answer: $\psi$ is not a bijection since the range is contained in $\{(x,y): x >0\}$
If you restrict the codomain to this set you can find the inverse as follows: $t=\ln x$ and $s=ye^{-2t}=ye^{-2\ln x}=y/x^{2}$
So $\psi^{-1}(x,y)=(\ln x ,  yx^{-2})$ on $\{(x,y): x>0, y \in \mathbb R\}$.

Inverse of $\psi(t,s)=(e^t,se^{2t})$


Has W.A.R. been used in this fashion?

Question: Whether justifiably or not, in modern baseball conversations, W.A.R. (wins above replacement) has become the goto statistic to qualify who's the best in the game.
My question is, can it be applied to teams?  And has it?
What I mean is:  say we figured out the record of an all replacement level squad -  it seems like it would vary based upon the year, but for ease of this question, let's say 62 wins, 100 losses.
Maybe it should be less, but whatever the case, what we're talking about here is the win-loss record for a team with a combined W.A.R. of 0.0.
Now - if we took at a team with 92 wins and 70 losses, how close would their record come to their combined team W.A.R.?  In other words, could we expect them to have a combined team W.A.R. of 30?  If not; why not?
Is there any sort of statistical interest in combined team W.A.R., and / or has any sort of analysis been done to see how closely team W.A.R. correlates to actual Wins and Losses?
And if it doesn't correlate in that manner, shouldn't the name be changed?
Answer: There has been analysis done to look at the correlation between individual WAR and the record of teams. Most entities that calculate WAR make the same assumption that a team full of replacement level players would win about 52 games in a season (.320 Win %).
Below are 2 links that show high correlation when studying the relationship between WAR and team records. Hardball is more in depth and (mostly) impartial. FanGraphs is more of a summary and could be less impartial.
Hardball Times WAR Study
FanGraphs WAR Study

Has W.A.R. been used in this fashion?


Child process won't suicide if parent dies

Question: I have a subprocess (running on MacOS) that I want to kill itself if the parent quits, exits, terminates, is killed or crashes. Having followed the advice from How to make child process die after parent exits? I can't get it to quietly kill itself if the parent program crashes. It will go to 100% CPU until I manually kill it.
Here are the key points of the code:
int main(int argc, char *argv[])
{
  // Catch signals
  signal(SIGINT,  interruptHandler);
  signal(SIGABRT, interruptHandler);
  signal(SIGTERM, interruptHandler);
  signal(SIGPIPE, interruptHandler);

  // Create kqueue event filter
  int kqueue_fd = kqueue();
  struct kevent kev, recv_kev;
  EV_SET(&kev, parent_pid, EVFILT_PROC, EV_ADD|EV_ENABLE, NOTE_EXIT, 0, NULL);
  kevent(kqueue_fd, &kev, 1, NULL, 0, NULL);

  struct pollfd kqpoll;
  kqpoll.fd = kqueue_fd;
  kqpoll.events = POLLIN;

  // Start a run loop
  while(processEvents())
  {
    if(kill(parent_pid, 0) == -1)
      if(errno == ESRCH)
        break;

    if(poll(&kqpoll, 1, 0) == 1)
      if(kevent(kqueue_fd, NULL, 0, &recv_kev, 1, NULL))
        break;

    parent_pid = getppid();
    if(parent_pid == 1)
      break;

    sleep(a_short_time);

    // (simple code here causes subprocess to sleep longer if it hasn't
    // received any events recently)
  }
}

Answer: Answering my own question here:
The reason for this problem was not down to detecting whether the parent process had died. In processEvents() I was polling the pipe from the parent process to see if there was any communication. When the parent died, poll() returned a value of 1 and the read loop thought there was infinite data waiting to be read.
The solution was to detect whether the pipe had been disconnected or not.


Proprieties of the heat kernel on a bounded domain of $\mathbb{R}^{d}$

Question: I'm interesting to PDE, and I'm asking if the heat kernel with Dirichlet boundary conditions $p_{D}(t,x,y)$ on $[0,1]^{d}$, where $d\geq 1$ satifies
i) $\int_{D}p_{D}(t,x,y)dy =1$    or    $c_{0} > 0$   ?
ii) The chapmann Kolmogorov equation $p_{D}(t+s,x,y) = \int_{D}p_{D}(t,x,z)p_{D}(s,y,z)dz$ ?
On $\mathbb{R}^{d}$ this is true, but in a bounded domain $D$ I don't know. Help me please.
Comment: For $D = [0,1]$, I think you can calculate $p_D$ explicitly using Fourier series. So then you can just check the answers for i) and ii) directly.
Answer: For the purpose of deciding whether to believe such properties, it helps to think of $p_D(t,x,y)$ in probabilistic terms: as a function of $y$, this is the distribution at time $t$ of Brownian motion that starts at $x$ and gets killed when reaching the boundary (the latter is the Dirichet boundary condition). Then  $\int_D p_D(t,x,y)\,dy$ is easy to understand: this is the probability that the Brownian particle is still in $D$ at time $t$. Due to our boundary conditions, this probability  is less than $1$ for all $t>0$, and tends to $0$ as $t\to\infty$.
The second property is true. It expresses the lack of memory of Brownian motion: its distribution at time $t+s$ is what we get by starting with distribution at time $t$ and following it for time period $s$. This property is not affected by boundary conditions. To prove it, you can appeal to the corresponding property of the heat equation: $U(\cdot,t+s)$ is $V(\cdot ,s)$ where $V(\cdot,0)=U(\cdot,t)$.
Comment: Thank you very much, in fact I hope estimate the integrale $\int_{0}^{t}\int_{D}p_{D}(s,x,y)dsdy$ and I hope obtain a lower bound of the form $c t^{\rho}$ where $c$ is a positive constant and $\rho \geq 0 $. I wish that you help me, I thank you very much.
Comment: @user110160 This is a new question, and should be asked as such.


Voltar para inicio da condição quando for solicitado

Question: Não posso usar função, queria saber como voltar para uma determinada linha do código quando o número 0 for pressionado, exemplo:
system(color 7);
printf("Teste");
printf("Teste01");
printf("Pressione 0 para reiniciar");
scanf("%d", &jog);

Agora como faço para se ele digitar 0, a execução voltar para a linha do system()? Com função seria fácil, mas não posso usar então como vou fazer?
Answer: Apesar de não ser a melhor opção, uma opção é o goto.
voltaAqui:
... código
goto voltaAqui;

Comment: @Marciano.Andrade Eu acredito que criar funções é melhor :)
Comment: Por que não seria a melhor opção? `goto` é controle de fluxo :P
Comment: Também acho que criar função deixa o código mais limpo etc.. Mas é isso aí que eu queria, obrigado
Answer: Pode colocar o código dentro de um loop e verificar se o valor da variável jog é diferente de 0. Se for, você interrompe o loop:
int jog;

while(1){

  // código...

  printf("Pressione 0 para reiniciar");
  scanf("%d", &jog);

  if(jog) break;
}

Comment: Geralmente eu uso esse, sem o break. Mas ia deixar o código maior, o goto veio bem a mim
Answer: for (;;) {
    /* codigo */
}

ou
while (1) {
    /* codigo */
}

ou
do {
    /* codigo */
} while (1):


Fourier transform of $t H(t)$

Question: I want to calculate the Fourier transform of $f(t):=t\cdot H(t)$ ($H$ denotes the Heaviside function). For the integral I got
$$\hat{f}(y)=\left[\left(\frac{1}{y^2}+\frac{ix}{y}\right)e^{-i\omega x}\right]_{x=0}^{\infty}$$
Now I'm having trouble getting handling the boundaries, since $|e^{-i\omega x}|=1$.
Could I maybe compute $\hat{g}$ for $g(x):=xe^{-\varepsilon x}H(x)$ for $\varepsilon>0$ and then send $\varepsilon \rightarrow 0$ to get the transform I want?
Comment: Since $xe^{-\varepsilon x} H(x) \to xH(x)$ for $\varepsilon \downarrow 0$ in the sense of tempered distributions: yes, you can.
Comment: @danielfischer A naive application of that limit neglects the contribution of the Dirac Doublet (i.e., $\delta'(\omega)$).
Comment: @MarkViola Yes, but hopefully the knowledge that one is working with tempered distributions reduces one's naïveté.
Comment: This is not correct, because it does not take into account the discontinuity at $t=0$.
Answer: If we proceed using the limiting procedure discussed at the end of the question, we find that for $\omega\ne0$
$$\begin{align}
\lim_{\epsilon\to0^+}\int_{-\infty}^\infty xH(x)e^{-\epsilon x}e^{-i\omega x}\,dx&=\lim_{\epsilon\to0^+}\int_{0}^\infty xe^{-(\epsilon+i\omega) x}\,dx \\\\
&=\lim_{\epsilon\to 0^+}\frac1{(\epsilon+i\omega)^2}\\\\
&=-\frac1{\omega^2}
\end{align}$$
But this is not the Fourier Transform of $tH(t)$.
We now proceed to evaluate the distributional limit $\displaystyle \lim_{\epsilon\to 0^+}\frac1{(\epsilon+i\omega)^2}$ by applying it to a suitable test function.

Let $f$ be a smooth function of compact support.  We can write for any $\delta>0$
$$\begin{align}
\lim_{\epsilon\to 0^+}\int_{-\infty}^\infty \frac{f(\omega)}{(\epsilon+i\omega)^2}\,d\omega&=\lim_{\epsilon\to 0^+}\int_{|\omega|\ge \delta}\frac{f(\omega)}{(\epsilon+i\omega)^2}\,d\omega+\lim_{\epsilon\to 0^+}\int_{|\omega|\le \delta}\frac{f(\omega)}{(\epsilon+i\omega)^2}\,d\omega\\\\
&=-\int_{|\omega|\ge \delta}\frac{f(\omega)}{\omega^2}\,d\omega-\lim_{\epsilon\to 0^+}\int_{|\omega|\le \delta}\frac{f(\omega)}{(\omega -i\epsilon)^2}\,d\omega\\\\
&=-\int_{|\omega|\ge \delta}\frac{f(\omega)}{\omega^2}\,d\omega-\lim_{\epsilon\to 0^+}\int_{|\omega|\le \delta}\frac{f(0)+f'(0)\omega}{(\omega -i\epsilon)^2}\,d\omega+O(\delta)\\\\
&=-\int_{|\omega|\ge \delta}\frac{f(\omega)}{\omega^2}\,d\omega+2\frac{f(0)}{\delta}-i\pi f'(0)+O(\delta)\\\\
&=-\int_{|\omega|\ge \delta}\frac{f(\omega)-f(0)}{\omega^2}\,d\omega-i\pi f'(0)+O(\delta)\tag1
\end{align}$$
Letting $\delta\to0$ in $(1)$ reveals
$$\begin{align}\lim_{\epsilon\to 0^+}\int_{-\infty}^\infty \frac{f(\omega)}{(\epsilon+i\omega)^2}\,d\omega&=-\text{PV}\int_{-\infty}^\infty\frac{f(\omega)-f(0)}{\omega^2}\,d\omega-i\pi f'(0)\\\\
&=\text{PV}\int_{-\infty}^\infty\left(- \frac{1}{\omega^2}\right)\left( f(\omega) - f(0) \right)\,d\omega+i\pi\int_{-\infty}^\infty \delta'(\omega)f(\omega)\,d\omega\tag2
\end{align}$$
We deduce from $(2)$ that in distribution
$$\lim_{\epsilon\to 0^+}\frac1{(\epsilon+i\omega)^2}=\left(-\frac1{\omega^2}\right)+i\pi \delta'(\omega)$$
where the distribution $\displaystyle \left(-\frac1{\omega^2}\right)$ is interpreted in the sense of $(2)$.
Comment: There's a typo in $1\,1/\omega^2$. $PV(1/\omega^2)$ hasn't been defined, you do not say how it acts on an arbitrary test function. Suppose you have a functional $g$ that gives zero for every test function $f$ s.t. $f(0)=0$ (I assume that's what you mean by $f(\omega)=0$). That information is not sufficient, the $\delta$ term in $g$ is arbitrary. Incidentally, $PV$ is a rather misleading notation for a regularization of $1/\omega^2$. Also, unless you define that regularization in a non-standard way to include a $\delta'(\omega)$ term, the sign at $\delta'(\omega)$ in the answer is wrong.
Comment: I don't see any edits though. If you know only how the functional acts on test functions that are vanishing at zero, how can you say that you've fully defined the functional? Do you agree with what I said about the $\delta$ component being arbitrary? In the example from my first comment, can you say that $g$ is identically zero? The sign is wrong because of the error in the evaluation of the integral of $\omega/(\omega-i\epsilon)^2$.
Comment: Then it's simply not a well-defined distribution at all, if it doesn't map every test function to $\mathbb C$. You lose all the nice properties of distributions, e.g., you cannot compute the convolution of this object with a distribution, because the convolution requires the action on $f(x+y)$, and now you cannot restrict $f$ in a suitable way. Look at it this way: you can add $\delta(\omega)$ to your answer and say it is also an answer; there's nothing in your definition that rules out a $\delta$ term. You keep ignoring this point.
Comment: There's a typo in the second line of (1) now, the minus sign before $1/\omega^2$ is missing. A quick way to see that the sign of $\delta'$ was wrong is to consider the transform of $H(x)$.
Comment: For the record, I believe the corrected answer still is effectively indeterminate. Let me present one more argument. The object that you denote by $PV(1/\omega^2)$ is not the distributional derivative of $-PV(1/\omega)$, because the distributional derivative is a well-defined functional and therefore doesn't return any signed infinities, which you call complex numbers for some reason. Therefore all Fourier transform identities involving derivatives break down.
Comment: $t H(t)$ certainly has a Fourier transform, see my answer. I'm saying that what you denote by $PV(1/\omega^2)$ either isn't a distribution (if you choose to introduce the infinities) or, at best, is a distribution that has an indeterminate $C \delta(\omega)$ term (see my comment above that mentions that you can add $\delta(\omega)$ to your answer), that's why it's not correct.
Comment: Remember that we're dealing with singular functionals, whose action isn't given by $\int g f$. $w^{-2}$ is fully defined by saying that it's the distributional derivative of $-w^{-1}$:
$$(w^{-2}, f) = ((-w^{-1})', f) = (w^{-1}, f') = \\
\operatorname{v.\!p.} \int_{-\infty}^\infty \frac {f'(w)} w dw =
\int_0^\infty \frac {f(w) + f(-w) - 2f(0)} {w^2} dw.$$
This is well-defined for any test function $f$. This is why $FP(1/w^2)$ ($FP$ standing for finite part) is preferable to $PV$ when just $w^{-2}$ can be ambiguous $-$ generally speaking, it's not the p.v. integral of $f(w)/w^2$.
Comment: @Maxim I removed the unnecessary and inappropriate constraint that $f(0)=0$.  Now, there is an extra term $2f(0)/\delta=\int_{|\omega|\ge\delta}\frac{f(0)}{\omega^2}\,d\omega$ that combines nicely with the integral $\int_{|\omega|\ge\delta}\frac{f(\omega)}{\omega^2}\,d\omega$.  All is right with the world now.  Thank you for your patience and your helping with getting it correct.  I've deleted all of my prior comments to reduce the clutter and noise.
Answer: In addition to @MarkViola's good answer, and his and @DanielFischer's good comments, one might also think in terms of degrees of homogeneity of distributions, plus "sign". That is, $t\cdot H(t)$ is a linear combination of $|x|$ and of $\hbox{sgn}(x)\cdot |x|$, which are (positive-) homogeneous of degree $1$ in both cases, one odd and one even.
It is an exercise to show that homogeneity (and parity) behave intelligibly under Fourier transform. The exact formulation depends on conventions about notation of "homogeneity"... This is in principle very well known, indeed, but beginners seem to chronically overlook it in favor of direct computation...
So, for example, one finds that up to constants the Fourier transform of $\hbox{sgn}(x)$ is (principal value integral attached to) $1/x$. And similarly in the cases at hand.
Answer: The transform of $e^{−\epsilon x} H(x)$ is $1/(\epsilon + i w)$, which has a well-known distributional limit. We obtain
$$\mathcal F[H] =
\lim_{\epsilon \downarrow 0} \mathcal F[e^{-\epsilon x} H(x)] =
-\lim_{\epsilon \downarrow 0} \frac i {w- i \epsilon} =
-i w^{-1} + \pi \delta(w), \\
\mathcal F[x H(x)] = i \frac d {dw} \mathcal F[H] =
-w^{-2} + i \pi \delta'(w),$$
where $w^{-1}$ is the p.v. functional and $-w^{-2}$ is its distributional derivative.
Comment: (+1) for the clear and concise post.
Comment: It might be useful and instructive to define how $-\omega^{-2}$ operates on a test function.  That is, it would benefit future readers to discuss the "finite part" integral by folding the principal value of $\frac{f(\omega)-f(0)}{\omega^2}$.

Fourier transform of $t H(t)$


merge custom 2 array

Question: halo guys. nice to meet you. i am still new in program. especially in php code. now im learning about array code. can i merge 2 array become 1.
ex :
i vardump some parameter and the result like this
<code>'list_data' =>
array (size=2)
  0 =>
    array (size=1)
      'branch_id' => string '3' (length=1)
  1 =>
    array (size=1)
      'branch_id' => string '4' (length=1)
</code>
can i merge that array become like this :
<code>'list_data' =>
array (size=2)
  0 => string  '3'
  1 => string  '4'
</code>
please help me. im so curious about this.
Comment: Possible duplicate of [Merge PHP arrays](https://stackoverflow.com/questions/8236259/merge-php-arrays)
Comment: Couldn't you just use the `array_merge()` function?
Comment: i already used that function. but the result still same with the first one
Answer: This is a case for array_map:
<code>$array = [
    'list_data' => [
        [ 'branch_id' => 3],
        [ 'branch_id' => 4],
    ]
];

$array['list_data'] = array_map(function($item) {
    return $item['branch_id'];
},$array['list_data']);
var_dump($array);
</code>
Or array_column
<code>$array['list_data'] = array_column($array['list_data'], 'branch_id');
var_dump($array);
</code>
Comment: Thank you very much!. really appreciate.. God Bless You

merge custom 2 array


How to interpret a two-dimensional contingency table?

Question: I am trying to understand how to interpret log-linear models for contingency tables, fitted by way of Poisson GLMs.
Consider this example from CAR (Fox and Weisberg, 2011, p. 252).
require(car)
data(AMSsurvey)
(tab.sex.citizen <- xtabs(count ~ sex + citizen, data=AMSsurvey))

Yielding:
        citizen
sex      Non-US  US
  Female    260 202
  Male      501 467

Then we fit the model of (mutual) independence:
AMS2 <- as.data.frame(tab.sex.citizen)
(phd.mod.indep <- glm(Freq ~ sex + citizen, family=poisson, data=AMS2))
pchisq(2.57, df=1, lower.tail=FALSE)

Outputting:
> (phd.mod.indep <- glm(Freq ~ sex + citizen, family=poisson, data=AMS2))

Call:  glm(formula = Freq ~ sex + citizen, family = poisson, data = AMS2)

Coefficients:
(Intercept)      sexMale    citizenUS
     5.5048       0.7397      -0.1288

Degrees of Freedom: 3 Total (i.e. Null);  1 Residual
Null Deviance:      191.5
Residual Deviance: 2.572    AIC: 39.16
> pchisq(2.57, df=1, lower.tail=FALSE)
[1] 0.1089077

The p value is close to 0.1 indicating weak evidence to reject independence. However, let us assume that we have sufficient evidence to reject the NULL (i.e. for our purposes, the 0.10 p value is indicative of an association between the two variables).
Question: How, then, do we interpret this loglinear model?
(Do we fit the saturated model (i.e. update(phd.mod.indep, . ~ . + sex:citizen))? Do we interpret the estimated regression coefficients? In CAR they stop at this point, because of weak evidence for rejecting the NULL, but I'm interested in understanding the mechanics of the interpretation of this simple log-linear model as if the "interaction" were significant...)
Answer: In general, there isn't much to a 2-way contingency table, but you are trying to unpack this at such a level of detail that some confusions are arising.  Typically, with a simple contingency table like this, people just want to know if the variables (sex and citizen) are independent.  To assess that, you can run a chi-squared test:
chisq.test(tab.sex.citizen)
#  Pearson's Chi-squared test with Yates' continuity correction
#
# data:  tab.sex.citizen
# X-squared = 2.389, df = 1, p-value = 0.1222

You can perform a likelihood ratio version of this test (the chi-squared test above is a score test), by performing a nested model test of the Poisson GLM you ran against the full (saturated) model:
phd.mod.indep <- glm(Freq ~ sex + citizen, family=poisson, data=AMS2)
phd.mod.sat   <- glm(Freq ~ sex * citizen, family=poisson, data=AMS2)
anova(phd.mod.indep, phd.mod.sat, test="LRT")
# Analysis of Deviance Table
#
# Model 1: Freq ~ sex + citizen
# Model 2: Freq ~ sex * citizen
#   Resid. Df Resid. Dev Df Deviance Pr(>Chi)
# 1         1     2.5721
# 2         0     0.0000  1   2.5721   0.1088
deviance(phd.mod.indep)                                        # [1] 2.572123
deviance(phd.mod.sat)                                          # [1] 3.308465e-14
1-pchisq(deviance(phd.mod.indep)-deviance(phd.mod.sat), df=1)  # [1] 0.1087617

You can also get the Wald test of the interaction term (which is the test of independence):
summary(phd.mod.sat)
# ...
# Coefficients:
#                   Estimate Std. Error z value Pr(>|z|)
# (Intercept)        5.56068    0.06202  89.663  < 2e-16 ***
# sexMale            0.65592    0.07643   8.582  < 2e-16 ***
# citizenUS         -0.25241    0.09379  -2.691  0.00712 **
# sexMale:citizenUS  0.18214    0.11373   1.602  0.10926
# ...
#     Null deviance: 1.9148e+02  on 3  degrees of freedom
# Residual deviance: 3.3085e-14  on 0  degrees of freedom
# AIC: 38.586
# ...

(To read about score vs Wald vs likelihood ratio tests, see my answer here: Why do my p-values differ between logistic regression output, chi-squared test, and the confidence interval for the OR?)

Note however, that the way you conducted your test of phd.mod.indep is incorrect (see here: Test GLM model using null and model deviances).  The test of that model against the null model is the test of whether all cells have the same probability in the population.  It would be implemented as follows:
1-pchisq(191.5-2.57, df=3-1)  # [1] 0

Setting aside the test of whether all cell probabilities are equal (which I doubt is of much interest to you), if you believed that there was an association between sex and citizen, you would not interpret the model phd.mod.indep.  That would be a misspecified model.
Comment: *"Note however, that the way you conducted your test of `phd.mod.indep` is incorrect"* I suspect that the difference comes from testing different hypotheses. The `1 - pchisq(191.5-2.57, df=3-1)` test will look at whether "the [fitted] model as a whole is better than the null model". The `1 - pchisq(2.57, df=1)` test is intended as a *lack-of-fit* test (see CAR p. 252); in my understanding, it compares the fitted model to the saturated model (i.e. `update(phd.mod.indep, . ~ . + sex:citizen)`, which has 0 residual deviance and 0 df).
Comment: So I'm looking too much into it, and it's mostly about detecting association... Thank you for the thorough answer. I'll do some reading and some checks, and later get back on the subject of the incorrect test...
Comment: @landroni, fair enough. I suppose you can do it that way.
Comment: I added an answer covering the use of mosaic plots to aid interpretation of contingency tables.
Answer: In addition to @gung's answer, I discovered that mosaic plots are very useful in assessing the relative relationships with categorical data. Once we establish (actually, we assume here) departure from independence, one can use package vcd to graphically display such contingency tables.
A mosaic plot:
mosaic(tab.sex.citizen, shade=TRUE, legend=TRUE)

An association plot:
assoc(tab.sex.citizen, shade=TRUE, legend=TRUE)

From the second plot, it's clear that the proportion of women is bigger for non-citizens than for US citizens. Equivalently, the proportion of non-citizens is bigger for females than for males.

The graphs are clearer when the departure from independence is clear-cut, so here's an example on the Titanic data (see this tutorial).
data(Titanic)
sex.survived <- margin.table(Titanic, c(2,4))
ftable(sex.survived)

Yielding:
> ftable(sex.survived)
       Survived   No  Yes
Sex
Male            1364  367
Female           126  344

Then the plots:
mosaic(sex.survived, shade=TRUE, legend=TRUE)
assoc(sex.survived, shade=TRUE, legend=TRUE)

From the Pearson residuals (a measure of the departure of the Observed Frequencies from the Expected Frequencies, or the bits in the data not explained by the loglinear model), it's clear that for males there is a disproportionately high number that haven't survived and a disproportionately low number that have survived. Equivalently, out of those that survived the number of females is unexpectedly high.
Comment: +1, looking at your data is always important. Mosaic plots & association plots are a nice basic option; there are others as well, see [here](http://stats.stackexchange.com/q/38350/7290). Friendly's *Visualizing Categorical Data* (the book) has lots of nice ideas, [this pdf](http://www.datavis.ca/books/vcd/vcdstory.pdf) is a nice short introduction. If your contingency tables are larger than 2x2, correspondence analysis can be helpful (see [here](http://stats.stackexchange.com/a/147868/7290)).


Computing Posterior Probability of a Model being the correct one

Question: Let $x\sim N(\mu,\sigma^2)$ and $\mu\sim N(\xi, \tau^2)$.
To test whether $\mu<0$ or $\mu>0$, in Bayesian inference it's usual to take the perspective of hypothesis testing as model selection. In that perspective,
$M_1:\mu<0$ and $M_2:\mu>0$ .
There are at least two ways to compute $P(M_{True}=M_1|x)$. The easy one seems to use the fact that $P(M_{True}=M_1|x)=P(\mu<0|x)=\Phi(-\xi(x)/w)$, since it's known that $\mu|x\sim N(\xi(x),w^2)$ .
(to save space-time I won't write $\xi(x)$ or $w$ formula)
The second way to calculate the $P(M_{True}=M_1|x)=\frac{\int l_k(\theta)\pi_k(\theta) d\theta \ \ P(M=k)}{\sum_j\int l_j(\theta)\pi_j(\theta) d\theta \ P(M=j)}$.
I'm trying to do by the second way. However, I get $P(M_{True}=M_1|x)=1-\Phi(-\xi(x)/w)=\Phi(\xi(x)/w)$
This is based on the book Bayesian Essentials, page 40.
Any help would be appreciated.
Edit: for the second way, we define $$\pi_1(\mu)=\frac{\exp\{-(\mu-\xi)^2/(2\tau^2\}}{(2\pi \tau^2)^{1/2}\Phi(-\xi/\tau)}\mathbb{I}_{\mu<0}$$
$$\pi_2(\mu)=\frac{\exp\{-(\mu-\xi)^2/(2\tau^2\}}{(2\pi \tau^2)^{1/2}\Phi(\xi/\tau)}\mathbb{I}_{\mu>0}$$
Comment: For what its worth, I teach students to do the "easy one" as it seems very arbitrary to me to turn the question into a hypothesis testing question.
Comment: For the second approach, I don't think you have defined enough. I'm assuming your priors for $\mu$ under the two models are the truncated versions of the prior for $\mu$ that you defined. I'm also assuming that the prior model probability is the integral of the defined prior with respect to that model.
Comment: Uh? The equation (2.7) on [page 40](http://www.amazon.com/gp/product/1461486866/ref=as_li_tl?ie=UTF8&camp=1789&creative=390957&creativeASIN=1461486866&linkCode=as2&tag=chrprobboo-20&linkId=ZLMLRYVIU22HLCDW) does give $\Phi(-\xi(x)/w)$ as the answer.
Comment: @jaradniemi I've added a few details. May you help me? Thanks
Comment: @Xi'an I'm not sure I understand you. I don't manage to get the solution of the text by 2nd way...
Answer: You are correct in setting the restricted priors
\begin{align*}
\pi_1(\mu) &= \frac{\exp\{-(\mu-\xi)^2/(2\tau^2\}}{(2\pi \tau^2)^{1/2}\Phi(-\xi/\tau)}\mathbb{I}_{\mu<0}\\
\pi_2(\mu) &= \frac{\exp\{-(\mu-\xi)^2/(2\tau^2\}}{(2\pi \tau^2)^{1/2}\Phi(\xi/\tau)}\mathbb{I}_{\mu>0}
\end{align*}
Next step is identifying the prior weights
\begin{align*}
\mathbb{P}(\mathfrak{M}=M_1)&=\mathbb{P}(\mu<0)=\Phi(-\xi/\tau)\\
\mathbb{P}(\mathfrak{M}=M_2)&=\mathbb{P}(\mu>0)=\Phi(\xi/\tau)
\end{align*}
which leads to the posterior probability
\begin{align*}
\mathbb{P}(\mathfrak{M}=M_1|x)&\propto \int_{-\infty}^0 \varphi(\{x-\mu\}/\sigma) \pi_1(\mu)\,\text{d}\mu\times\mathbb{P}(\mathfrak{M}=M_1)=\int_{-\infty}^0 \varphi(\{x-\mu\}/\sigma) \pi(\mu)\,\text{d}\mu\\
\mathbb{P}(\mathfrak{M}=M_2|x)&\propto \int_0^\infty \varphi(\{x-\mu\}/\sigma) \pi_2(\mu)\,\text{d}\mu\times\mathbb{P}(\mathfrak{M}=M_2)=\int_0^\infty \varphi(\{x-\mu\}/\sigma) \pi(\mu)\,\text{d}\mu
\end{align*}
or [denoting $\mathfrak{m}(\cdot)$ for the marginal density of $X$]
\begin{align*}
\mathbb{P}(\mathfrak{M}=M_1|x)&\propto \mathfrak{m}(x) \int_{-\infty}^0 \pi(\mu|x)\,\text{d}\mu=\mathfrak{m}(x) \Phi(-\xi(x)/w)\\
\mathbb{P}(\mathfrak{M}=M_2|x)&\propto \mathfrak{m}(x)\int_0^\infty \pi(\mu|x)\,\text{d}\mu=\mathfrak{m}(x) \Phi(\xi(x)/w)
\end{align*}
which leads again to
$$\mathbb{P}(\mathfrak{M}=M_1|x)=\Phi(-\xi(x)/w)$$
Comment: Many thanks. I thought the prior weights could be  anything as long as $P(M=M_1)=1-P(M=M_2)$... That's one of the reasons why I didn't get exactly the same.  The other being a typo in my calculations. Now I get it. Thanks ;)
Comment: @Anoldmaninthesea. Well, in a sense, you are free to model those weights as you wish when you run hypothesis testing and model comparison. However, if you start from a prior over the whole space as stated in the question, this prior induces the said weights.


Prove $X_i$ in Span of $ X_k, k \neq i$

Question: Let $(\Omega,\mathcal F, P)$ be a probability space and let $L_1$ be the collection of all integrable (finite expectation) real-valued random variables defined on this space. Assume that for $X_k\in L_1,k=1,2,\dots n$ it holds that $\mathbb E \lvert \sum_k a_k^m X_k \rvert \leq 1,\forall m$, where $(a_1^m,a_2^m,\dots,a_n^m)=:a_m$ is a sequence in $\mathbb R^n$ such that $\max_k \lvert a_k^m \rvert\to \infty, m \to \infty.$ Prove that $\exists i$ and real numbers $b_k$ such that $\mathbb E \lvert X_i - \sum_{k\neq i} b_k X_k \rvert=0$.
Note that this is related to homework.
I tried a number of things but can't pin down where I fail. I tried using contradiction and Fatou to show that there is a set of non zero measure where the $\lim \inf$ is infinite but did not manage to convince myself. I also tried arguing by standardizing all coefficients by the $\max$, leading to $\mathbb E \lvert \sum_k \alpha_k^m X_k \rvert\to0$ where at least one $\alpha_k^m \in \{ -1,1\},\forall m$ but could not convince myself that this is helpful. From here I also tried using the fact that there is a subsequence converging almost surely to zero.
In short, I am at a loss where to even start. I feel like I've tried all the standard tools from a graduate level probability course but am not making progress. I am looking for a pointer in the right direction. The overall goal is to show that the span of finite number of integrable r.v.s is a closed set, but this is a step on the way.
Comment: Thank you for expanding the question! I suspect you might be able to offer a constructive demonstration by considering the sequence $\mathrm{a}/||\mathrm{a}||$ of normalized vectors: show that it must have an accumulation point on the sphere $S^{n-1}\subset \mathbb{R}^n$ and calculate the $b_k$ from the coefficients of such an accumulation point.
Comment: @whuber thanks for the suggestion! I'll go and work on that and see where it gets me.
Answer: Based on @whuber's hint, I came up with the following. Please do let me know if I made a mistake somewhere.
Let $\alpha^{m}:=\left(a_{1}^{m},\dots, a_{n}^{m}\right)/\left\Vert \left(a_{1}^{m},\dots\,a_{n}^{m}\right)\right\Vert$. Since every bounded sequence in $\mathbb{R}^{n}$ has a convergent sub-sequence (Bolzano-Weierstrass), we may pick $m_{l}:\alpha^{m_{l}}\to b$  for some  $b\in\mathbb{R}^{n}$. Then $\sum_{k}\alpha_{k}^{m_{l}}X_{k}\to\sum_{k}b_{k}X_{k}$ pointwise. By assumption we also have $$
\mathbb{E}\left|\sum_{k}\alpha_{k}^{m_{l}}X_{k}\right|\leq1/\left\Vert a^{m_{l}}\right\Vert \to0
$$
Since $\sum_{k}\mathbb{E}\left|X_{k}\right|<\infty$ and $\left|\sum_{k} \alpha_{k}^{m_{l}}X_{k}\right|\leq\sum_{k}\left| \alpha_{k}^{m_{l}}X_{k}\right|\leq\sum_{k}\left|X_{k}\right|$ dominated convergence gives: $$0=\lim_{l\to\infty}\mathbb{E}\left|\sum_{k} \alpha_{k}^{m_{l}}X_{k}\right|=\mathbb{E}\left|\sum_{k}b_{k}X_{k}\right|,$$
which is what we wanted to prove (upon standardizing $b$ so that $b_k=1$ for at least one $k$).

Prove $X_i$ in Span of $ X_k, k \neq i$


Probability - Poisson Arrival Process

Question: Car arrive at a toll booth according to the Poisson process at a rate of 3 arrivals per minute.
a) What is the probability that the third car arrives within 3 minutes of the first car?
b) Of the cars arriving at the booth, it is known that over the long run 60% are Japanese imports. What is the probability that in a given 10 minute interval, 15 cars arrive at the booth and 10 of these are Japanese imports?
For a) I'm thinking that we need to find the P(Time two more cars arrive after first car < 3), but I'm not sure how to set the any formulas up.
For b) We assume independence so we can use the multiplication rule for P(10 cars out of 15 are Japanese) and P(15 cars arrive in 10 minutes). Again, not sure how to use the Poisson process to set up the second probability.
Comment: The probability of $1$ or fewer car arrivals in the $3$ minutes after the first is $e^{-9}+e^{-9}\frac{9^1}{1!}$. So our required probability is $1-\left(e^{-9}+e^{-9}\frac{9^1}{1!}\right)$.
Answer: For $\lambda=3$/minute, the   $\mathsf P(N=k\mid T=t) = \dfrac{(3t)^k\mathsf e^{-3t}}{k!}$

a) What is the probability that the third car arrives within 3 minutes of the first car?

Hint: You don't care what time the first car arrives.  You want the probability that in the following three minutes at least two more cars arrive.
$$\mathsf P(N \geq 2\mid T=3) = 1- \sum_{k=0}^1 \mathsf P(N=k\mid T=3)$$

b) Of the cars arriving at the booth, it is known that over the long run 60% are Japanese imports. What is the probability that in a given 10 minute interval, 15 cars arrive at the booth and 10 of these are Japanese imports?

For a given number of cars that arrive, $N$, then the count of imports is the count of successes in $N$ Bernoulli trials with success rate $0.60$.   Under this condition, what kind of distribution is this?
$$\mathsf P(N=15, N_\text{import}=10 \mid T=10) ~=~ \mathsf P(N=15\mid T=10)\cdot\mathsf P(N_\text{import}=10 \mid N=15)$$
Answer: Hint...for the first part you need the probability that at least three cars arrive in a three minute period. Therefore use $\lambda=9$.
For the second part you need to multiply the Binomial probability of $10$ out of $15$ cars being Japanese with the Poisson probability of $15$ cars arriving in a $10$ minute period, so use $\lambda=30$.

Probability - Poisson Arrival Process


Understanding of bivariate Gaussian distributions in connection with complex random variable

Question: Say that we want to model a complex-valued signal using the RV $S$, where $S$ can be expressed by it's real and imaginary part, i.e. $S = X + iY$, where $X$ and $Y$ are real-valued random variables.
Given that $X$ and $Y$ are both Gaussian, have zero mean, are independent and have the same variance. Is the joint PDF $f_{X,Y}(x,y)$ complex-valued?
My intuition says that the joint PDF is real-valued, since the joint distribution can be viewed as a joint PDF of two orthogonal Gaussian RVs (Re{S} = X, Im{S} = Y), and thus, we can view $f_{X,Y}(x,y)$ as a real-valued bivariate Gaussian distribution, where $f_{X,Y}(x,y)=f_X(x)f_Y(y)$.
Is this line of thinking correct or is my intuition about the problem completely wrong?
Answer: There is nothing complex about the pair $(X,Y)$, so yes, the density is real-valued. As the density of a complex-valued $S$ is defined as the density of $(X,Y)$, this is real-valued, too.
The subtlety here is that according to the standard definition obviously a density of a 2-d real-valued random variable is real valued. The standard definition does not cover complex-valued RVs $S$, so it has to be explicitly defined that $f_S=f_{(X,Y)}$, but this is what is done. (Wikipedia - complex random variable)


In the MLB, is someone known as being the ultimate journeyman?

Question: I'm thinking there must be a player whose career consisted of a collection of single seasons, each with a different team.
I know there are relief pitchers like this.  I'd be more interested in learning about a position player.
I tried to search for players who fit this mold on Baseball Reference.  One that came to mind was Arthur Rhodes.  His career was front loaded with a long stint at Seattle, and the second half saw him hop around.
I'm sure there's got to be someone who is known as being the ultimate journeyman.
Comment: Ricky Henderson is an interesting case: despite being a Hall-of-Famer, he played for 9 different teams. He was with five of them for one season or less, and though he played for Oakland for 14 years, that was split into *four* separate stints. From the age of 34 to 44, he never spent more than one-and-a-half seasons with a team at one time. (And this is only considering his MLB career, which was followed by two seasons in the Atlantic League and one in the Golden Baseball League.)
Comment: I don't think this is a good question for this format, at least in the way it seems to be most likely to be interpreted.  If the question were, "What player is known as The Big Hurt", it would be fine - that's a question with a specific answer, because The Big Hurt is the specific nickname for Frank Thomas.  But it sounds like you're asking a question that really depends on opinion, because there isn't a player whose nickname is "The Ultimate Journeyman" - instead it's more of a "list some players who played for a lot of teams", which isn't really on topic here.
Answer: I've never heard that term applied to a single player.  That's unlikely to be a fan-favorite, because you're looking for someone that was never with any team very long and wasn't good enough to be kept around.
My vote would be for Matt Stairs.  Although he did play for Oakland for 5 consecutive years, all the other teams were max 2 years.  19 seasons in the majors, 12 different teams.
Matt also holds the MLB record for pinch hit homers with 23.
Kenny Lofton played for 11 different teams, but was such a force for Cleveland during his prime that I don't think he fits your request.  There's probably several players with only one year with each team (or less), but that didn't hold up for long and are quite forgettable.
I remember Paul Bako during his stint with the Astros.  He played for 11 teams, no more than 2 consecutive years with any, but I think backup catcher may be similar in feel to relief pitcher.
Comment: Nice answer.  Didn't realize that about Stairs or Lofton.


How to programmatically delete a display from a view

Question: Is it possible to programmatically delete a display from a view?
The view object has numerous member functions related to displays (add_display, attach_displays, choose_display, set_display, new_display, etc.) and I can also disable a display like this:
<?php
  $view_name = "faq";
  $display_name = "page_1";
  $view = views_get_view($view_name);
  $view->display[$display_name]->display_options['enabled'] = FALSE;
  views_save_view($view);
?>

But I can't see how I can remove the display completely. Can anyone advise? Thanks!
Answer: This is how you do it. It is how it is done in views_ui_edit_view_form_submit() when you delete a display via the admin UI:
unset($view->display[$display_name]);

Comment: I should have thought to look there. Thanks - that worked.


Como escrever Query utilizando Laravel

Question: Como escrever essa Query no Laravel?
SELECT
        a.id, a.name, a.email, a.role, a.percentage, a.remaining_tax, a.min_peoples_per_table ,a.regions,
        GROUP_CONCAT( r.name SEPARATOR ", ") as regions_name
    FROM administrator as a
    INNER JOIN regions as r
        ON a.regions REGEXP CONCAT("[[:<:]]", r.id, "[[:>:]]")
    GROUP BY a.id
    ORDER BY a.id desc;

Código em construção:
$list = DB::table('administrator as a')
        ->select("a.id" , "a.name", "a.email", "a.role", "a.percentage", "a.remaining_tax", "a.min_peoples_per_table" ,"a.regions")
        ->groupBy("a.id")
        ->orderBy("a.id", "desc")
        ->get();
 return $list;

Na parte do GROUP_CONCAT e JOIN que estou meio perdido.
Comment: Editei minha pergunta.
Answer: O método join() aceita 4 argumentos:

A tabela que vai ser feito o join. Neste caso: regions as r.
O campo da cláusula ON. Neste caso: a.regions
O operador da cláusula ON. Neste caso: REGEXP
O segundo campo da cláusula ON. Neste caso nós podemos usar DB::raw() para adicionar o código. Ex.: DB::raw('CONCAT("[[:<:]]", r.id, "[[:>:]]")')

Então ficaria assim:
<?php

$list = DB::table('administrator as a')
            ->select("*")
            ->join(
                'regions as r',
                'a.regions',
                'REGEXP',
                DB::raw('CONCAT("[[:<:]]", r.id, "[[:>:]]")')
            )
            ->groupBy("a.id")
            ->orderBy("a.id", "desc")

Comment: Call to undefined method Illuminate\Database\Query\JoinClause::onRaw()
Deu esse erro.
Comment: Atualizei a resposta. Eu tinha confundido o `whereRaw` e acabei complicando mais do que o necessário. Acredito que agora vai dar certo.

Como escrever Query utilizando Laravel


Covariance beween value and prediction in linear regression

Question: Equation (7.23) in the book "Elements of Statistical Learning" reads that for the model $Y = \beta \cdot X + \epsilon$ with $\epsilon \sim \mathcal N(0, \sigma^2)$,
We have
$$\sum _{i=1}^N \operatorname{Cov}(\hat y_i, y_i) = d \sigma^2,$$ where $d$ is the number of features and $N$ is the size of the training sample.
I don't understand how this can be true, since it seems evident that increasing the size of the training set should also increase this sum, as we add many terms in the sum while intuitively only decreasing the covariance a little. Moreover, I would like to know where I may find a proof of this fact, as it is just quoted in the book with seemingly no justification.
Answer: This is more of a maths question, so here is the appropriate answer on Mathematics Stack Exchange:
https://math.stackexchange.com/a/266069/476670
The answer above shows that $\text{Cov}(\hat{\textbf{y}}, \textbf{y}) = \sigma^2\textbf{H}$, where $\textbf{H}$ is the hat matrix, $\textbf{X}\left(\textbf{X}^T\textbf{X}\right)^{-1}\textbf{X}^T$. We can extend this answer about the vector $\textbf{y}$ to your question about scalar $y_i$:
$$
\sum\limits_{i = 1}^N\text{Cov}(\hat{y}_i, y_i) = \text{tr}(\textbf{H})\sigma^2.
$$
According to this other answer on Mathematics Stack Exchange, $\text{tr}(\textbf{H}) = \text{tr}(\textbf{I}_d) = d$.
Comment: The last line is wrong, $\text{tr}(H)$ is the *rank* of $H$, and the sum of its eigenvalues (all either 1 or 0).
Answer: The other answer links to the proofs, but let's talk intuition.
Before we discuss linear regression, suppose you have a set of real numbers $\{x_1, \dots, x_m\}$ and you want to know how far you have to increase $x_1$ so that $\bar x_m$ increases by 1 unit. Do you have to move $x_1$ farther if $m = 10$ or if $m = 1000$? Clearly the answer is $m=1000$, which shows how the mean becomes less and less correlated with each particular input as we sample more and more. Asymptotically, if instead the $X_i$ are iid Gaussian RVs (for example, and switching to upper case to show they're RVs) with mean $\mu$, we have $\bar X_m \to_p \mu$ and constants are uncorrelated with everything, so in the limit our sample average is actually uncorrelated with each input observation.
Now, returning to linear regression, consider a single term $Cov(\hat y_i, y_i)$. This tells us how closely $\hat y_i$ tracks to $y_i$, and is exactly answering the question from the previous paragraph of how much $\hat y_i$ moves when $y_i$ moves. The more $\hat y_i$ changes by, the more flexible our model is (because changing a single observation can change its prediction), which is why $\sum_i Cov(\hat y_i, y_i)$ is a great definition of degrees of freedom.
Now imagine that we are fitting a linear regression and $N$ gets bigger and bigger, and we want to explore the effect of changing one particular observed value $y_0$. The more data we have, the farther we'll have to move $y_0$ in order to make an impact on our loss that's big enough for the trend line to move. In other words, as $N$ gets bigger, $Cov(\hat y_i, y_i)$ shrinks for each $i$ which is exactly what we saw with our $\bar X_m$ (and indeed, that corresponds exactly to an intercept-only linear regression). That's how this sum can work out, because even though we add more and more things, those individual things get smaller and smaller because our model complexity doesn't increase with $N$ (compare this to nonparametric methods like smoothing splines where as $N$ increases you can model a wider range of patterns).


Syntax of mac2vlan file in freeradius?

Question: Below is the content of mac2vlan file in freeradius.
When I uncomment this line 00:01:02:03:04:05,VLAN1 it logs a parsing error
including configuration file /etc/raddb/modules/mac2vlan
/etc/raddb/modules/mac2vlan[10]: Parse error after "00:01:02:03:04:05"
Errors reading /etc/raddb/radiusd.conf

What is the correct syntax?
# -*- text -*-
#
#  $Id$

#  A simple file to map a MAC address to a VLAN.
#
#  The file should be in the format MAC,VLAN
#  the VLAN name cannot have spaces in it, for example:
#
        00:01:02:03:04:05,VLAN1
#       03:04:05:06:07:08,VLAN2
#       ...

passwd mac2vlan {
        filename = ${confdir}/mac2vlan
        format = "*VMPS-Mac:=VMPS-VLAN-Name"
        delimiter = ","
}

Answer: I know it's been a while since this was posted, but for the next guy (or gal) that stumbles across this posting looking for help as I did, hopefully will find value in my answer.
The /etc/raddb/modules/mac2vlan file only shows an example of what the mac2vlan file should look like.
The actual mac2vlan file is referenced in this script:
filename = ${confdir}/mac2vlan

You should have (or create as I had to) a mac2vlan file in /etc/raddb/ using the syntax referenced above. Do not uncomment anything in /etc/raddb/modules/mac2vlan file.
I should also mention, that the version of freeradius I am using, the path is actually /etc/freeradius not /etc/raddb as referenced above.
Answer: Looks like it is complaining about a line with a comment, which is missing a # character at the start of the line. Additionally, the last line probably shouldn't have been a comment, so the # character on the last line need to be removed.
Comment: Trust me that  is not the reason.
Comment: @EdikMkoyan Then edit your question, such that it is clear exactly what is in each configuration file.

Syntax of mac2vlan file in freeradius?


form_alter correct coding question

Question: <code>function MYMODULE_form_views_exposed_form_alter(&$form, $form_state) {
 if ($form['#id'] == 'views-exposed-form-search-page-1') {
 $form['submit']['#value'] = 'Go';
 $form['text']['#size'] = '100';
  }
}
</code>
In the code above, which is the correct way:
<code>   $form['submit']['#value'] = 'Go';
</code>
Or
<code>   $form['submit']['#value'] = t('Go');
</code>
And:
<code>  $form['text']['#size'] = '100';
</code>
Or
<code>  $form['text']['#size'] = 100;
</code>
Answer: Always wrap all strings in t() so that it can be translated. And always use english for strings in the source code because Drupal assumes that it is english. Even if your site is in a different language (You can translate it afterwards through the UI or create .po files).
The other one doesn't matter. Technically, it's an integer, so without quotes but it will be converted to a string when displayed anyway.

form_alter correct coding question


Impressão de uma sequência de números formatado de 3 em 3 separados por traço

Question: Digamos que eu tenha a seguinte entrada String S = "00-44  48 5555 8361" e que preciso retornar essa cadeia de caracteres dividida de 3 em 3, separadas por "-", da seguinte maneira:

Saída: 004-448-555-583-61

A quantidade de caracteres pode variar. Abaixo o seguinte escopo:
public class Solution{
    public static String solution(String S){
    }
}

public static void main(String[] args) {
        String S = "00-44  48 5555 8361";
        System.out.print(solution(S));

    }

}

De uma forma eficaz, como resolver isso em Java 8?
Answer: Regex faz mágica:
class Solution {
    public static void main(String[] args) {
        String s = "00-44  48 5555 8361";
        System.out.println(solution(s));
        String s2 = "00-44  48 5555 8361 xxx 1";
        System.out.println(solution(s2));
        String s3 = "12345";
        System.out.println(solution(s3));
    }

    public static String solution(String s) {
        return s.replaceAll("[^\\d]", "").replaceAll("...", "$0-").replaceAll("-$", "");
    }
}

Eis a saída:
004-448-555-583-61
004-448-555-583-611
123-45

Veja aqui funcionando no ideone.
Explicação:

O replaceAll é um método que opera sobre três strings: A instância sobre a qual o método é chamado (A), o primeiro parâmetro (B) e o segundo parâmetro (C). Esse método procura por ocorrências da expressão regular de B dentro da string A e as substitui por C, retornando o resultado após serem feitas todas as substituições. Referências denotadas com $ podem ser usadas em C para referenciar grupos definidos em B.
O replaceAll("[^\\d]", "") utiliza a expressão regular [^\\d]. Esta expressão regular serve para representar qualquer coisa que não for um número. O trecho \\d é o que representa um número. O [^ ... ] indica todos os caracteres exceto os que estão entre o [^ e o ]. Logo, [^\\d] representa todos os caracteres, exceto os numéricos. Assim sendo isso, isso vai substituir qualquer caractere que não seja um número pela string vazia. Ou seja, isso serve para arrancar todos os caracteres não-numéricos da string.
O replaceAll("...", "$0-") utiliza a expressão regular .... O . representa qualquer caractere, logo ... são três caracteres. Como a expressão regular anterior já eliminou os não-numéricos, então isso daqui encontra os dígitos em grupos de três em três. Logo, essa expressão substitui cada trio de caracteres numéricos pelo que é representado por $0-. Ocorre que $0 representa tudo o que a expressão regular encontrou, que no caso é os três caracteres encontrados. Assim sendo, isso vai substituir cada três caracteres por esses mesmos caracteres seguidos de um -.
Pode ser que sobre um - no final, tal como no caso do "00-44  48 5555 8361 xxx 1". Por isso temos o replaceAll("-$", ""). A expressão regular -$ significa um - seguido do fim da string (que é representado por $). Isso significa que o traço que estiver no final da string (se houver) vai ser substituído por uma string vazia. Ou seja, deletado.
Comment: Resolveu, sua resposta foi incrível!
Comment: Esse redux faz mágica, olha a quantidade de linhas de códigos! Muito eficiente sua solução. Muito Obrigada!
Comment: @mayssalns Se essa resposta resolveu o seu problema e não restou nenhuma dúvida, marque-a como correta/aceita ao clicar no "✅" que está ao lado dela, o que também marca a sua pergunta como resolvida. Se ainda te resta alguma dúvida ou gostaria de maiores esclarecimentos, fique a vontade para comentar.


What does the chord notation X/Y ("slash chord") mean?

Question: Questions about slash chords are frequent enough that this question was created to answer the general concerns as well as link to related or more specific questions on the topic.

Chords notated like X/Y: What do they mean, and how does one play them?
The first two bars of "Can't Help Falling in Love" (from here)

The first four bars of "On Green Dolphin Street" (from here)

This example of how to play Queen-style chords on guitar (from here)
Answer: TL;DR
For pianists, play the X chord with the right hand and the Y bass note with the left hand. For guitar/bass bands: guitarist plays the X chord and bassist plays the Y bass note. (With thanks to @piiperiReinstateMonica)

TOC
There are three main parts to this answer that can be read independently of each other.

What does it mean? (includes subsections on literal interpretation and contextual meanings)
- Literal meaning
- Contextual meaning
How does one play it?
Other slash uses
- Secondary dominants
- Polychords
- 6/9 chords
Further reading / Related questions

What does it mean?
Literal meaning
Chords of the form X/Y, read X over Y, and sometimes called "slash chords", mean
play chord X, making Y the lowest note.
For example, the first of the "Queen chords", Bb7/D, means play a Bb7 chord, and make the lowest note a D.
Similarly, the second chord in "Can't Help Falling in Love", means play a C major chord, but make the lowest note a Bb. Note that Bb is not part of a C major chord (which contains pitches C E G). This is address below in the "How does one play this?" section.
Contextual meaning

Chord inversion
When chord X includes note Y, then you're looking at an inversion of X. For example C/E is a first inversion C major chord, played E-G-C (or E-C-G). Similarly, Cm7/Bb is a third inversion Cm7 chord played Bb-C-Eb-G (or Bb-Eb-G-C, etc.)

Passing movement in the bass
Sometimes you want the bass to move smoothly from one chord to the next. Consider the "Can't Help Falling in Love" example in the OP. The basic chord sequence is Bb - C - F - Gm. If taken literally, the bass player would play only the chord roots:

X:0
K:Fmaj
M:4/4
L:1/2
[V:v1 clef=bass] "Bb"B,, "C"C, | "F"F, "Gm"G, |

However, the chord notation is letting the bass player know that a descending step-wise pattern is wanted.
X:0
K:Fmaj
M:4/4
L:1/2
[V:v1 clef=bass] "Bb"B,, "C/Bb"B,, | "F/A"A,, "Gm"G,, |

Pedal tones
Sometimes you want chord to change above a stationary bass pitch, known as a pedal tone The "On Green Dolphin Street" example in the OP demonstrates this. The C is kept in the bass through the entire first four bars while the principal chords change above it.

Notational convenience
Sometimes it's easier for the music reader if the chord notation uses slashes to clarify or simplify things. For example, "On Green Dolphin Street" might have been notated Cmaj9 Cmin7 D7 Dbmaj7. This would be literally correct as far as the notes involved, and an astute player, or one familiar with the tune, would recognize the possibility of the C pedal tone (see #3 above).
However, that's more complex to read than Cmaj9 Eb/C D/C Db/C, which mainly involves triads plus a bass note, and the /C chords make the pedal tone explicit.

How does one play it?
In literal terms, this is answered above: you play chord X, placing (or adding) Y as the lowest pitch. In essence, you can play chord X however you want (that is, in any voicing), as long as Y is the lowest pitch.
In practice, this depends on the context you're playing in. If you're a soloist or otherwise responsible for the bass line/lowest pitch, then you make sure Y is the lowest note. But if you are playing with a bass player, or some other instrument responsible for the lowest part, then you probably want to avoid playing Y -- at least not in the same octave as the bass part -- so as not to conflict. (This is a rule of thumb, but not a rule. For more on that, see this question: Should the comping instrument ever double the bass player?)
So, for example, given a G/B chord, if the bass player has the B, then the piano or guitar would play G and D (and possibly B), pitched higher than the bass's B.
Other slash uses
Secondary dominants
In Functional Analysis (Roman Numeral Analysis), slashes are used to indicate a secondary dominant relationship. Secondary dominants are explained in What is a secondary dominant chord?.
Polychords
There is another form of "slash" chord in which a horizontal line is used, and the notation is written vertically. This denotes a "polychord". See also John Belzaguy's answer to the question Chord Symbols in Kurt Rosenwinkel transcriptions
6/9 Chords

The 6/9 chord is a pentad with a major triad extended by a sixth and ninth above the root, but no seventh. (Wikipedia)

In this case, the slash is just a separator for readability.
Related questions / further reading
Questions related to slash notation are reasonably common on SE:MP&T. Here's a compendium.
"What does it mean?" questions.

Secondary dominants/slash notation in Elton John
What does 'on' mean in chord notation?
What is a G/F chord, and how do you play it?
What are G7/D and C/G chords?
Does the bass note in a "slash" chord really have an associated interval?
Meaning of slash chord without anything left of the slash
Slash chords and notation for A/C (according to Haunschild Book)
What do the brackets mean?
Deciphering the notation of this slash chord
Is a slash chord the same as an Inversion?
What is a D/A Chord?
Playing one chord over another
what is the root note of D/A
Roman numeral analysis of chord with non-chord tone in bass
Why is it called a Gm7/C when C is not even in the chord?
Csus4/Db vs Dbmaj7#11
How to interpret this chord notation?
what is the slash in roman numerals?

"How to play it?" questions.

How to play chords like G/B
Can E/G# be played like this?
What is a G/F chord, and how do you play it? (See above)
"slash" chords, e.g. B/F♯ - are these only for inversions, or can any note be the bass note?
How to play these slash chords (piano)?
To Slash or not to Slash?
How do you play a 3 note jazz voicing for a slash chord?
importance of the information after the slash for a single guitar player
Am/C guitar chord help
Playing one chord over another (See above)
Difference between playing a D/F# and a D in the key of G on piano
what is the root note of D/A
Is it always necessary to include the root in a slash chord?
What does 'on' mean in chord notation?
How should this "fraction" chord be played on a piano? (Polychord, not slash notation)

Also of interest

About slash and 7th chord's meaning and their history
Slash chords nomenclature/reading convention
How to determine which (slash) chord to use?
Improvisation Technique and Theory Over Modal Sus or slash chords
How do I use slash chords in music composition?
Is it CMaj9/B or Cadd9/B?
Chord Symbols in Kurt Rosenwinkel transcriptions (polychords)
How to transpose slash chords for guitar
What is the clearest way to signify the harmonic function of a polychord?
Is there a term for chords like F/G and C/D? (specifically, major chord over supertonic)
Comment: If the chord is G/B, the the bass player plays B. Fair enough, but why should anyone else *avoid* playing a higher B? I understand that no-one else needs to play that low B, but what's wrong with a higher one? I do it all the time! Should 'To Slash or not to Slash' be included?
Comment: If the other instruments avoid playing a B in a G/B chord it could sound bare; especially if the bass plays a bottom B. Like Tim, I tend to play it. Though if I'm in a good mood I might avoid playing it in the same register as the bass.
Comment: @Tim Re: doubling the bass at a higher octave. The only "rule" I know of that relates is not doubling the leading tone in species counterpoint exercises. (I.e., Don't double the third of a V chord.) But in practice, your point is beyond fair. I hope it's sufficient to have linked to the [should I double the bass player](https://music.stackexchange.com/questions/104159/should-the-comping-instrument-ever-double-the-bass-player) question, but let me know if you feel it should be addressed explicitly here.
Comment: Those counterpoint exercises aren't really for today's playing in a lot of cases. That 3rd of a V chord often cries out to be played, maybe three or four octaves higher than a bass would play it. As the leading note, there's nothing wrong with it doing its job! The curious amongst us will eventually find the 'Slash' question. Would 'figured bass' feature somewhere in this answer?
Comment: @Tim Re: Figured bass. I purposely avoided it to keep from getting over-broad. In my searching I didn't find much overlap between slash notation questions and figured bass questions. (However, here's the one exception I found: [Roman Numeral Chords with Slash](https://music.stackexchange.com/questions/65924/roman-numeral-chords-with-slash). Linked here, now, I guess, so maybe that's sufficient.) But as always, let me know if you disagree, or if you find questions that deserve links.
Answer: Based on your examples it is almost self explanatory.  The X is the chord that is being played and the Y indicates the note that should be played in the bass, lowest pitch note in the chord.  That does not have to be played by the bass player but should be the lowest pitch note.  As for how to play them, there are several ways to play any chord.  Since you have provided chord charts with the specific fingering I'd say play them that way.  But without those you might have to work at finding a suitable fingering.
In many cases the slash notation indicates an inversion, for example A/E might be A major second inversion (5th in the bass).  In some of your examples the chords are more exotic.  You have C/Bb which would be a C7 chord 3rd inversion (7th in the bass).  In many cases you can grab a standard chord form and then search for a way to grab the bass note if it's in the vicinity.
Since this question seems very guitar-centric I'd recommend going through Chord Chemistry by Ted Greene, and Mel Bay's Rhythm Guitar Chord System.  Two very different approaches but both very useful and valid.
Comment: 'The lowest pitch note in the chord'. Quite often, the 'slash note' isn't even part of the chord. It doesn't have to be - but when it is, that shows which inversion is required.
Comment: That is an interesting way to put it.  I would say that by definition once the Y is placed there, it is "part of the chord" but  I suppose then my description is self contradictory.  To tell you the truth I have never seen C/Bb, but I've seen C7/Bb for example.
Comment: C/Bb occurs quite often - C, C/B, C/Bb, F/A. And I also regard the 3rd one as C7, and may well add a higher Bb, although I believe the first 3 chords would be simple C, in the composer's eye (or even ear...).
Comment: I am not sure I understand your comment "and may well add a higher Bb".  Once you put the Bb there it IS a C7.  If you play the slash chord I don't know how the composer would hear a C.  I think that by definition of X/Y, Y much be the lowest pitch note.
Comment: I am a beginner guitar player, and I think there's an example that I was taught that uses this, which is a C/G combined with a G (or maybe G9).  In this case, the chords used for the song are G and C, and you simply move the fingers on the lowest strings from 3 3 - x x to - 2 2 - x x.  ( I think x is 4. Sorry, not just beginner, but I've been away from practice for months).  If it is C/G is that an inversion?
Comment: @Xalorous, I am not sure how you "combined" this with G9.  C/G alone is a C maj chord with G in the Bass, 2nd inversion.


why doesn't tolower convert my uppercase chars to lowercase?

Question:
Possible Duplicate:
tolower() not working

Here is my code:
char *ptr=&twod[j][i];

                 while (*ptr != '\0')
    {
        tolower(*ptr);

        cout<<endl
            <<endl
            <<endl
            <<*ptr;

        ptr++;

    }

When I cout the above, the the uppercase letters still remain as uppercase. Can someone explain to me why?
Comment: `tolower` is a function from the C standard library. Remember that in C, `someFunction(variable)` can *never* modify the variable, because C has no notion of references.
Answer: You need to do this:
*ptr = tolower(*ptr);

std::tolower returns the lowercase. It does not accept the argument by reference, hence it cannot modify *ptr which you pass to it.
Read the documentation of std::tolower for detail.
Comment: The argument to `tolower` must be cast to `unsigned char`. Read the documentation for detail.
Comment: @RolandIllig: The caller doesn't need to cast. Just pass `*ptr` which is `char` which is fine if it is not negative.
Comment: "If it's not negative." — But who guarantees you that? There are popular implementations out there where `char` can be negative. Since the question doesn't give examples of particular strings, you have to expect _any_ character.
Answer: tolower doesn't modify the value, it returns a new one.
Try this:
*ptr = tolower(*ptr);

Answer: tolower doesn't mutate its argument. Set a variable or print out the operation:
*ptr = tolower(*ptr);
std::cout << *ptr;
// or
std::cout << tolower(*ptr);


Calling cv::calibrateCamera() failed

Question: I'm trying to get the cameraMatrix from the function cv::calibrateCamera(), actually I'm not sure if I did it right or not, my initial idea is that:

Get two input images which come from the same camera.
Extract all the feature points from image_1 and image_2
Use cv::calibrateCamera() to get the cameraMatrix (don't know if it would work or not)

Here is my code of doing it:
calling calibrateCamera()
The compilation went through pretty well, but when I ran it, it throws an exception said:

OpenCV Error: Assertion failed (i < 0) in create, file
  /home/hjbolide/OpenCV-2.3.1/modules/core/src/matrix.cpp, line 1198
  terminate called after throwing an instance of 'cv::Exception'
  what():  /home/hjbolide/OpenCV-2.3.1/modules/core/src/matrix.cpp:1198:
  error: (-215) i < 0 in function create

As I said, I was just trying this method, and try to get the cameraMatrix from it. Don't know where it goes wrong. Any suggestions?
Thanks very much.
Comment: I would start with the example app and work from there
Answer: I had a similar problem. I ported a C calibration example from the Learning OpenCV book to use the C++ interface and was seeing the exact error you saw. I changed rvec and tvec to std::vector<cv::Mat> and then the calibration worked. Note that the 2.3 documentation marks both rvec and tvec as OutputArrayOfArrays.
Comment: This is still the case with OpenCV 2.4.6.

Calling cv::calibrateCamera() failed


Loop infinito indevido no while

Question: Fiz um programa para calcular dentro de uma sequência a soma dos números positivos e a soma dos números negativos. Quando utilizo o comando while, a ideia é que seja dentro de uma sequência de 7 números, e depois o programa saia do while e faça condição, porém não está acontecendo isto.
Segue código abaixo:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<locale.h>

int n, num, somaPositivo, somaNegativo, i;

int main ()
{
    setlocale(LC_ALL, "portuguese");

    printf("\n Digite o tamanho da sequência: ");
    scanf("%f",&n);

    somaPositivo = 0;
    somaNegativo = 0;
    i = 1;
    while (i <= n)
    {
        printf("\n Digite um número da sequência: ");
        scanf("%f",&num);
    }

    if (num > 0)
    {
        somaPositivo = somaPositivo + num;
    }
    else
    {
        somaNegativo = somaNegativo + num;
    }

    i = i + 1;

    printf("\n A soma dos números positivos da sequência é: \n",somaPositivo);
    printf("\n A soma dos números negativos da sequência é: \n",somaNegativo);
}

Comment: Alguma das respostas resolveu sua dúvida? Acha que pode aceitar uma delas? Veja o [tour] como fazer isso, se ainda não o fez. Você ajudaria a comunidade identificando qual foi a melhor solução para você. Pode aceitar apenas uma delas. Mas pode votar em qualquer pergunta ou resposta que achar útil no site todo.
Answer: Este código tem vários erros e nem compila, e algumas práticas ruins ,então note todas alterações.
O principal problema é que boa parte do que deveria estar dentro do laço está fora, como não há incremento o laço nunca termina. A acumulação realizada também precisa estar ali no laço.
Preferi usar um for que é o mais adequado para este caso. Simplifiquei o código também.
Não resolvi o problema de uso do scanf() não tratando seu retorno porque para exercício está bom assim.
#include<stdio.h>
#include<math.h>
#include<locale.h>

int main() {
    setlocale(LC_ALL, "Portuguese");
    int n;
    printf("\n Digite o tamanho da sequência: ");
    scanf("%d", &n);
    int somaPositivo = 0;
    int somaNegativo = 0;
    for (int i = 0; i < n; i++) {
        printf("\n Digite um número da sequência: ");
        int num;
        scanf("%d", &num);
        if (num > 0) somaPositivo += num;
        else somaNegativo += num;
    }
    printf("\n A soma dos números positivos da sequência é: %d\n", somaPositivo);
    printf("\n A soma dos números negativos da sequência é: %d\n", somaNegativo);
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Answer:
Controle condicional (if) está fora do while, isso significa que ele não é executado n-vezes, mas apenas uma: após a saída do while. Não havendo soma real dos números;
O caractere especificador "%f" é para tipos de ponto flutuante como float ou double;
O dois últimos printfs não possuem o caractere especificador de impressão "%f" para float/double ou "%d" para int;
A variável i, que será usada para contador, deve preferencialmente ser do tipo int, e o scanf para isso, deve usar o caractere especificador %d. Nada impede contudo, de ser float ou double;
O loop é infinito, pois não há incremento da variável i, dentro do loop, ou seja, a condição (i <= n), sempre será atendida, suponto que n seja >= 1.

Supondo que haja algum motivo justo para se usar o while e não outro, como o for, o código correto (testado) dever ser parecido com o abaixo, se a sequência de números for realmente de inteiros:
 int n, i = 1, num, somaPositivo = 0, somaNegativo = 0;

 int main() {
   printf("\n Digite o tamanho da sequência: ");
   scanf("%d", &n);

   while (i <= n) {
     printf("\n Digite o %do número da sequência: ", i);
     scanf("%d", &num);

     if (num > 0) {
       somaPositivo += num;
     } else {
       somaNegativo += num;
     }

     i++;
   }

   printf("\n A soma dos números positivos da sequência é: %d \n", somaPositivo);
   printf("\n A soma dos números negativos da sequência é: %d \n", somaNegativo);
 }

Comment: `%f` é float, enquanto que `%lf` é double

Loop infinito indevido no while


Check if string is a palindrome after removing one character. My working solution is too slow

Question: I cant seem to find a proper solution to an exercise. The exercise asks to create a method that returns true if a string can be a palindrome by removing one character. I have a solution that works but fails tests of large (100,000 character) strings because its exceeding the time limit of 1 second. Can somebody point me in the right direction?
I realize my approach is brute force and I'm sure there's a better way to solve it. I'm assuming my problem lies with the iteration.
public class Main {

    public static boolean makePalindrome(String mjono) {

        StringBuilder sb = new StringBuilder(mjono);

        for (int i = 0; i < mjono.length(); i++) {
            sb.deleteCharAt(i);

            if(isPalindrome(sb.toString())){
                return true;
            } else {
                sb.insert(i, mjono.charAt(i));
            }
        }
        return false;
    }

    private static boolean isPalindrome(String string) {
        return string.equals(new StringBuilder(string).reverse().toString());
    }

    public static void main(String[] args) {
        System.out.println(makePalindrome("ABCBXA"));
        System.out.println(makePalindrome("ABCBAX"));
        System.out.println(makePalindrome("ABCXBA"));
        System.out.println(makePalindrome("ABCDE"));
        System.out.println(makePalindrome("BAAAAC"));
    }
}

These are the tests it fails:
@Test(timeout=1000)
public void suuri2() {
    int n = 100000;
    char[] t = new char[n];
    for (int i = 0; i < n; i++) t[i] = 'A';
    t[12345] = 'B';
    testaaSuuri(new String(t), true);
}

@Test(timeout=1000)
public void suuri3() {
    int n = 100000;
    char[] t = new char[n];
    for (int i = 0; i < n; i++) t[i] = 'A';
    t[12345] = 'B';
    t[54321] = 'C';
    testaaSuuri(new String(t), false);
}

Thanks in advance.
Comment: Seems to be a popular question, see http://stackoverflow.com/questions/10577422/create-palindrome-from-existing-string-by-removing-characters?s=3|0.8945
Comment: As a slight optimization, you only need to reverse half of the string.
Comment: If the code is working, it might be better suited for [Code Review](http://codereview.stackexchange.com/).
Comment: The main inefficiency is in editing the new string with `.insert()`.  There is a much better way to solve it.  Take the original string. Create another string to reverse it.   Walk the string (no editing required) starting at the first character, looking for exact character to character matches, allowing exactly one character removal.  If you get halfway through the string with only one error you're done.
Answer: Well, there's of course the naive solution running in O(n ^ 2) by trying each possibility to remove one char.
But we can certainly do better:
We can define a palindrome recursively:
palindrome = x.palindrome.x | x | x.x , where x is an arbitrary token

So how does that help us? Pretty simple: we can derive a rules that allow checking whether the string is palindromic in O(n).
A palindrome consists of a char c, followed by a string that must be empty or palindromic, followed by another c, if it's longer than 1 char. If it's of length 1, it's automatically palindromic.
Thus, the last character must be equal to the first, the second to the second to the last, and so on. So basically:
boolean isPalindrome(String s){
    for(int i = 0 ; i < s.length() / 2 ; i++)
        if(s.charAt(i) != s.charAt(s.length() - i - 1))
            return false;

    return true;
}

We have to alter this rule a bit, since once we may remove a single character. This introduces splitting the whole problem into two parts, as we can see from a definition:
palindrome_1 = s.x.palindrome.reverse(s) | s.palindrome.x.reverse(s) | palindrome

As we can easily see, this contains the original palindrome-definition, but in addition allows introduction of one additional char x.
static boolean isPalindrome_1(String s){
    for(int i = 0 ; i < s.length() / 2 ; i++)
        if(s.charAt(i) != s.charAt(s.length() - i - 1))
            return isPalindrome(s , i + 1 , s.length() - i - 1) ||
                    isPalindrome(s , i , s.length() - i - 2);

     return true;
}

static boolean isPalindrome(String s , int lower , int upper){
    while(lower < upper){
        if(s.charAt(lower) != s.charAt(upper))
            return false;

        lower++;
        upper--;
    }

    return true;
}

An explanation/or at least an attempt to explain this:
This piece of code:
if(s.charAt(i) != s.charAt(s.length() - i - 1))
    return isPalindrome(s , i + 1 , s.length() - i - 1) ||
        isPalindrome(s , i , s.length() - i - 2);

Is required, if the definition of palindrome doesn't apply to our input-string. In that case, we have to check two possibilities, how the code was built:
s.x.palindrome.reverse(s)
s.palindrome.x.reverse(s)

If the definition of palindrome doesn't apply, we have reached a point, were we have to ommit either the character of at the start of the remaining string (x.palindrome) or the end of the remaining string (palindrome.x) and see, if the rest matches the definition of a palindrome. This is done by calling isPalindrome(...) with two different substrings, that are cut by one character at either the start or the end of the remaining string.
An few examples of how this code works:
A B C D E F E D C B A
|                   | portion that runs inside isPalindrome_1

A B D E F E D C B A
| |             | |  portion that can be checked inside isPalindrome_1
    |       |        isPalindrome(s , i , s.length() - i - 2)
      |       |      isPalindrome(s , i + 1 , s.length() - i - 1)

As we can see in the second example, the code searched for the first pair of chars that isn't equal. At this point, we have two substrings to search further, which each ommit one character, either at the beginning or the end of the string.
Efficiency:
This code runs in-place - there are never made any copies of the input-string. Runtime is O(n) (O(2 * n) to be precise). Building a faster solution won't be possible - at least until we get quantum computers ;)
Comment: Thanks for the thorough explanation. I understand the concept, I just need to wrap my head around some of the details.
Comment: Please fix your sample solution, it isn't even syntactically valid.
Comment: @Markus sry, didn't even test it. I just intended to provide code to show how it works, not to provide a simple copy-and-paste solution. But I'll fix that
Comment: @Markus fixed. That was nothing but a few typos and lines I forgot to delete
Comment: @Paul Thanks for taking the time. I think code examples posted here should be at least syntactically valid.
Comment: @Markus I was in a bit of a hurry, when I posted that yesterday. Sry for the incorrect code :). Anyways, I've the current version of the code is tested. Syntactically correct and results were correct for about a dozen of different input-strings.
Answer: Hint 1: since this is an exercise, posting solutions is inappropriate.  (It detracts from the learning experience of doing the exercise yourself.)
Hint 2:  The following operations are all O(N) for an N character String or StringBuilder:

Adding or removing a character from a StringBuilder
Creating a new StringBuilder from an existing StringBuilder
Reversing a StringBuilder
Creating a String from a StringBuilder (toString())
Comparing two equal or "almost equal" String objects.

(In most cases you copy or compare N characters.  For insertion and deletion, you copy on average 0.5 N characters assuming that the buffer does not need to grow, but that is still O(N).  For equals ... it is complicated, but the worst-case is clearly O(N).)
So a fast palindrome tester for large strings needs to avoid these operations.
Hint 3: you can treat the string as an array of characters, either by converting it into a char[] or using charAt(...).
Hint 4: you don't have to physically remove the char from the string.  You can just get your algorithm to pretend it isn't there.
Answer: We can solve this using LCS(Longest Common Sub-sequence).
LCS tells us the length of the longest sub-sequence in two strings.
boolean isPalindromAfterRemovingOneChar(String s) {
    int lengthOfLCS = lcs(s, s.reverse(), s.length());
    return (s.length()- lengthOfLCS) == 1;
}

Answer: function test(s) {
const check = isPalindrome(s)
if (!check) {
    const arr = s.split('')
    const arrCheck = []
    arr.forEach((element, i) => {
        if (element !== arr[arr.length - i - 1]) {
            const news = Array.from(arr)
            console.log(arr, news.splice(i, 1))
            isPalindrome(news.join(''))
        }
    });
    console.log('arrCheck', arrCheck)
}

function isPalindrome(s) {
var reversedString = s.split("").reverse().join("");
if (s === reversedString) {
    console.log('this string is palindrome', s)
    return true
} else {
    console.log('no')
    return false
}

test('aaab')

Answer: Only need to compare the first half to the second half.  Don't waste time reversing the whole String either.
private boolean isPalindrome(String string) {
    char[] values = string.toCharArray();

    for (int i = 0; i < values.length / 2; i++) {
       if (values[i] != values[values.length - 1 - i])
           return false;
    }

    return true;
}


ARM template adminPassword is null for Uri file deployment but not for local files

Question: In PowerShell I deploy a simple ARM template with a SQL Server 2022 VM.
I pass the adminPassword parameter as a securestring to the cmdlet New-AzResourceGroupDeployment in my script and it works fine, when the parameter file and template file are locally on my machine in Windows.
# This one works fine:
New-AzResourceGroupDeployment -ResourceGroupName $resourceGroupName -TemplateParameterFile parameters.json -TemplateFile template.json -adminPassword $adminPassword

But the parameterpassing of adminPassword does not work, when I point directly to the files in GitHub. I get an error which says the adminPassword parameter is null
New-AzResourceGroupDeployment -ResourceGroupName $resourceGroupName -adminPassword $adminPassword -TemplateParameterUri https://raw.githubusercontent.com/camillagaardsted/dp300/main/Lab1VM/parameters.json -TemplateUri https://raw.githubusercontent.com/camillagaardsted/dp300/main/Lab1VM/template.json

My complete script can be found here:
https://github.com/camillagaardsted/dp300/blob/main/Lab1VM/deployvm.ps1
I know it's not best practice to save a password in a script, but it's for a short demo and I don't want to use Azure key vault in this case.
Why does it fail with with the github files and not with the local ones?
Comment: I have tried to deploy the above shared arm template in my subscription with `adminpassword` value as `null` in parameters.json file and able to deploy the vm successfully as shown in this image https://i.imgur.com/zq9jKBm.png
Comment: It's when I use the TemplateParameterUri parameterset it fails. The local download of the template files works fine.
Answer: I tried the similar approach in my environment by referring to this MSDoc
Create a virtual machine and deploy it using ARM template. Provided parameters by parameters.json file containing adminusername & adminpassword(secure string).  The deployment was successful, with no admin password null errors by templateuri.
Note: Probably, you should upgrade Azure PowerShell version and test it if it is working with templateuri.
Sample code snippet:
{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/xxxxxdeploymentTemplate.json#",
  "contentVersion": "184.108.40.206",
  "parameters": {
    "adminUsername": {
      "type": "string"
    },
    "adminPassword": {
      "type": "secureString",
      "minLength": <userdefined>
    }
  }
}

vm.json:

New-AzResourceGroupDeployment:
 New-AzResourceGroupDeployment -ResourceGroupName <resourceGroup> -TemplateUri "https://raw.githubusercontent.com/Azure/xxxazuredeploy.json" -adminUsername <xxxadminUsername> -adminPassword <securedadminPassword> -dnsLabelPrefix <dnsLabelPrefix>

Deployed in Portal:
Comment: This one worked succesfully yesterday, so it works fine with just a templateUri:

    New-AzResourceGroupDeployment -ResourceGroupName $resourceGroupName `
 -TemplateUri "https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/quickstarts/microsoft.sql/sql-logical-server/azuredeploy.json" `
 -administratorLogin $adminUser -administratorLoginPassword $adminPassword

The problem arises when I have a template parameter file together with a templateUri. The files are generated via the Create VM wizard in the portal.


Twitter Module with Formatted tweet

Question: I use the Twitter module to create a feed from various accounts for my website.
If I created a block with a field Twitter: Formatted tweet, the preview doesn't show anything. A broken image, a blank message etc.
If I add also the field Twitter: Twitter status message ID, the preview show most of the tweets, but there are still some of them without content.
If I set the fields custom without the Formatted tweet, I don't have this problem.
Also, I have this error on the page where I show this block:
Notice: Trying to get property of non-object in twitter_views_handler_field_formatted_tweet->render() (line 146 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/twitter_views_field_handlers.inc).
Notice: Undefined property: stdClass::$text in twitter_views_handler_field_formatted_tweet->render() (line 157 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/twitter_views_field_handlers.inc).
Notice: Trying to get property of non-object in include() (line 10 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Trying to get property of non-object in include() (line 10 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Trying to get property of non-object in include() (line 11 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Trying to get property of non-object in include() (line 12 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Trying to get property of non-object in include() (line 21 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Trying to get property of non-object in include() (line 21 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Trying to get property of non-object in include() (line 25 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Trying to get property of non-object in include() (line 25 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Undefined property: stdClass::$twitter_id in include() (line 35 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Undefined property: stdClass::$twitter_id in include() (line 38 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Undefined property: stdClass::$twitter_id in include() (line 41 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Trying to get property of non-object in twitter_views_handler_field_formatted_tweet->render() (line 146 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/twitter_views_field_handlers.inc).
Notice: Undefined property: stdClass::$text in twitter_views_handler_field_formatted_tweet->render() (line 157 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/twitter_views_field_handlers.inc).
Notice: Trying to get property of non-object in include() (line 10 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Trying to get property of non-object in include() (line 10 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Trying to get property of non-object in include() (line 11 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Trying to get property of non-object in include() (line 12 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Trying to get property of non-object in include() (line 21 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Trying to get property of non-object in include() (line 21 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Trying to get property of non-object in include() (line 25 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Trying to get property of non-object in include() (line 25 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Undefined property: stdClass::$twitter_id in include() (line 35 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Undefined property: stdClass::$twitter_id in include() (line 38 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Undefined property: stdClass::$twitter_id in include() (line 41 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Trying to get property of non-object in twitter_views_handler_field_formatted_tweet->render() (line 146 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/twitter_views_field_handlers.inc).
Notice: Undefined property: stdClass::$text in twitter_views_handler_field_formatted_tweet->render() (line 157 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/twitter_views_field_handlers.inc).
Notice: Trying to get property of non-object in include() (line 10 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Trying to get property of non-object in include() (line 10 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Trying to get property of non-object in include() (line 11 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Trying to get property of non-object in include() (line 12 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Trying to get property of non-object in include() (line 21 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Trying to get property of non-object in include() (line 21 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Trying to get property of non-object in include() (line 25 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Trying to get property of non-object in include() (line 25 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Undefined property: stdClass::$twitter_id in include() (line 35 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Undefined property: stdClass::$twitter_id in include() (line 38 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Undefined property: stdClass::$twitter_id in include() (line 41 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).

Answer: I'm gonna give you an answer that will not sound like good news. The rendering of the Twitter: Formatted tweet field is a bit buggy at times.
As a quick workaround I'd says don't use Twitter: Formatted tweet and use all the other Twitter: ......... fields available to you. And then style your output which ever way suits you with a template.
The alternative is to debug the module...
Comment: Ouch! That wasn't good! Thank you for your answer. At least I can take the css of the tweets that works and do it by myself on custom fields.

Twitter Module with Formatted tweet


Precise asymptotics of the sum of two square root functions

Question: Question: Let $x_n$ be some term that goes to infinity as $n\rightarrow\infty$. I would like to know the precise asymptotics of $-\sqrt{x_n}+\sqrt{x_n+4}$.
My attempt: We have
\begin{align*}
-\sqrt{x_n}+\sqrt{x_n+4}
&=\sqrt{x_n}\left(-1+\sqrt{1+\frac{4}{x_n}}\right) \\
&=\sqrt{x_n}(-1+1+\epsilon_n) \\
&=\sqrt{x_n}\cdot\epsilon_n,
\end{align*}
where $\epsilon_n$ is some decaying function that I want the precise asymptotics of. Thanks.
Comment: $\epsilon_n\approx 2/x_n$ by Taylor's Theorem.
Answer: $$\sqrt{x_n+4}-\sqrt{x_n}=\frac{4 }{\sqrt{x_n+4}+\sqrt{x_n}} \sim \frac{2 }{\sqrt{x_n}}$$
Answer: Your start is fine, now using the Taylor series
$$\sqrt{1+x}=1+\frac{x}{2}-\frac{x^2}{8}+\cdots$$
you obtain
$$\sqrt{x_n}\left(-1+1+\frac{2}{x_n}-\frac{2}{x_n^2}+\dots\right)=\frac{2}{x_n^{1/2}}-\frac{2}{x_n^{3/2}}+\dots\overset{x_n\to\infty}{\longrightarrow} 0$$
as the series is alternating and monotonically decreasing


Working out probability with alpha and beta

Question: Let's say in an experiment, the Null hypothesis is patients having Condition $\alpha$ (type I error) is $0.05$ and $\beta$ (type II error) is $0.15$.
If I have a sample of 50 patients, 35 with condition A and 15 with condition B, how would I work out the following:

Probability of properly predicting the condition of all patients with condition A
Probability of properly predicting the condition of all patients with condition B
Probability of predicting every condition properly
Probability of incorrectly predicting at least 5 condition Bs.

I'm really confused on this, but here's what I think:

Since the error rate is $0.05$, properly predicting it would be a chance of 0.95. So 0.95^number of Condition A = $0.95^{35}$. Is that right?
Reverse of 1, so $0.85^{15}$.
Multiplying 1 & 2
$0.15^{10}$.

Or am I doing it totally wrong and it should be worked out as a binomial problem?
Comment: Your first sentence makes no sense as is. What is the null hypothesis?
Answer: You cannot answer these questions with the information given.
$\alpha$ and $\beta$ are about incorrectly rejecting or accepting the null hypothesis. The null hypothesis is (nearly always) something like "there is no difference between groups".  Your statement

Let's say in an experiment, the Null hypothesis is patients having
  Condition A.

is not a hypothesis at all, since it doesn't say anything about those patients.
But, even with a proper null (something like "Patients in group A and group B will not differ on XXX") $\alpha$ and $\beta$ wouldn't answer your questions, as these are about the null, not about individual cases.


ng-click change value of a var

Question: I'm trying to set ng-click to modify a var inside my controller.
I've tried to set ng-click to target the var mar.

inside the controller.js i have this
eventsApp.controller('EventController', function EventController($scope) {

    //variables
    var mar = 'test-1';

}

So what i was hoping is to get var mar changed to 'test-2'; but, my html page just keeps displaying test-1.  is there a directive or a way to dynamically change var mar?
I do not want to have to setup a $scope.mar = 'test-1' and manipulate that. How can i do this?  Thank you.
Comment: Your update doesn't make sense. You want to be able to update a variable that is in your controller, but you don't want to have any type of relationship for that variable between your controller and your view? That's not really possible. Perhaps you could expand on your question to describe exactly what it is you're trying to accomplish here.
Comment: so i want to dynamically change the variable so i can use it in a function.

var tModel = modelService.models(mar);

would that be called like this?

var tModel = modelService.models($scope.mar);

?
Comment: You haven't given us much information to go on, but I will conditionally say that yes, that would be the way to use two-way data binding in AngularJS.
Answer: You should declare it on $scope and you have a typo
eventsApp.controller('EventController', function EventController($scope) {

    //variables
    $scope.mark = 'test-1';

}

EDIT
If you don't want to use $scope you have to assign this to a variable inside your controller. Here is a little example.
var app = angular.module('app', []);

app.controller('EventController', function ($scope) {

    //variables
    var vm = this;
    vm.mar = 'test-1';

});

  <button class="Button" ng-click="ctrl.mar = 'test-2';">
    Click me!
  </button>

{{ctrl.mar}}

If you want to use the variable inside a function on the controller you just use $scope.mar or vm.mar.
Comment: is there a way to call $scope.mark as a parameter in a function?  for example.

        var tModel = modelService.models(mar);
Comment: You can just use $scope.mark inside that function. Are you using the controller on a state?

ng-click change value of a var


Largest integer $k$ such that $\frac{a^{m+1}+b^{m+1}}{a^m+b^m}\geq\sqrt[k]{\frac{a^k+b^k}2}$

Question: The setup is as follows:
Suppose that $m$ is a given natural number. What is the greatest natural number $k$ such that for all real numbers $a,b>0$, we have $$\sqrt[k]{\frac{a^k+b^k}2}\le\frac{a^{m+1}+b^{m+1}}{a^m+b^m}$$?
Remark: Note that $$\sqrt[k]{\frac{a^k+b^k}2}\le\sqrt[l]{\frac{a^l+b^l}2}$$ when $k\le l$ by the Power mean inequality.
My attempt: I will show that $k\geq 1$, no matter what $m$ is:
Note that $$(a-b)(a^m-b^m)\geq 0$$ for all $a,b>0$ which implies that  $$ab^m+a^mb \le a^{m+1}+b^{m+1}$$
and thus $$a^{m+1}+ab^m+a^mb+b^{m+1}\le2(a^{m+1}+b^{m+1})$$
i.e.
$$(a^m+b^m)(a+b)\le2(a^{m+1}+b^{m+1})$$
which is exactly the above inequality for $k=1$.
Comment: Please clarify: Title says "smallest" but text says "greatest". You likely want greatest, since the RHS is an increasing function of $k$.
Comment: @CalvinLin Thank you for catching that
Answer: The hint.
Let $a\geq b$ and $a=xb$.
Thus, $x\geq1$ and we need $f(x)\geq0,$ where
$$f(x)=\ln\left(x^{m+1}+1\right)-\ln\left(x^m+1\right)-\frac{1}{k}\ln\left(x^k+1\right)+\frac{\ln2}{k}.$$
Now, $f(1)=f'(1)=0$ and $f''(1)=\frac{2m+1-k}{4},$ which says that for $k>2m+1$ our inequality is wrong.
Thus, it's enough to prove that
$$\frac{x^{m+1}+1}{x^m+1}\geq\sqrt[2m+1]{\frac{x^{2m+1}+1}{2}},$$ which is smooth:  https://artofproblemsolving.com/community/c6h1750157