Puzzle on Ranks

Question: Here is a puzzle from textbook : 40 Puzzles and Problems in Probability and Mathematical Statistics
Peter draws n = 100 independent realizations of a continuous rv and ranks them in increasing order from 1 to 100. Subsequently, Paula draws a single value from the same population and inserts this value into the rank order created earlier by Peter. For example, if her value is such that 50 of Peter's
draws are smaller and 50 are larger, then the rank associated with her draw
would be 51 — that is, overall, her value would be the 51st in increasing order.
Or, if her value is smaller than all 100 of Peter's, then the rank 1 would be
associated with it.
Derive for general n the probability that Paula's value will occupy rank
k, where 1 ≤ k ≤ n + 1.
My solution is as follows : If Paula's value is x, then
Pr(Rank = k| value = x) = $^nC_{(k-1)}[CDF(x)]^{k-1}[1-CDF(x)]^{n-k+1}$
Therefore,
Pr(Rank=k) = $\int$Pr(Rank = k| value = x) $PDF(x) dx$
Pr(Rank=k) = $\int ^nC_{(k-1)}[CDF(x)]^{k-1}[1-CDF(x)]^{n-k+1}PDF(x) dx$
Pr(Rank=k) = $\int_0^1 ~ ^nC_{(k-1)}[C]^{k-1}[1-C]^{n-k+1} dC$
Pr(Rank=k) = $^nC_{(k-1)} B(k,n-k+2)$
Pr(Rank=k) = $^nC_{(k-1)} \frac{(k-1)! (n-k+1)!}{ (n+1)!}$
Pr(Rank=k) = $\frac{n!}{(k-1)! (n-k+1)!} \frac{(k-1)! (n-k+1)!}{ (n+1)!}$
Pr(Rank=k) = $\frac{1}{ n+1}$
Is the logic correct?
Comment: In my humble opinion, that's a skewed view of rigour and symmetry. Arguments from symmetry can be quite rigorous (of course some aren't), and I suspect the likelihood of making an error in appealing to symmetry is lower than the one of making a mistake in a calculation like the one in your answer.
Comment: The answer is correct. The logic may or may not be correct but is certainly unnecessarily complicated. The answer is $1/(n+1)$ by symmetry.
Comment: @joriki : I know the answer is 1/(n+1), but is my approach correct? I generally try to do problems with mathematical rigor and not use symmetry analogy(which is awesome. I should have thought that way!)
Answer: The answer is right, but here is one way to see it.
Since all draws are iid, there is no reason to believe that the last one should be of a given rank more than another. Imagine Paula selecting first, then the second of the $n+1$ ball, etc.
So every rank is equally likely to occur.
Comment: The computation is correct. This is a good way of thinking about the problem though.
Comment: I was lazy to check it :)
Answer: You may equivalently let Peter draw $n+1 = 101$ independent values and then let Paula take one of Peter's at random.
So, in the ranking of the $n+1=101$ values, Paula's can be any of them, with equal probability $\frac{1}{n+1}=\frac{1}{101}$.

Puzzle on Ranks


Query funciona no phpmyadmin, mas nao funciona no PHP

Question: Estou tentando fazer uma query via php no Mysql , mas não esta funcionando no PHP, mas funciona no PHPMYADMIN.
<code>$check_in = strtotime($arrival);
$check_out = strtotime($departure);
</code>
Queries que já tentei no PHP...
<code>$query = "SELECT * FROM wp_st_availability WHERE post_id = 5993 AND check_in > '$check_in' and check_in < '$check_out'";

$query = "SELECT * FROM wp_st_availability WHERE post_id = '5993' AND check_in > '$check_in' and check_in < '$check_out'";

$query = "SELECT * FROM wp_st_availability WHERE post_id = '5993' AND check_in > '" . $check_in . "' and check_in < '" . $check_out . "'
</code>
;
Full code:
         $query = "SELECT * FROM wp_st_availability WHERE post_id = '$post_id' AND check_in > '" . $check_in . "' and check_in < '" . $check_out . "'";
       echo nl2br($query);
        $query = $this->db->query($query);
        if ($query->rowCount() == 1) {
        echo "achou";
        exit;
      } else {
        echo "nao achou nada";
        exit;
      }
Novo codigo, estou utilizando PDO.
Desculpe a formatação, não consigo formatar para codigo.
$check_in = '1514764800';
        $check_out = '1525132800';
<code>    $post_id = "5993";
     $query = ("SELECT * FROM wp_st_availability WHERE post_id='$post_id' AND check_in > '$check_in' AND check_in < '$check_out'");
  // $query = ("SELECT * FROM wp_st_availability WHERE post_id = '$post_id' AND check_in > '" . 1514764800  . "' and check_in < '" . 1525132800  . "'");
    $query = $this->db->query($query);
    if ($query->rowCount() == 1) {
    echo "achou";
    exit;
  } else {
    echo "nao achou nada";
    exit;
  }
</code>
Comment: A primeira versão está correta. Explica melhor o que é o "não funciona no php".
Comment: Faça um `echo nl2br($query)` pra ver os retornos
Comment: retorno do echo nl2br($query)  = SELECT * FROM wp_st_availability WHERE post_id = '5993' AND check_in > '1514764800' and check_in < '1525132800'
Comment: @bfavaretto ele executa ok no phpmyadmin ( retorna os resultados ) e no php não retorna nada no rowCount
Comment: Qual é o formato de $arrival e $departure? O strtotime está funcionando? Se estiver, faça `date('Y-m-d, $strtotime(...))`.
Comment: O strtotime ta funcionando sim.. $check_in vem 1514764800 e $check_out 1525132800
Comment: O problema não é o formato, pois quando eu pesquiso no phpmyadmin aparece os valores. Eu tirei as variaveis e coloquei o valor de check_in e check_out e não retornou nada no php. Fiz a mesma coisa no phpmyadmin e retornou os resultados
Comment: Pode estar dando erro na conexão ou na própria query. Não sei o que você usa para acessar o mysql (mysqli? pdo?), mas precisa chamar a função que te informa os erros.
Answer: Olha, fiz assim:
No banco:

No código php:
<code> <?php
 $mysqli = new mysqli("host", "user", "password", "db");

$id_post = 1;

$check_in = strtotime('2018-02-12') ;
$check_out = strtotime('2018-02-15');

//$check_in =1518393600;
//$check_out = 1518652800;

if($sth = $mysqli->query("SELECT * FROM teste WHERE id='$id_post' AND
check_in > '$check_in' AND check_in < '$check_out'")){
    while ($row = $sth->fetch_assoc()) {
       echo $row['nome'];
    }
}
</code>
resposta:

Observe que no banco o valor check_in é 1518393700, o valor da variável $check_in é menor que ele e o check_in é menor que o $check_out, ou seja, entre as duas, reveja na sua tabela os valores de check_in, talvez seja esse o problema, pra ter certeza da dos valores pesquisados, você pode fazer um var_dump($variavel); pra ver se variável está indo correta


How to find Popup state and refresh state in React-router?

Question: I know this question kind a stupid But I am pretty confused with this site producthunt how they are doing this.When clicking the product list popup with react router is done like this..

But When I refresh that page it render like this..How this is done using React-router
Answer: My bet would be that they use the state property when pushing a page to give an indication to the component about how to render the page. More specifically, to indicate the component where it comes from. For example:
router.push({
  pathname: '/posts/origami-studio-by-facebook',
  state: { fromPosts: true }
})

And then you can read the router's state in the route's component to check what page to show.
const Post = (productName) => {
  if(this.context.router.location.state.fromPosts) {
    return <Posts productPopup{productName} />
    // open the posts page with a popup for the product
  } else {
    return <PostPage productName={productName} />
  }
}

So when you open the page in your browser, the state.fromPosts is not set and you get redirected to the PostPage. In the end, even if the route is the same, what you end up seing is completely different.


por que o meu else não funciona?

Question: const alun = document.querySelector("#bottomaluno")

alun.addEventListener('click', addaluno)

function addaluno() {

    if(display = 'none') {
        document.querySelector("#alunos").style.display = 'block';
    } else{
        document.querySelector("#alunos").style.display = 'none';
    }
 }

Comment: Isto responde à sua pergunta? [Como utilizar o 'else if' corretamente?](https://pt.stackoverflow.com/questions/470618/como-utilizar-o-else-if-corretamente)
Answer: Porque um sinal de igual é de atribuição de valor e não de comparação, para ser dfe comparação tem que usar 2 sinais de igual, assim:
if(display == 'none') {

Comment: mesmo assim não funciona o único formato que funcionou foi com =, com dois "==" da esse erro  Uncaught ReferenceError: display is not defined
    at HTMLButtonElement.addaluno (addfield.js:6)
Comment: @Pedro isso ai é outro erro e não é igual ao código mostrado da pergunta.
Comment: é exatamente o mesmo código, quando eu utilizo = funciona somente o if, quando eu utilizo ou == ou === da esse erro de display não definido e não funciona nem o if e nem o else
Comment: Caro @Pedro a varivel display não existe, não faz parte do código citado acima, ou então o código esta simplesmente todo errado.
Comment: então ele está todo errado :(
Answer: Ao usar:
display = 'none'

você está atribuindo o valor 'none' a display, o que não vai funcionar
O correto seria comparar usando:
display == 'none'

Ainda assim você estaria comparando somente o valor, e não o tipo, então eu recomendaria usar:
display === 'none'

Comment: mesmo assim não funciona o único formato que funcionou foi com =, com dois "=="  ou com três "===" da esse erro " Uncaught ReferenceError: display is not defined at HTMLButtonElement.addaluno", ps não alterei em nada o código.
Answer: " = " atribuição,
" == " igualdade,
" === " Estritamente igual.
display == 'none'
Comment: mesmo assim não funciona o único formato que funcionou foi com =, com dois "=="  ou com três "===" da esse erro " Uncaught ReferenceError: display is not defined at HTMLButtonElement.addaluno", ps não alterei em nada o código.

por que o meu else não funciona?


For $S = \{ \frac{4x}{x+1} | x \in \mathbb{R}, x \geq 1 \}$ bdd? g.l.b.S? l.u.b.S?

Question: Let $S = \{ \frac{4x}{x+1} | x \in \mathbb{R}, x \geq 1 \}$
Is S bounded? Find g.l.b. S and the l.u.b. S if they exist. Give justification, formal proof not necessary. (Based on Calculus)
I did not justify my answers for this, but i knew the glb S = 2
and lub S = DNE.
I also said based off calculus that because 4x is faster than x+1 that it is unbounded above.
Comment: Can you find a point $x\geq 1$ where $\frac{4x}{x+1}\geq 5$?
Comment: (Also, a related hint: what is $\lim_{x\to\infty}\frac{4x}{x+1}$?  I think you'll find that it is not, in fact, unbounded above.  An even more explicit hint: since $x$ is positive, $\frac{4x}{x+1}\leq \frac{4x}{x+1}+\frac{4}{x+1}$.  Can you find a way to simplify the RHS there?)
Comment: @StevenStadnicki $\lim_{x\to\infty}\frac{4x}{x+1}=4$
Answer: You can write $\frac{4x}{x+1}=\frac{4}{1+\frac{1}{x}}$, then on the interval $[0,\infty)$, the set $S$ is bounded below by zero and bounded above by four.


Derive which values $P(A\cap B \cap C)$ can take, using only the axioms of probability

Question: For three events $A, B, C$ we know that $P(A\cap B) = 0.4, P(A \cap C)=0.5 \text{ and } P(B\cap C)=0.6$
(a) Derive which values $P(A\cap B \cap C)$ can take, with a clear explanation. Show in every step which axiom you use. You can only make use of the following axioms:

$P(A)\geq 0$
$P(S)=1$
$P(A_1\cup A_2 \cup \dots)=\sum\limits_{i=1}^\infty A_i, \text{ } \forall i\neq j$

(b) Let $D=(A\cap B^c \cap C^c) \cup (A^c\cap B \cap C^c) \cup (A^c\cap B^c \cap C)$. Which are the values that $P(D)$ can take? Give a clear explanation of your derivations.

What I attempted so far
(a)
I came this far: $A\cap B=(A\cap B \cap C) \cup (A\cap B \cap C^c)$ (these sets are disjoint). Hence $P(A\cap B \cap C) \leq P(A\cap B) = 0.4$, by axioms 3 and 2, since $P(A\cap B \cap C^c)\geq 0$.
By making a Venn-diagram I figured out that the lower boundary should probably be $0.25$, as this is $0.4+0.5+0.6-1=0.5$ (which is everything that should be in some intersection because the total probability cannot be greater than one) devided by $2$ (because the $0.5$ can be split over two intersections). However, I am not sure how to show this using the axioms provided. Could anyone please help?
(b) I think I will need the result from a. I am however not at all sure yet what I should do to solve this question. Any help would be appreciated.
Answer: Here's a way to formalize your Venn diagram argument.
Let $X=(A\cap B)\cup(A\cap C)\cup(B\cap C)$, and let $Y=A\cap B\cap C$. Then $X$ is the disjoint union of the sets $Y$, $X_{AB}=(A\cap B)\setminus Y$, $X_{AC}=(A\cap C)\setminus Y$, and $X_{BC}=(B\cap C)\setminus Y$. Note that $A\cap B$ is the disjoint union of $X_{AB}$ and $Y$, so $0.4=P(A\cap B)=P(X_{AB})+P(Y)$, and $P(X_{AB})=0.4-P(Y)$. Similarly, $P(X_{AC})=0.5-P(Y)$ and $P(X_{BC})=0.6-P(Y)$. Thus,
$$\begin{align*}
P(X)&=P(X_{AB})+P(X_{AC})+P(X_{BC})+P(X)\\
&=(0.4-P(Y))+(0.5-P(Y))+(0.6-P(Y))+P(Y)\\
&=1.5-2P(Y)\;,
\end{align*}$$
or $P(Y)=\frac12(1.5-P(X))\ge\frac12(1.5-1.0)=0.25$, since $P(X)\le 1$.
To do a really thorough job on (a), for each $p\in[0.25,0.4]$ you should demonstrate that it's possible to arrange $A,B$, and $C$ so that $P(Y)=p$. I would at least draw Venn diagrams illustrating the two extremes.
For (d), note that $D=(A\cup B\cup C)\setminus X$, where $X$ is as above: it's the set of points belonging to exactly one of the sets $A,B$, and $C$. Thus,
$$P(D)=P(A\cup B\cup C)-P(X)=P(A\cup B\cup C)-1.5+2P(Y)\;.$$
Bearing in mind that $P(A\cup B\cup C)\le 1$, what can you say about the possible range of values of $P(D)$? Again, you should check to be sure that the apparent extremes are actually possible.
Comment: @rbm: Looks good to me. You're welcome!
Comment: Wow, what a great answer! Thank you very much for your great effort! To answer your last question, I think that using the fact that $P(A\cup B \cup C)\leq 1$ gives me the inequality $P(D)\leq 0.3$ (since using the other inequality that can be obtained using the range for $P(Y)$ gives contradicting inequality signs I think, and would thus not give you a definite inequality). Am I right?


Drop duplicates based on a column, if another column does not contains a certain text in pandas

Question: I wanted to drop duplicates based on column id and if it does not contain the word us in either country 1 or country 2. How can I achieve this.
ID  country1  country2    status
1.   us,yt      au,in,sg     monetize
1.   tr,hk      ds,gh        block
2.    ju        te,yu,us     block
2.    ju        te,yu        block

Expected output
ID  country1.  country2.    status
1.   us,yt      au,in,sg     monetize
2.    ju        te,yu,us     block

Comment: What have you tried so far?
Comment: @ChrisLoonam #df = df.query("~(df['country1'].str.contains('US', na=False) | ~(df['country2'].str.contains('US', na=False)").drop_duplicates('id', keep='first').  Do u have a better solution????
Answer: Try:
df["key"]=df["country1"].str.contains("us")| df["country2"].str.contains("us")
df=df.sort_values("key", ascending=False).drop_duplicates(subset="ID", keep="first").drop(columns=["key"])

Outputs:
   ID country1  country2    status
0  1.    us,yt  au,in,sg  monetize
2  2.       ju  te,yu,us     block

Comment: I am not sure if this is dropping duplicates based on column ID
Comment: I tweaked my answer, have a look now


Can And Object Be Controlled By Multiple Classes? (and how to stop this happening)

Question: I have a Point object that holds coordinates, I then use that Point in the creation of two other objects, a Triangle and a Circle, then inside circle object I translate that point. It also translates the point in the triangle class. Why is this? Have I just set up two variables to access the same object rather than have a 'copy' of that object in both shapes? How can I amend this?
I create the point in the main class then pass that point onto the constructors of both the Circle and Triangle classes which then assign it to a property of that class.
So it's like this:
//main class
Point p = new Point(50,50);
Circle c = new Circle(p);
Triangle t = new Triangle(p);

c.translate(20,30); //also translates the triangles point

//Circle class
public Circle(Point p) {
    this.p = p;
}

//Triangle class
public Triangle(Point p) {
    this.p = p;
}

Comment: and what is the exact your problem with that?
Comment: As long as your Point is immutable, I think it is actually a good idea that the same Point is shared by all classes as much as possible. That is good memory economy.
Answer: Yes, you passed two references to the same Point object to Circle and Triangle.
To avoid this, there are basically two solutions:

create a copy of the Point object (either before passing it to Triangle and Circle, or in the constructor of those two classes, to make sure they use a different instances)
make the Point class immutable (all fields final, no setter), to make sure nobody can ever modify a Point. To translate a point, you would then be forced to create a new Point, with new coordinates. This is much safer, because you can't forget to make a copy. The immutability guarantees that the point can be shared between shapes without any way for them to modify each other by modifying their points.
Comment: Thanks, I'll have to copy the object, I'm following a strict spec >.>
Answer: The constructors for both your Circle and Triangle classes just assign the Point they are given to a data member. In this way, you're storing a reference to the same object, and every time it's manipulated, it will effect all references to it.
A safer way of handling such situations is, as you suggested, to copy the object passed to the constructor. E.g.:
//Circle class
public Circle(Point p) {
    this.p = new Point(p.getX(), p.getY());
}

Alternatively, if you defined Point as clonable:
//Circle class
public Circle(Point p) {
    this.p = p.clone();
}

Comment: Thanks, I've heard cloning objects should be avoided though?
Comment: `clone()` has odd semantics, true. Personally, I try to avoid it, but some frameworks/projects employ it. I guess it's a matter of style.
Answer: Your making one instance of the Point object and making references to that one Point object in the Circle and Triangle object instances. The translate method modifies that Point object.


Why the content of a block created in an external module does not appear?

Question: I am creating a module for wich i need to create a block with php code. I`m making it as follow:
<code>function my_modulo_block_info() {
   $blocks = array();
   $blocks['start'] = array(
      'title' => 'Start',
      'info' => t('The start block'),
      'status' => TRUE,
      'region' => 'content',
   );
   return $blocks;
}

function my_modulo_block_view($delta='') {
   $block = array();
   switch($delta) {
      case 'start' :
         $block['content'] = '<?php echo "Hello world"; ?>';
         break;
   }
   return $block;
}
</code>
But i see only the block name on the page, it dont print Hello world. Any body know why?
Comment: Do you actually want `` or do you want 'Hello World' to display?  If you want the php, I am wondering if it is in your html but you don't see it in the browser because of the `<>`  maybe try using `<` and `>`  or if you do just want 'Hello World' then change the line to `$block['content'] = 'Hello world';`
Comment: I really need the php code, "Hello world" is only an example for undeerstand. Wath are < and > ?
Comment: They are character codes [link](https://dev.w3.org/html5/html-author/charref).  `<` = `<` and `>` = `>`  You might also use the php function highlight_string() [link](http://php.net/manual/en/function.highlight-string.php)
Comment: That is not the problem, it seems that the block does not recognize php code. I do not know how to define the block that recognizes php code, just like full html and plain text format on configure block pages.
Comment: Sorry, I don't understand what you mean by "recognizes php code."  What to you actually want to see in the browser?  The `$block['content']` variable is for the HTML content you want to display.
Comment: Let's see how I explain myself better
When a block is created through the drupal interface, the name, description, body and text format are written. This way you can choose the format to "php code" and write php code in the body of the block. I need to do the same but using the hooks that provides drupal to work with blocks. Do you understand me now?
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/58625/discussion-between-dyn-and-r-leurquin).
Comment: Ignoring the fact that you should never ever use the php filter for a second - its intended use is when you _can't_ do it properly in PHP. Since your block is coded, it makes no sense at all to make its content php. PHP won't randomly execute a string, you would theoretically need to run that code through `check_markup` with the php format to make that happen. But definitely don't do that, just execute the PHP
Answer: call a php function to built block-content, in hook_view code should be:
<code>//construct your output as a function
$block['content'] = myfunctionname(); // this function is called 3 lines below
....
return $block;
//then call your output content function
function myfunctionname() {
$output = 'whatever you want(arrays, functions, html, more php, ....)'
 };
 return $output;
</code>
that will return $output as your content.
Comment: It's preferable to return a render array as the content, but this is the right idea


Evaluate $I=\int^1_0\frac{\ln(1+x)\ln(1+x^3)}{x}\mathrm{d}x$

Question: Question
$$I=\int^1_0\frac{\ln(1+x)\ln(1+x^3)}{x}\mathrm{d}x$$
My approach so far
Let
$$f(z)=\frac{\ln(1+z)\ln(1+z^3)}{z},\ I=\int^1_0f(z)\ \mathrm{d}z$$The main idea is to integrate $f(z)$ along three paths and obtain an algebraic equation with $I$.
The first path is simply the interval $[-1,1]$. Since the contributions from the indentations around the branch points tend to $0$, we may change the path to $e^{\pi i[0,1]}$.
\begin{align}
\int^1_{-1}f(z)\ \mathrm{d}z
&=I-\int^1_0\frac{\ln(1-x)\ln(1-x^3)}{x}\mathrm{d}x\\
&=\mathrm{Im}\int^\pi_0\mathrm{Log}(1+e^{i\theta})\mathrm{Log}(1+e^{3i\theta})\ \mathrm{d}\theta\\
&=\frac{3}{2}\int^\frac{\pi}{3}_0\theta\ln\left(2\cos\frac{\theta}{2}\right)\mathrm{d}\theta+\frac{1}{2}\int^\frac{\pi}{3}_0\theta\ln\left(2\cos\frac{3\theta}{2}\right)\mathrm{d}\theta+\int^\pi_{\frac{\pi}{3}}\left(\frac{3}{2}\theta-\pi\right)\ln\left(2\cos\frac{\theta}{2}\right)\mathrm{d}\theta
\end{align}The second path:
\begin{align}
\mathrm{Re}\int_{e^{\pi i/3}[0,1]}f(z)\ \mathrm{d}z
&=\mathrm{Re}\int^1_0\frac{\ln(1+xe^{\pi i/3})\ln(1-x^3)}{x}\mathrm{d}x\\
&=\frac{1}{2}\int^1_0\frac{\ln(1+x+x^2)\ln(1-x^3)}{x}\mathrm{d}x\\
&=\frac{\zeta(3)}{3}-\frac{1}{2}\int^1_0\frac{\ln(1-x)\ln(1-x^3)}{x}\mathrm{d}x\\
&=\frac{\zeta(3)}{3}+\frac{1}{2}\int^1_{-1}f(z)\ \mathrm{d}z-\frac{1}{2}I
\end{align}
The third path:
\begin{align}
\mathrm{Re}\int_{e^{\pi i[1/3,0]}}f(z)\ \mathrm{d}z
&=\mathrm{Im}\int^\frac{\pi}{3}_0\mathrm{Log}(1+e^{i\theta})\mathrm{Log}(1+e^{3i\theta})\ \mathrm{d}\theta\\
&=\frac{3}{2}\int^\frac{\pi}{3}_0\theta\ln\left(2\cos\frac{\theta}{2}\right)\mathrm{d}\theta+\frac{1}{2}\int^\frac{\pi}{3}_0\theta\ln\left(2\cos\frac{3\theta}{2}\right)\mathrm{d}\theta
\end{align}-
Comment: Very similar integral [here](https://math.stackexchange.com/questions/3294203/is-there-a-closed-form-solution-for-sum-n-1-infty-sum-m-1-infty-fr) ($x$ is negated in the log arguments)
Comment: The link posted by @user170231 involves $\sum H_n/n^2 x^n$, which is related to the integral $\int x \ln(\cos x) dx$.
Answer: Let $\gamma=[0,1]\cup e^{\pi i[0,1/3]}\cup e^{\pi i/3}[1,0]$. By Cauchy's integral theorem,
$$\int_\gamma f(z)\ \mathrm{d}z=0$$Therefore,
$$I=\frac{2}{9}\zeta(3)+\color{red}{\frac{3}{2}\int^\frac{\pi}{3}_0\theta\ln\left(2\cos\frac{\theta}{2}\right)\mathrm{d}\theta}+\color{blue}{\frac{1}{2}\int^\frac{\pi}{3}_0\theta\ln\left(2\cos\frac{3\theta}{2}\right)\mathrm{d}\theta}+\color{green}{\frac{1}{3}\int^\pi_{\frac{\pi}{3}}\left(\frac{3}{2}\theta-\pi\right)\ln\left(2\cos\frac{\theta}{2}\right)\mathrm{d}\theta}$$The red integral:
\begin{align}
\color{red}{\frac{3}{2}\int^\frac{\pi}{3}_0\theta\ln\left(2\cos\frac{\theta}{2}\right)\mathrm{d}\theta}
&=-\frac{3}{2}\mathrm{Re}\int^{e^{\pi i/3}}_1\frac{\ln{z}\ln(1+z)}{z}\mathrm{d}z\\
&=-\frac{3}{2}\mathrm{Re}\left[\mathrm{Li}_3(-z)-\mathrm{Li}_2(-z)\ln{z}\phantom{\frac{}{}}\right]^{e^{\pi i/3}}_1\\
&\color{red}{=-\frac{9}{8}\zeta(3)-\frac{3}{2}\mathrm{Cl}_3\left(\frac{2\pi}{3}\right)+\frac{\pi}{2}\mathrm{Cl}_2\left(\frac{2\pi}{3}\right)}\\
\end{align}The blue integral:
\begin{align}
\color{blue}{\frac{1}{2}\int^\frac{\pi}{3}_0\theta\ln\left(2\cos\frac{3\theta}{2}\right)\mathrm{d}\theta}
&=\frac{1}{18}\mathrm{Re}\int^1_{-1}\frac{\ln{z}\ln(1+z)}{z}\mathrm{d}z\\
&=\frac{1}{18}\mathrm{Re}\left[\mathrm{Li}_3(-z)-\mathrm{Li}_2(-z)\ln{z}\phantom{\frac{}{}}\right]^1_{-1}\\
&\color{blue}{=-\frac{7}{72}\zeta(3)}
\end{align}The green integral:
\begin{align}
\color{green}{\frac{1}{3}\int^\pi_{\frac{\pi}{3}}\left(\frac{3}{2}\theta-\pi\right)\ln\left(2\cos\frac{\theta}{2}\right)\mathrm{d}\theta}
&=2\mathrm{Re}\int^\frac{\pi}{2}_\frac{\pi}{6}\theta\ln(1+e^{2i\theta})\ \mathrm{d}\theta-\frac{2\pi}{3}\mathrm{Re}\int^\frac{\pi}{2}_\frac{\pi}{6}\ln(1+e^{2i\theta})\ \mathrm{d}\theta\\
&=\frac{1}{2}\mathrm{Re}\int^{e^{\pi i/3}}_{-1}\frac{\ln{z}\ln(1+z)}{z}\mathrm{d}z+\frac{\pi}{3}\mathrm{Im}\int^{e^{\pi i/3}}_{-1}\frac{\ln(1+z)}{z}\mathrm{d}z\\
&=\frac{1}{2}\mathrm{Re}\left[\mathrm{Li}_3(-z)-\mathrm{Li}_2(-z)\ln{z}\phantom{\frac{}{}}\right]^{e^{\pi i/3}}_{-1}-\frac{\pi}{3}\mathrm{Im}\ \mathrm{Li}_2(-e^{\pi i/3})\\
&\color{green}{=-\frac{1}{2}\zeta(3)+\frac{1}{2}\mathrm{Cl}_3\left(\frac{2\pi}{3}\right)+\frac{\pi}{6}\mathrm{Cl}_2\left(\frac{2\pi}{3}\right)}
\end{align}Finally,
$$I=\int^1_0\frac{\ln(1+x)\ln(1+x^3)}{x}\mathrm{d}x=\boxed{\displaystyle-\frac{3}{2}\zeta(3)-\mathrm{Cl}_3\left(\frac{2\pi}{3}\right)+\frac{2\pi}{3}\mathrm{Cl}_2\left(\frac{2\pi}{3}\right)}$$
Comment: +1 This is really cool. Congrats on your first answer :D


Stop nginx processing further rules

Question: I am using nginx to  proxy a directory to a remote server, with the code:
location /directory/ {
    proxy_set_header   X-Real-IP $remote_addr;
    proxy_set_header   Host      sub.domain.io;
    proxy_pass         http://sub.domain.io:80/;
}

However, various static files like CSS break due to other rules I have after this.
Is there a way I can end the processing once matched to this directory? In the same way you can use last for rewrites.
Here is the full config:
root /var/www/site;
autoindex off;
index index.php;
charset utf-8;
log_not_found off;
access_log /var/www/site/data/logs/access.log;
error_log /var/www/site/data/logs/error.log;

add_header X-debug-message "$geoip_country_code" always;

location ~ \.php$
{
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php7.2-fpm.sock;
}

location ~ "^/(de|es|fr)*$" {
    set $lang "$1/";
    set $page 'homepage';
    if ($http_accept_encoding !~ gzip) {
        rewrite ^/(.*)$ /index.php?request=/ last;
    }
    try_files /data/cache/html/$lang$page.html.gz @php;
    add_header  Content-Encoding  gzip;
    gzip off;
    default_type text/html;
}

location /directory/ {
    proxy_set_header   X-Real-IP $remote_addr;
    proxy_set_header   Host      sub.domain.io;
    proxy_pass         http://sub.domain.io:80/;
}

if ($allowed_country = no) {
    return 444;
}

location /
{
    try_files $uri @main_cache;
}

location @main_cache {
    if ($http_accept_encoding !~ gzip) {
        rewrite ^/(.*)$ /index.php?request=$1 last;
    }
    if ( $query_string ) {
            rewrite ^/(.*)$ /index.php?request=$1 last;
    }
    try_files /data/cache/html$uri.html.gz @php;
    add_header  Content-Encoding  gzip;
    gzip off;
    default_type text/html;
}

location @php {
    rewrite ^/(.+)$ /index.php?request=$1 last;
}

location /data/cache/pred
{
    try_files $uri $uri/ =404;
    if ( !-e $request_filename )
   {
            rewrite /cache/ps/(.*)$ /index.php?request=get&pin=$1 last;
            break;
    }
}

location ~* \.(eot|ico|jpe?g|png|svg|ttf|woff|woff2)$
{
        gzip_static on;
        gzip_vary on;
        expires 30d;
        add_header Cache-Control "public";
}

location ~* \.(css|js)$
{
        gzip_static on;
        gzip_vary on;
        expires 7d;
        add_header Cache-Control "public";
}

location ~ ^/(src|cron|tpl)
{
        return 301 $scheme://$server_name;
}

The request ends up as a 404 on the source server. It only ends up like that for the file formats listed in the penultimate two blocks.
Answer: The answer is in nginx location directive documentation.
A short version applied to your situation:
nginx first sees /directory as a candidate when processing the URL. It remembers this match, and then tries to look for regular expression matches.
If a suitable regular expression location is found, nginx will apply that location rules. If a match is not found, nginx will use the remembered /directory location.
In your case, regular expression blocks match some of the URIs inside /directory. When you want to prevent it, you can use the following block:
location ^~ /directory/ {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header Host sub.example.com;
    proxy_pass http://sub.example.com:80/;
}

Stop nginx processing further rules


Prove identity in law for stochastic process driven by Brownian Motion

Question: Let $B = (B_t)_{t\geq 0}$ be a standard brownian motion started at $0$. Consider the two following stochastic equations:
\begin{equation}
\begin{split}
dX_t &=& (13 + 2X_t)\,dt + (6 + X_t)\,dB_t \\
dY_t &=& 2Y_t\,dt + Y_t\,dB_t
\end{split}
\end{equation}
with $X_0 = Y_0 = 1$.
I am trying to show that the following identity in law holds:
$$
X_t - Y_t\left(1 + 6\int_0^t\frac{1}{Y_s}\,dB_s \right) \stackrel{law}{=} 7\int_0^tY_s\,ds
$$
Combining $X$ and $Y$, it can be shown through Ito's formula that the solution for $X$ is given by
$$
X_t = Y_t\left(1 + 7\int_0^t\frac{1}{Y_s}\,ds + 6\int_0^t\frac{1}{Y_s}\,dB_s \right)
$$
But I am having trouble operating with the first equation to work out the law identity, and the solution for $X$ is not really helping me. Any hint is most welcome, as I am a bit lost now. I suspect the solution might not be trivial.
Comment: So, basically your claim boils down to $$Y_t \int_0^t \frac{1}{Y_s} \, ds \stackrel{\text{law}}{=} \int_0^t Y_s \, ds, $$ right?
Comment: yes, with a 7 multiplying the integral on the left of your identity also. Maybe now applying integration by parts?
Answer: Note that the solution of the SDE, $\mathrm dY_t = 2Y_t\mathrm dt + \mathrm dB_t\ (\mbox{for }Y_0 = 1)$, is a collection of log-normal random variables,
$$
Y_t = e^{\frac{3}{2}t + B_t}~(\mbox{for }t\geqslant 0)\,.
$$
Therefore, for $0\leqslant s\leqslant t$,
$$
\left\{\frac{Y_t}{Y_s}\right\}_{0\leqslant s\leqslant t}\quad \stackrel{\text{law}}{=}\quad \left\{Y_{s}\right\}_{0\leqslant s\leqslant t}\,.\tag{1}
$$
proof:

For $n\in\mathbb{N}$ and $0\leqslant t_1<t_2<\ldots<t_n\leqslant t$, the time-reversal properties of Brownian motion justify the following:

$
\,\,\,P\left(\frac{Y_t}{Y_{t_1}}\leqslant y_1,\ \ldots,\ \frac{Y_t}{Y_{t_n}}\leqslant y_n\right)\\
\begin{eqnarray*}
&=& P\left(\frac{3}{2}(t-t_1) + B_t - B_{t_1}\leqslant \log y_1,\ \ldots,\ \frac{3}{2}(t-t_n) + B_t - B_{t_n}\leqslant \log y_n \right) \\
&=& P\left( B_t - B_{t_1}\leqslant \log y_1 - \frac{3}{2}(t-t_1),\ \ldots,\ B_t - B_{t_n}\leqslant \log y_n - \frac{3}{2}(t-t_n) \right) \\
&=& P\left( -(B_{t-r_1}-B_t)\leqslant \log y_1 - \frac{3}{2}r_1,\ \ldots,\ -(B_{t-r_n}-B_t)\leqslant \log y_n - \frac{3}{2}r_n \right) \\
&=& P\left( B_{t-r_1}-B_t\leqslant \log y_1 - \frac{3}{2}r_1, \ldots, B_{t-r_n}-B_t\leqslant \log y_n - \frac{3}{2}r_n \right) \\
&=& P\left( B_{r_1}\leqslant \log y_1 - \frac{3}{2}r_1,\ \ldots,\ B_{r_n}\leqslant \log y_n - \frac{3}{2}r_n \right) \\
&=& P\left( \frac{3}{2}r_1 + B_{r_1}\leqslant \log y_1,\ \ldots,\ \frac{3}{2}r_n + B_{r_n}\leqslant \log y_n \right) \\
&=& P\left(Y_{r_1}\leqslant y_1,\ \ldots,\ Y_{r_n}\leqslant y_n\right),
\end{eqnarray*}
$

where we defined $r_i:=t-t_i\ .$

The equality in law, $(1)$, implies
$$
\int_0^t \frac{Y_t}{Y_s} \, ds \stackrel{\text{law}}{=} \int_0^t Y_s \, ds\,,
$$
which, from your application of Ito's lemma and as deduced by @saz, is the relationship to be proved.


20k records are coming from database select query then in foreach loop its hang

Question: I am facing an issue is, i have to select a record from database with specific condition (where status=0), after that if around 20k rows are coming from select query then i added foreach loop to apply some conditions and on condition true i update the status of every fetched row from 0 to 1 and 1 to 2 and so on...
My problem is when large amount of data is coming from database then this process is hang and service stopped.
Please guide me what else i can do on place of foreach...if..else etc...
Comment: Create Shell Script for background jobs! https://book.cakephp.org/3.0/en/console-and-shells.html#
Comment: Thank for reply, but can you please give me single example because i am not familiar with this. Please @Salines
Comment: Idea: Have you considered batch processing? using `limit` to only load say 100 records at a time?
Comment: yes i applied shell_exec(command to update records). but i dont thing so that only doing so foreach loop headache will reduce...
Comment: Also added array_chunk on final array which is storing records from database select query, around 20k records, so i used array_chunk(2000), is it fine? or there should be more better way to do so
Answer: <code>Use hash insted of foreach

// Common Usage:
$users = [
    ['id' => 1, 'name' => 'mark'],
    ['id' => 2, 'name' => 'jane'],
    ['id' => 3, 'name' => 'sally'],
    ['id' => 4, 'name' => 'jose'],
];
$results = Hash::extract($users, '{n}.id');
// $results equals:
// [1,2,3,4];
</code>
Comment: Thanks for your response, here is my code which process i am using is:
if (count($mediaFilesDetails) > 0) {
foreach(array_chunk($mediaFilesDetails, 1000) as $media) {
                   foreach ($media as $key => $imgDetail) {
                     // Query Part to update some data...
                   }
}
}

will you please elaborate how should i proceed...
Comment: please review above foreach loop and let me know how can i reduce its loading time by applying any method because around 10k data is coming so i created 10 chunks of 1000 chunk.
Comment: I am explaining my task deeply is:
1. I have to fetch columns with status 0 (It may be 0 or around 10k...).
2. On resultant array i applied foreach with array chunk of 1000, after that added another foreach loop to use array with key. as mentioned above comment.


Simple node.js app deployment on DigitalOcean from GitHub

Question: I have a node.js application on my Github. Right now I am using Heroku for hosting it but I want to give DigitialOcean a try (the $5/month is more affordable).
I am used to using Heroku, where I just go create an app > connect it to my github account > deploy from the master branch > boom app deployed.
When I signed up for DO and started exploring it seemed way too much and too many steps to get my app deployed. I researched around to find a simpler way (similar to one I follow in Heroku) but all the blogs and YouTube videos go through the same tedious process.
I know I am being lazy but I just need a few clicks app deployment. Does anyone know a better (smarter) way I can deploy my app on DO from Github?
Comment: There's no way to 100% administrate a DigitalOcean server from the browser. If you're not willing to learn how to do stuff from the Linux command line, it's not the right service for you. Not that there's anything wrong with that - it's why Heroku exists :p
Comment: I should mention however that DigitalOcean's [tutorials site](https://www.digitalocean.com/community/tutorials) is excellent, if you do want to learn how to do it yourself :)
Comment: Thanks. I think I will give it a try before I come to any conclusion. I will at least put some efforts in learning. From your experience is DO better than Heroku? Price wise and service wise.
Comment: I don't think one is better than the other, it's just a trade off - DigitalOcean costs less and gives you more control over the server, but you have to manage stuff like updates and deployments yourself, whereas Heroku is more expensive, but handles all of that stuff for you. I'd definitely recommend giving DO a try (my site is hosted on there, and I've had really good experiences with them), but there's zero shame in going back to Heroku if you decide it's not for you :)
Answer: It will not be as easy with Heroku. It is always tempting to use cheaper services like Digital Ocean or Vultr and pay only fraction of the price (especially using coupon links that can make it free for months - Digital Ocean, Vultr) but having your own VPS means that you need to manage it yourself. Simplifying that process is what you pay for when you're using Heroku. But it doesn't have to be that bad.
Here is a good tutorial on how to do it:

https://www.distelli.com/docs/tutorials/build-and-deploy-nodejs-to-digitalocean/

And see this list of tutorials - search for those with "deploy" in the title:

https://www.digitalocean.com/community/tags/node-js?type=tutorials

Basically you have few options that I would consider here:

A semi-manual deploy with git - You can install a git server on your VPS and push to it whenever you want to deploy a new version
Automatic deploy with git - You can add a deployment process to you CI scripts that will do what you do manually in (1) but after all tests pass
You can trigger a pull from git on the server with ssh or a custom API
You can do (3) in your CI scripts
You can add a custom webhook in GitHub to notify your server about new version and your server may then pull the code and restart
You can add a custom webhook in CI and do the same as in (5)
Comment: Thanks for the pointers. I will go through the tutorials and see if it makes sense to deploy my app there. What is your personal opinion on DO? For a professional app deployment which one is better?


Newton's root finding method that copes with stationary points

Question: I am using Newton's method to solve an equation of the form $y=f(x)$ for increasing values of $y$. The value of $x$ found for some $y$ is used for the next $y$ as a starting approximation and this works fine.
$f$ is increasing but may have stationary points, and I do have situations where the range of interest of $y$ starts or ends on an extremum or very close. This causes the algorithm to experience a division by zero or yield very inaccurate roots.
Is there a simple way to cope ? Is there a known modified Newton's method able to deal with this situation ?
I know that double roots can be handled by the modified iterations $$x\leftarrow x-2\frac{f(x)}{f'(x)}$$ but this still does not work at the root, and one needs to know when to activate the factor $2$.

For information, my function $f$ is a cubic polynomial, but I want to avoid the explicit computation of the roots by Cardano's formulas.

Update:
If we restate Newton's method at a stationary point, we get to the next term of Taylor's development,
$$f(x+h)-y\approx f(x)-y+\frac{h^2}2f''(x),$$
so that $$h\approx\sqrt{-\frac{f(x)-y}{f''(x)}}.$$
In fact, the approximation
$$f(x+h)-y\approx f(x)-y+h f'(x)+\frac{h^2}2f''(x)$$ always holds, giving the general formula
$$h\approx \frac{f'(x)\pm\sqrt{f'^2(x)-2f''(x)(f(x)-y)}}{f''(x)}.$$
Due to the increased complexity, I don't want to use that formula all the time.
Comment: Assuming $f(x)= ax^3+bx^2+cx+d$, you know $f'(x)$ and $f''(x)$ and the roots of $f'(x)$. When $x$ approaches the roots of $f'(x)$, could you use l'hopital's rule and switch to $f'(x)/f''(x)$?
Comment: @PierreCarre: come on, in the interval of interest.
Comment: @PierreCarre: good point.
Comment: Incidentally, there' s an old but pretty good book, _Numerical Recipes_, that covers rootfinding in detail including various alternatives to Newton. You might be particularly interested in https://en.wikipedia.org/wiki/Brent%27s_method .
Comment: @StevenStadnicki: of course. I need very fast convergence (at most two iterations), otherwise the cost of the iterations might outweigh that of Cardano's approach.
Answer: There is an easy modification called modified Newton's method. The idea is easy: every time the derivative is zero, one uses a value of the derivative from the last iteration, when it was nonzero (couple of times if needed). This changes the method to the secant kind of method for these couple of iterations. When it becomes nonzero again, one switches back to Newton's method. In more dimensions it works as well.
Additional thing, which you can always try in case of convergence problems, is the damped version of Newton's method. It means, that you reduce each increment by some fixed value smaller than $1$, for example by $0.9$.
Can you post the function you solve and your starting point?
Comment: Thanks. But what when you *start* the iterations at a minimum ? The functions are any cubic in a monotonic section, possibly starting or ending on an extremum. If you want a case, $-x^3+3x$ from $(-1,-2)$.
Comment: Interesting. Then you have to start from a different point. (Do you need to find one solution or all solutions?) You can try to generate starting points randomly in the solved domain and run Newton's method from these points unless you are successful.
Comment: Or you can try to examine functional value in more points (equidistantly spaced) and as a starting point choose the one, in which the value is closest to zero. Then you get a starting point of higher quality.
Comment: Yes, this is an option. In fact, for my application it is more natural to process by increasing $y$ and this is why I would prefer to have a solution that starts from the starting point.
Answer: If I understood correctly, the basic step is to solve the equation $f(x)-y=0$, for given $y$. If we are unsure of the multiplicity of a root, we can apply the modified Newton's method, which corresponds to the application of the usual Newton's method to $g(x)=\frac{f(x)-y}{f'(x)}$. This way, the quadratic convergence is recovered, at least in exact arithmetic. The iteration would be
$$
x_{n+1} = x_n-\dfrac{\frac{f(x_n)-y}{f'(x_n)}}{\frac{f'(x_n)^2 - (f(x_n)-y)f''(x_n)}{f'(x_n)^2} } = x_n - \dfrac{f'(x_n)(f(x_n)-y)}{f'(x_n)^2-f''(x_n)(f(x_n)-y)}
$$
If, by any chance, $f'(x_0)=0$, just move it  a bit.
Comment: You could probably get away with setting $f'(x_0)$ to $ε$ instead of evaluating $f'(x_0+ε)$ to save a few cpu cycles.
Comment: $f'(x_0)=0$ (as well as $f'(x_0)\approx0$) is the topic of my question.
Comment: @YvesDaoust I understand. I'm just saying that using this method $f'(x_0)\approx 0$ does not pose a problem.
Comment: With $f'(x_0)=0$, the iterations don't start.
Comment: @YvesDaoust That is why I proposed that "If, by any chance $f'(x_0)=0$, just move it a bit". It would be part of the algorithm to check if $f'(x_0)=0$ and act accordingly.
Comment: I implemented it in Mathematica and it works fine.
Comment: If you want my question is about "how precisely can I move it a bit". When is $f'(x_0)$ considered negligible, and what to do exactly, in a way that blends with the normal case.
Comment: In my implementation, when $f'(x_0)=0$, I just moved $x_0$ by $\varepsilon>0$, where $\varepsilon$  was the tolerance used for Newton iterations. I suppose that better criteria can be obtained, but this one gets the work done. If $x_0$ is an extreme point in the interval, you can make it specifically move right or left. I also tried cases where $f'(x_0) = f''(x_0) = 0$.
Answer: Momentum-based algorithms are good at passing through stationary points while retaining fast convergence.
$$m_i=(1-\beta)f'(x_i)+\beta m_{i-1}=m_{i-1}-(1-\beta)(m_{i-1}-f'(x_i))$$
$$x_{i+1}=x_i-(1-\beta^i)\frac{f(x_i)}{m_i}$$
The $1-\beta^i$ factor serves as bias correction, supposing one takes $m_0=0$, since we get $m_i=(1-\beta^i)f'(x_i)$ if $x_i$ is fixed.
As $\beta\to0$, you get Newton's method and faster convergence, while for larger $\beta$ you will get better "resilience" against stationary points.
For your purposes, you know that $f'(x)\ge0$, so rather than setting $m_0=0$, you may want to initialize it to a small positive value, or perhaps even use the same $m_i$ sequence for every $y$, since it is likely you will converge to the solution for $y=f(x)$ for a given $y$ while $m_i$ is sufficiently large that starting from where it left off works well for the next $y$.
If you go with the latter approach, you'll want to choose $\beta$ based on the density of your $y$ around the stationary points. If $\beta$ is too small and you have many $y$ near a stationary point, then $m_i$ will decay rapidly, which leaves you with the original issue.


Is there a portable way to copy a block of memory in C#?

Question: If you want to do a memory copy between two arrays, there's an Array.Copy function for that in .NET:
char[] GetCopy(char[] buf)
{
    char[] result = new char[buf.Length];
    Array.Copy(buf, result);
    return result;
}

This is usually faster than manually for-looping to copy all the characters in buf to result, because it's a block copy operation that simply takes a chunk of memory and writes it to the destination.
Similarly, if I was instead given a char* and an int specifying its size, what are my options? Here are the ones I've considered:

Buffer.BlockCopy: requires src and dst to be arrays
Buffer.MemoryCopy: exactly what I'm looking for, but only available on .NET Desktop
Marshal.Copy: stopped being supported in .NET 2.0

Or, if there's no alternative, is there some kind of way to construct an array from a pointer char* and a length int? If I could do that, I could just convert the pointers to arrays and pass them into Array.Copy.
I'm not looking for for-loops because as I said they're not very efficient compared to block copies, but if that's the only way I guess that would have to do.
TL;DR: I'm basically looking for memcpy(), but in C# and can be used in PCLs.
Comment: I have no idea, but since copying memory is limited by memory speed and CPU I'd not expect manual loop to be slower than CPU specific block copy. Note by the way that post is asking for equivalent of `memcpy` that does not necessary compile into block copy instructions... Consider to do your own benchmark . You can find more info about copying in similar questions like http://stackoverflow.com/questions/2658380/how-can-i-copy-unmanaged-data-in-c-sharp-and-how-fast-is-it and http://stackoverflow.com/questions/4707012/c-memcpy-vs-stdcopy).
Comment: The assertion that Marshal.Copy() "stopped being supported" is nonsense.  It is alive and well in all .NET versions through 4.6, even available in PCL and WinRT apps.  And the obvious solution to this non-existing problem.
Comment: Have you actually measured how much slower basic unsafe manual memory copy (similar to [Buffer.MemoryCopy](http://referencesource.microsoft.com/#mscorlib/system/buffer.cs,c2ca91c0d34a8f86) ) is? Since there are no runtime checks and resulting code is tiny there should be not much difference compared to block move operations (and really `memcpy` is frequently just manual loop too).
Comment: @AlexeiLevenkov No, but shouldn't a block-based one be faster? I'm not asking this because I'm dissatisfied with manual for-looping; I'm just curious to know if there's a better way.
Answer: You state that Marshal.Copy would not be supported any longer, however on the documentation of the Marshal class i can find no indication for that.
Quite the contrary, the class is available for the following framework versions: 4.6, 4.5, 4, 3.5, 3.0, 2.0, 1.1
One possible implementation of a utility function based on this method would be:
public static void CopyFromPtrToPtr(IntPtr src, uint srcLen,
                                    IntPtr dst, uint dstLen)
{
    var buffer = new byte[srcLen];
    Marshal.Copy(src, buffer, 0, buffer.Length);
    Marshal.Copy(buffer, 0, dst, (int)Math.Min(buffer.Length, dstLen));
}

However, it is quite possible, that copying the bytes from IntPtr to byte[] and back again negates any possible performance gain over pinning the unsafe memory and copying it in a loop.
Depending on how portable the code needs to be, you could also consider using P/Invoke to actually use the memcpy method. This should work well on Windows 2000 and onwards (all systems that have the Microsoft Visual C Run-Time Library installed).
[DllImport("msvcrt.dll", EntryPoint = "memcpy", CallingConvention = CallingConvention.Cdecl, SetLastError = false)]
static extern IntPtr memcpy(IntPtr dst, IntPtr src, UIntPtr count);

Edit: The second approach would not be suited for portable class libraries, the first however would be.
Answer: I don't recall what built-in APIs the BCL has but you can copy the BCL memcpy code and use it. Use Reflector and search for "memcpy" to find it. Unsafe code is perfectly defined and portable.


Get videos in Android app using Facebook Graph API

Question: For a high school project, I need to get a list of uploaded videos on a Facebook page inside my own Android app.
Facebook SDK suggests the following code for this:
<code>/* make the API call */
new Request(
session,
"/{page-id}/videos/uploaded",
null,
HttpMethod.GET,
new Request.Callback() {
    public void onCompleted(Response response) {
        /* handle the result */
    }
}
).executeAsync();
</code>
I have inserted the ID of my page in the Request.
The problem is that I need to supply an Access token. Using the Graph Api Explorer I can browse the output of the query supplying my access token on their side. How do I supply the access token inside the Java code?
The response I am getting is this one:
<code>{Response:  responseCode: 400, graphObject: null, error: {HttpStatus: 400, errorCode: 104,       errorType: OAuthException, errorMessage: An access token is required to request this resource.}, isFromCache:false}
</code>
Can you please help me out how to supply the access token to the request
Answer: An AccesToken is obtained through Facebook Login Service, when a user is logged in, Facebook generates one. You should take a look at
https://github.com/sromku/android-simple-facebook
It is a library that simplifies common Facebook API tasks (such as login user).


Cannot produce (sing) any sound higher than #C5

Question: I'm a male hobbyist singer, probably somwhere between baritone and tenor.
I cannot seem to produce any sound above a #C5. I'm not talking about singing in full voice, just to squeak out anything, falsetto, headvoice, whistle, flageolet. Not on any vowel, not in lip rolls, hum, ng-sound, nothing. It seems like there is an absolutely hard ceiling there. If I look at youtube videos like this one:

 it seems that one should be able to produce notes above #C5 at least in a quiet manner.

Here the guy is going to a bB5!! I can speak in a "mickey mouse tone", apparently that's falsetto, but that will be in the range around F4 to bB4. So maybe I cannot pass my second bridge?
Any tips on what I could practice to at least be able to silently squeak out those notes? I think if I can get the basic vocal coordination down, I can practice to have a fuller tone with vowels etc.
Comment: Is #C5 the C# above Middle C or the C# above the C above Middle C? I've seen conflicting standards regarding this, and I'd like to know which standard you use.
Comment: If middle C is C4 (like the marked key here: https://en.wikipedia.org/wiki/C_(musical_note)#/media/File:MiddleC-Keyboard.svg) then I mean C#5, so one octave + 1 semitone above middle C. Or 8th fret high E string on a guitar. I think it's the C# one semitone above tenor high C. Since tenors sing the high C in full voice, it should be possible to go much higher in falsetto, or am I wrong?
Answer: Though I'm now in my 60s & well past my prime for a good top-end, I was a pro session singer for many years in my youth.
I also had a hard-stop beyond which I could not sing. I could do the same note in full voice or in falsetto, but that was my brick wall top note.
Don't sweat it.
You might gain a tone or two if you're not yet fully warmed over a period of weeks not hours*, when you are well settled into your full capability, but don't ever push it.
*Don't consider mumbling along to the radio, or singing half an hour a day in the shower will ever fully warm your voice. This takes work.
Comment: Nope. Never did, ever. I can hit it in full voice or I can't hit it, switching voice gains nothing. Brick wall. I did used to have three & a half octaves of useful range, though I've lost a fair bit off the top end of that gradually over the past 20 years or so. Have a listen to someone like Elton John playing live recently - it happens to us all eventually. [If you want figures, I had D2 to A♯5, if I got my numbers right, nearly 2 octaves down from middle C & nearly 2 above it.]
Comment: So you simply had/have no flageolet register?


Advanced JavaScript RegExp Replacement Within HTML tags

Question: I have javascript code that works pretty well like:
var rgx = /MyName/g;
var curInnerHTML = document.body.innerHTML;
curInnerHTML = curInnerHTML.replace(rgx, "MyNameReplace");

The problem is that its matching the regex even in scenarios where it is contained within HTML attributes and what-not. How can I modify the regex so that it will only find it within the content of the HTML? For example, in this string

MyName

it currently results like (note the change in the title attribute):
        <div class="someclass" title="MyNameReplace</span">

    MyNameReplace

But I need it to be (leave the title attribute untouched):

MyNameReplace

Comment: Obligatory http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags
Comment: *"How can I modify the regex so that it will only find it within the content of the HTML?"* Reliably? You can't.
Answer: Your best bet, and it's a lot easier than it sounds, is not to try to use regex to parse HTML, but to take advantage of the fact that the DOM already has and recursively process the text nodes.
Here's an off-the-cuff:
// We use this div's `innerHTML` to parse the markup of each replacment
const div = document.createElement('div');

// This is the recursive-descent function that processes all text nodes
// within the element you give it and its descendants
function doReplacement(node, rex, text) {
    // What kind of node did we get?
    switch (node.nodeType) {
        case Node.ELEMENT_NODE:
            // Probably best to leave `script` elements alone.
            // You'll probably find you want to add to this list
            // (`object`, `applet`, `style`, ...)
            if (node.nodeName.toUpperCase() !== "SCRIPT") {
                // It's an element we want to process, start with its
                // *last* child and work forward, since part of what
                // we're doing inserts into the DOM.
                let sibling;
                for (const child = node.lastChild; child; child = sibling) {
                    // Before we change this node, grab a reference to the
                    // one that precedes it
                    sibling = child.previousSibling;

                    // Recurse
                    doReplacement(child, rex, text);
                }
            }
            break;
        case Node.TEXT_NODE:
            // A text node -- let's do our replacements!
            // The first two deal with the fact that the text node
            // may have less-than symbols or ampersands in it.
            // The third, of course, does your replacement.
            div.innerHTML = node.nodeValue
                                .replace(/&/g, "&")
                                .replace(/</g, "<")
                                .replace(rex, text);

            // Now, the `div` has real live DOM elements for the replacement.
            // Insert them in front of this text node...
            insertChildrenBefore(div, node);
            // ...and remove the text node.
            node.parentNode.removeChild(node);
            break;
    }
}

// This function just inserts all of the children of the given container
// in front of the given reference node.
function insertChildrenBefore(container, refNode) {
    let sibling;
    const parent = refNode.parentNode;
    for (const child = container.firstChild; child; child = sibling) {
        sibling = child.nextSibling;
        parent.insertBefore(child, refNode);
    }
}

Which you'd call like this:
doReplacement(
    document.body,
    /MyName/g,
    "MyNameReplace"
);

Live Example:

// We use this div's `innerHTML` to parse the markup of each replacment
const div = document.createElement('div');

// This is the recursive-descent function that processes all text nodes
// within the element you give it and its descendants
function doReplacement(node, rex, text) {
    // What kind of node did we get?
    switch (node.nodeType) {
        case Node.ELEMENT_NODE:
            // Probably best to leave `script` elements alone.
            // You'll probably find you want to add to this list
            // (`object`, `applet`, `style`, ...)
            if (node.nodeName.toUpperCase() !== "SCRIPT") {
                // It's an element we want to process, start with its
                // *last* child and work forward, since part of what
                // we're doing inserts into the DOM.
                let sibling;
                for (let child = node.lastChild; child; child = sibling) {
                    // Before we change this node, grab a reference to the
                    // one that precedes it
                    sibling = child.previousSibling;

                    // Recurse
                    doReplacement(child, rex, text);
                }
            }
            break;
        case Node.TEXT_NODE:
            // A text node -- let's do our replacements!
            // The first two deal with the fact that the text node
            // may have less-than symbols or ampersands in it.
            // The third, of course, does your replacement.
            div.innerHTML = node.nodeValue
                                .replace(/&/g, "&")
                                .replace(/</g, "<")
                                .replace(rex, text);

            // Now, the `div` has real live DOM elements for the replacement.
            // Insert them in front of this text node...
            insertChildrenBefore(div, node);
            // ...and remove the text node.
            node.parentNode.removeChild(node);
            break;
    }
}

// This function just inserts all of the children of the given container
// in front of the given reference node.
function insertChildrenBefore(container, refNode) {
    let sibling;
    const parent = refNode.parentNode;
    for (let child = container.firstChild; child; child = sibling) {
        sibling = child.nextSibling;
        parent.insertBefore(child, refNode);
    }
}

setTimeout(() => {
    doReplacement(
        document.body,
        /MyName/g,
        "MyNameReplace"
    );
}, 800);

MyName

This is MyName in a sentence.

This is MyName nested

How 'bout making MyName nested more deeply

This is MyName in an element with < and & in it.


Difficulties with partial integration

Question: I have asked several questions on the site regarding this topic already, but I can't seem to grasp this at all. Consider the following example:
$$ h(x) = e^{2x} \sin x$$
We have to find the integral. I rewrote this to the form:
$$e^{2x} \sin x \space dx =  d( -\cos x e^{2x}) - (-\cos x \dfrac{1}{2} e^{2x} \space dx)$$
I continued this:
$$e^{2x} \sin x \space dx = d( -\cos x e^{2x}) - d (- \sin \space x \dfrac{1}{2} e^{2x}) - (- \sin x \dfrac{1}{4}e^{2x} \space dx)$$
I subtracted the last term with the term on the LHS:
$$\dfrac{3}{4} (e^{2x} \sin x) \space dx = d( -\cos x e^{2x}) - d (- \sin \space x \dfrac{1}{2} e^{2x})$$
Apparently this is totally wrong but I have no idea what I did wrong or how it should be done otherwise. Can anyone help me find my errors? And perhaps give some tips?
Comment: When you say "this it totally wrong", what exactly do you mean? You look like you have the right terms there but with some incorrect coefficients. I'll post an answer shortly.
Comment: See my related answer [here](http://math.stackexchange.com/a/155769/28900). I also discuss standard usage of the "$d$" notation, which you seem to use differently.
Comment: you have mixed up the functions. At the beginning you should have either $e^{2x} \sin x dx=d(-\cos x e^{2x}) -(-2 e^{2x} \cos x dx)$ or $e^{2x} \sin x dx=d(\sin x e^{2x}/2)- (\cos x e^{2x}/2 dx)$
Answer:
I've never properly learned the notations with du and dx and dy/dx
  and such. Does du mean u'?

If you have a function $u(x)$ of the single variable $x$, the differential $du$ can be seen as the product of the derivative of $u(x)$ with the differential $dx$ of the independent variable, i.e. $du=u'(x)\ dx$.
For a detailed explanation of the notation see this answer.
--
The integration by parts corresponds to the following rule:
$$
\begin{equation*}
\int u(x)v^{\prime }(x)\ dx=u(x)v(x)-\int u^{\prime }(x)v(x)\ dx.
\end{equation*}
$$
We can select the functions $u(x),v(x)$ by using the LIATE rule as in my answer to your second last question or the techniques explained in the answers to your last question LIATE / ILATE rule. We get$^1$:
$$\int e^{2x}\sin x\,dx=\frac{1}{2}e^{2x}\sin x-\int \frac{1}{2}e^{2x}\cos
x\,dx$$
and
$$\int \frac{1}{2}e^{2x}\cos x\,dx=\frac{1}{4}e^{2x}\cos x+\frac{1}{4}\int
e^{2x}\sin x\,dx.$$
Consequently,
$$\begin{eqnarray*}
I &=&\int e^{2x}\sin x\,dx=\frac{1}{2}e^{2x}\sin x-\int \frac{1}{2}
e^{2x}\cos x\,dx \\
&=&\frac{1}{2}e^{2x}\sin x-\frac{1}{4}e^{2x}\cos x-\frac{1}{4}\int
e^{2x}\sin x\,dx \\
&=&\frac{1}{2}e^{2x}\sin x-\frac{1}{4}e^{2x}\cos x-\frac{1}{4}I.
\end{eqnarray*}
$$
Solving for $I$ we thus get
$$
\begin{eqnarray*}
\left( 1+\frac{1}{4}\right) I &=&\frac{1}{2}e^{2x}\sin x-\frac{1}{4}
e^{2x}\cos x \\
I &=&\frac{4}{5}\left( \frac{1}{2}\sin x-\frac{1}{4}\cos x\right) e^{2x}.
\end{eqnarray*}
$$
--
$^1$ The first integral can be evaluated as follows.  If $u(x)=\sin x$ and $v^{\prime }(x)=e^{2x}$, then $u^{\prime }(x)=\cos x$
and $v(x)=\frac{1}{2}e^{2x}$. The integration by parts yields
$$\int \underset{u(x)}{\underbrace{\sin x}}\,\cdot\underset{v^{\prime }(x)}{\underbrace{e^{2x}}}\ dx=\underset{u(x)}{\underbrace{\sin x}}\,\cdot\underset{v(x)}{\underbrace{\frac{1}{2}e^{2x}}}-\int \underset{u^{\prime }(x)}{\underbrace{\cos x}}\cdot\underset{v(x)}{\,\underbrace{\frac{1}{2}e^{2x}}}\ dx.$$
Remark. As can be seen in AWertheim's answer the opposite selection $u(x)=e^{2x}$ and $v^{\prime }(x)=\sin x$ works too.
Comment: Why isn't it $\int \dfrac{1}{2} e^{2x} - \cos x dx$
Comment: @tomtit If $u(x)=\sin x$ and $v^{\prime }(x)=e^{2x}$, then $u^{\prime }(x)=\cos x$
and $v(x)=\frac{1}{2}e^{2x}$. The integration by parts yields

$$\int \underset{u(x)}{\underbrace{\sin x}}\,\underset{v^{\prime }(x)}{\underbrace{e^{2x}}}dx=\underset{u(x)}{\underbrace{\sin x}}\,\underset{v(x)}{\underbrace{\frac{1}{2}e^{2x}}}-\int \underset{u^{\prime }(x)}{\underbrace{\cos x}}\underset{v(x)}{\,\underbrace{\frac{1}{2}e^{2x}}}dx.$$
Comment: @tomtit ... Basically the derivative of $\sin x$ is $\cos x$ and not $-\cos x$.
Comment: Wait.. I have gotten this all wrong. I taught you had to take the antiderivative...
Comment: @tomtit With the selection I made ($u(x)=\sin x$ and $v'(x)=e^{2x}$) I have to differentiate $\sin x$ and integrate $e^{2x}$. See my edit too.
Comment: I'm sorry for asking so many questions, but I've never properly learned the notations with du and dx and dy/dx and such. Does du mean u'?
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/9049/discussion-between-americo-tavares-and-tomtit)
Comment: Thanks, you've been a tremendous help. The notation is what made it so tough for me. You've cleared it up!
Comment: @tomtit Glad to help!
Answer: Let $P=\int e^{ax}\cos(bx)dx$ and $Q=\int e^{ax}\sin(bx)dx$
 $$P+iQ=\int e^{ax}\cdot e^{ibx}dx=\int e^{(a+ib)x}dx$$
$$P+iQ=\frac{1}{a+ib}e^{(a+ib)x}+C=\frac{ae^{ax}\cos bx+be^{ax}\sin bx +i(ae^{ax}\sin bx -be^{ax}\cos bx)}{a^{2}+b^{2}}+C$$
$$P=\frac{e^{ax}(a\cos bx+b\sin bx)}{a^{2}+b^{2}}+C$$
$$Q=\frac{e^{ax}(a\sin bx-b\cos bx )}{a^{2}+b^{2}}+C$$
In the given question a=2 and b=1.
$$\int e^{2x}\sin x\textrm{ d}x=\frac{1}{5}(-e^{2x}\cos x + 2e^{2x}\sin x) + C$$
Answer: We apply repeated integration by parts, making sure to be careful with the terms.
Let $u = e^{2x}$ and $dv = \sin x dx$. Then $du = 2e^{2x}$ and $v = -\cos x$, and we see:
$$\int e^{2x}\sin x dx = -e^{2x}\cos x + 2\int e^{2x}\cos x dx$$
We apply integration by parts again here on the integral on the right hand side.
Let $u = e^{2x}$ and $dv = \cos x dx$. Then $du = 2e^{2x}$ and $v = \sin x$, and we see:
$$\int e^{2x}\sin x dx = -e^{2x}\cos x + 2[e^{2x}\sin x - 2\int e^{2x}\sin x dx]$$
Rearranging carefully, we see:
$$5\int e^{2x}\sin x dx = -e^{2x}\cos x + 2e^{2x}\sin x$$
or
$$\int e^{2x}\sin x dx = \frac{1}{5}[-e^{2x}\cos x + 2e^{2x}\sin x] + C$$
accounting for an appropriate constant of integration.
Comment: I don't see where the 2 comes from
Comment: @tomtit, which 2 are you talking about? There are many here. If you're referring to differentiating $u$ with respect to $x$, then that's the chain rule: $\frac{d}{dx}e^{2x} = 2e^{2x}$.
Comment: I believe you did the opposite of what I did..
Comment: @tomtit yes, in the sense that I chose to differentiate $e^{2x}$ (i.e., I chose it as my $u$) and you chose to differentiate $\sin x$. However, it does not matter what you pick to be $u$ and $v$, i.e., if you go through the method I've outlined here and choose $u = \sin x$ and $dv = e^{2x}dx$, you will get the same thing.
Answer: Your instructor/book is using non-traditional notation.
What students usually find easy is to proceed as follows, using the mnemonic
$$\int u\,dv=uv-\int v\,du.$$
Let $u=e^{2x}$ and let $dv=\sin x\,dx$. Then $du=2e^{2x}\,dx$ and $v=-\cos x$. It is helpful to put this in a little table, like
$$\begin{align}
&u=e^{2x} \qquad &dv= \sin x\,dx\\
&du=2e^{2x}\,dx  &v=-\cos x
\end{align}
$$
Our integral is then
$$-e^{2x}\cos x+\int 2e^{2x}\cos x\,dx.$$
Now continue as in the answer to your previous question.
Comment: It is not overkill, it is the absolutely standard notation for the integral. In principle the $dx$ could be dispensed with, sort of. You will not find a respectable introduction to calculus that does that.
Comment: The Leibniz notation can serve as a useful mnemonic for calculations. And yes, there have been many attempts, partly successful. Lagrange helped popularize $f'$. The problem with introducing a new notation is that there are two possibilities (i) no one much will pay attention, and then your students will have difficulty communicating or, even worse (ii) the notation will get some popularity, and then we will be saddled with one more notation.
Comment: I already feared that I had to deviate from the book's method. What I already don't understand is why your last answer has an integral sign and a dx. Isn't that an overkill? Aren't those for the same purpose?
Comment: Hmm, that's clear. Just a question: Has there ever been a **serious** attempt to change the notation of calculus to something 'better'? Because Leibniz' method seems to me very, very bad. I have never encountered anything like it in math, and it is the only reason I thoroughly dislike calculus (unlike for example linear algebra)
Comment: By the way, does the instructor call it partial integration? Everyone else (in English) calls it integration by parts.
Comment: I live in the Netherlands, here it is called 'partieel integreren', so I assumed it would be called partial integration (just like partial derivatives)
Comment: @tomtit If you go to the Wikipedia and search for the English version of the entry [Partiële integratie](http://nl.wikipedia.org/wiki/Parti%C3%ABle_integratie) you find [Integration by parts](http://en.wikipedia.org/wiki/Integration_by_parts).
Answer: Here is how I approach this rather confusing topic, with a slightly different notation.
Let's define down as $f^\downarrow =f'$ and up as $f^\uparrow=\int f$ and
similarly double down as
$f^{\downarrow\downarrow} =f''$ and  double up as $f^{\uparrow\uparrow}=\int\int f$  and so on.
Now to do one round of  integration by parts use
$\int f g = f g^{\uparrow} - \int (f^\downarrow g^\uparrow)$
To do two rounds use
$\int f g =f g^{\uparrow} - f^\downarrow g^{\uparrow\uparrow}+ \int (f^{\downarrow\downarrow} g^{\uparrow\uparrow})$
in simple applications $f$ is a polynomial so its down is a simpler polynomial.
You notice in each term the number of up moves is one more than down moves.
Also in the first and last integrals the number of ups and downs are equal, and the integral itself counts as one up.
To do three rounds use
$\int f g =f g^{\uparrow} - f^\downarrow g^{\uparrow\uparrow}+ f^{\downarrow\downarrow}g^{\uparrow\uparrow\uparrow}- \int (f^{\downarrow\downarrow\downarrow} g^{\uparrow\uparrow\uparrow})$.
For example to do $\int x^3 e^{2x}dx$ we notice that the fourth (and subsequent) derivatives of $x^3$ will be zero so we go that far and get a convenient zero in the last integral
$\int x^3 e^{2x} = (x^3) (e^{2x})^{\uparrow} -(x^3)^\downarrow (e^{2x})^{\uparrow\uparrow}+ (x^3)^{\downarrow\downarrow}(e^{2x})^{\uparrow\uparrow\uparrow}-(x^3)^{\downarrow\downarrow\downarrow} (e^{2x})^{\uparrow\uparrow\uparrow\uparrow}+\int (x^3)^{\downarrow\downarrow\downarrow\downarrow} (e^{2x})^{\uparrow\uparrow\uparrow\uparrow}$
$\int x^3 e^{2x} =(x^3) (e^{2x}/2)-(3x^2)(e^{2x}/4)+(6x)(e^{2x}/8)-(6)(e^{2x}/16)+C$
Now, in your example you are dealing with a tricky integral where you go so far on the right until the integral looks like the original one, just differing by a constant multiple. At which point you stop and bring the right integral to left, hence completing the circle so to speak.  Here is how it goes: for cosine two rounds of either up or down brings us back to cosine so we use
$\int e^{ax} \cos bx = (e^{ax}) (\cos bx)^{\uparrow} - (e^{ax})^\downarrow (\cos bx)^{\uparrow\uparrow}+ \int (e^{ax})^{\downarrow\downarrow} (\cos bx)^{\uparrow\uparrow}$
$\int e^{ax} \cos bx = (e^{ax}) (\sin bx /b) - (a e^{ax}) (-\cos bx /b^2)+ \int (a^2e^{ax}) (-\cos bx /b^2)$
Now you bring the last integral to the left and factor it (postpone the constant to the last step)
$(1+a^2/b^2)\int e^{ax} \cos bx = 1/b e^{ax}\sin bx + a/b^2 e^{ax}\cos bx $
Now clean up to get
$\int e^{ax} \cos bx = e^{ax}(b\sin bx + a \cos bx)/(a^2+b^2) +C $

Difficulties with partial integration


Matrix of endomorphism in different basis

Question: Let $E$ be a vector space, with $\dim E = n$.
Let $u$ be an endomorphism of $E$ and $B = (b_1, \dots, b_n)$, $C = (c_1, \dots, c_n)$ be two basis of $E$.
Let $\operatorname{Mat}_{BC}(u)$ denote the matrix of $(u(b_1), \dots, u(b_n))$ in basis $C$.
Here is my question: if we introduce $B', C'$ two basis of $E$, is this formula right ?
$$\operatorname{Mat}_{B'C'}(u) = \left(\operatorname{Mat}_{C'C}(\operatorname{Id}_E)\right)^{-1}\operatorname{Mat}_{BC}(u)\operatorname{Mat}_{B'B}(\operatorname{Id}_E)$$
Secondly, if this is correct, any explanation or interpretation would be greatly appreciated.
Comment: Looks fine to me, this is the change of basis formula foe matrices.
Answer: Yes, your formula is correct although it is usually written differently. Let me introduce some notation which will make the formula look more natural. Given an $n$-dimensional vector space $E$ and an ordered basis $B = (b_1, \dots, b_n)$ for $E$, any vector $v \in E$ can be written uniquely as $v = v_1 b_1 + \dots + v_n b_n$ where $v_i \in \mathbb{F}$ are called the compomenets of the vector $v$ with respect to the basis $B$. Set
$$ [v]_B = \begin{pmatrix} v_1 \\ \vdots \\ v_n \end{pmatrix}. $$
That is, $[v]_B$ is a column vector which contains the components of the vector $v$ with respect to the basis $B$.
Now, let's assume $E,F$ are vector spaces, $B = (b_1, \dots, b_n)$ is a basis for $E$ and $C = (c_1, \dots, c_m)$ is a basis for $F$. Given a linear map $T \colon E \rightarrow F$, there is a unique $m \times n$ matrix denoted by $[T]^B_C$ (you should read it as the matrix representing $T$ with respect to the basis $B$ in the domain and the basis $C$ in the codomain) which satisfies
$$ [Tv]_C = [T]^B_C \cdot [v]_B $$
for all $v \in V$. On the right we have the matrix multiplication of the $m \times n$ matrix $[T]^B_C$ by the column $n \times 1$ vector $[v]_B$ so we get a $m \times 1$ column vector which contains the components of $Tv$ with respect to the basis $C$. The way to remember this formula (which is essentially the definition of $[u]_C^B$) is to note that the $B$'s cancel out as in:
$$ \require{cancel} [Tv]_C = [T]^{\cancel{B}}_C \cdot [v]_{\cancel{B}}. $$
Now, let's say we have another linear map $S \colon F \rightarrow G$ and a basis $D = (d_1, \dots, d_l)$ for $G$. The fact that matrix multiplication corresponds to composition of linear maps can be written as
$$ \require{cancel} [S \circ T]^B_D = [S]_D^{\cancel{C}} \cdot [T]_{\cancel{C}}^B $$
where again, on the right you have matrix multiplication and on the left you have the matrix representing the composition.
In particular, if $E = F$ and $T$ is invertible, then by taking $S = T^{-1}$ we get
$$ \require{cancel}  I_n = [\operatorname{Id}_E]_B^B = [T^{-1} \circ T]^B_B = [T^{-1}]_B^{\cancel{C}} \cdot [T]_{\cancel{C}}^B $$
and so
$$ [T^{-1}]_B^{C} = \left( [T]_{C}^B \right)^{-1}. $$

The relation between the notation I described and your notation is that $\operatorname{Mat}_{BC}(u) = [u]^B_C$. Translating your formula to my notation, we get
$$ [u]^{B'}_{C'} = \left( [\operatorname{Id}_E]^{C'}_{C} \right)^{-1} \cdot [u]^B_C \cdot [\operatorname{Id}_E]^{B'}_B = [\operatorname{Id}_E^{-1} ]^{C}_{C'}  \cdot [u]^B_C \cdot [\operatorname{Id}_E]^{B'}_B = [\operatorname{Id}_E ]^{\cancel{C}}_{C'}  \cdot [u]^{\cancel{B}}_{\cancel{C}} \cdot [\operatorname{Id}_E]^{B'}_{\cancel{B}} $$
so your formula is just an expression of the fact that matrix multiplication corresponds to composition.


What else could we do, instead of solving the congruences?

Question: I want to find the p-adic expansion of $\frac{1}{p}$ and $\frac{1}{p^r}$ in the field $\mathbb{Q}_p$.
So, do I have to solve the congruences $px \equiv 1 \pmod {p^n}, p^r x \equiv 1 \pmod { p^n }, \forall n \in \mathbb{N} $, respectively?
But.. these congruences do not have solutions, right?
What else could we do, in order to find the p-adic expansion of $\frac{1}{p}$ and $\frac{1}{p^r}$ in $\mathbb{Q}_p$ ?
Answer: In short, $\frac{1}{p^n}$ is its own $p$-adic expansion in $\mathbb{Q}_p$.
The congruence $px\equiv 1\mod p^n$ is equivalent to solving $$px-p^ny=1$$ for $x,y\in\mathbb{Z}$. This is impossible because it would imply that $p\mid 1$.
The $p$-adic expansion of a number $n$ looks like a Laurent series in $p$ with coefficients in $\mathbb{Z}/(p\mathbb{Z})$. So we have $$\frac{1}{p}=1\cdot p^{-1}+0+0\cdot p+0\cdot p^2+\ldots$$
Another way of seeing it is that every non-zero element of $\mathbb{Q}_p$ can be represented uniquely as $p^{n}z$ where $n\in\mathbb{Z}$ and $z\in(\mathbb{Z}_p)^{\times}$. The unit $z$ can be expanded as a $p$-adic integer series and then shifted $n$ units to the right or left by $p^{n}$.
Proof:
First, I prove that it is possible to represent elements of $\mathbb{Q}_p$ in the form mentioned above. Let $0\neq q\in\mathbb{Q}_p$. Now define $z:=q\cdot\vert q\vert_p$. Calculating the norm of $z$ shows that it is a unit in $\mathbb{Z}_p$: $$\vert z\vert_p=\left\vert q\vert q\vert_p\right\vert_p=\left\vert qp^{-\nu_p(q)}\right\vert_p=\vert q\vert_p\cdot \left\vert p^{-\nu_p(q)}\right\vert_p=p^{-\nu_p(q)}\cdot p^{\nu_p(q)}=1.$$ This gives $q=\vert q\vert_p^{-1}z$. Where $\vert\cdot\vert_p$ is the $p$-adic norm and $\nu_p(\cdot)$ is the $p$-adic valuation.
Second, I prove that there is only one such way to represent a given $p$-adic number. Let $p^nx=p^my$ with $m,n\in\mathbb{Z}$ and $x,y$ units in $\mathbb{Z}_p$. Then $p^{n-m}=yx^{-1}$. The right hand side shows that $p^{n-m}$ is a unit, so $m=n$ and $1=yx^{-1}$. Thus $x=y$ as well.
Applying this to your question, observe that $p^{-n}=p^{-n}\cdot 1$ is already of this form and that the $p$-adic expansion of $1$ is $1+0\cdot p+0\cdot p^2+\ldots$

If you would like to have a better grasp of this topic, I highly recommend getting a copy of $p$-adic Numbers: An Introduction. There is also a good amount of content on wikipedia.
An analogy
In $\mathbb{C}$, every non-zero element can be represented in polar form $z=re^{i\theta}$. Where $\vert z\vert=r$ and $e^{i\theta}$ is an element of the unit circle. The "unit circle" in $\mathbb{Q}_p$ is in some sense the units of $\mathbb{Z}_p$. So writing $q=p^{\nu_p(q)}u$ (where $u$ is a unit of $\mathbb{Z}_p$) is analogous to having a polar form for $p$-adic numbers.
Comment: No, what is important is that $z$ is a unit. It doesn't have to represented as $q\vert q\vert_p$, but it is true that every unit can be represented like that. The form $p^nz$ is unique for non-zero $p$-adic numbers (i.e. there is one and only one way to write each number that way). The form $q\vert q\vert_p$ is not unique at all (there are infinitely many ways to write a unit in that way).
Comment: J. David Taylor Could you explain me what you do from "For existence..", till the end? :/
Comment: Why does $z=q \cdot |q|_p$ have norm $1$?
Comment: J.David Taylor I understand... Could you also explain me why $z$ is of the form $q \cdot |q|_p$ ?
Comment: It's the definition of that variable in the proof. I changed the post to clarify.
Comment: J.David Taylor So each time, we write an element of $\mathbb{Q}_p$ as $p^nz$, is $z$ of the form $q \cdot |q|_p$ ?
Comment: A ok!!! Is the p-adic expansion of $\frac{1}{p^n}$ equal to $1 \cdot p^{-n}+ 0 \cdot p^{-n+1}+ \dots+ 0 \cdot p^{0}+ 0 \cdot p+0 \cdot p^2+ \dots$ ?
Comment: Yes. Usually we omit the zero terms because they are unnecessary, and just write $\frac{1}{p^n}$.
Comment: As another analogy, the decimal expansion of $\frac{1}{10^3}$ is $0.00100000000\ldots$. Usually, we drop the sequence of never ending zeros and write $0.001$.


How to create a service for the class with constructor arguments from a vendor package class?

Question: I am trying to inject class from FFMpeg
in my custom service of a module.
But the class has two constructor arguments.
So how can I pass those arguments in my custom service.
my_module.services.yml
services:
  # FFMPEG Factory
  my_module.php_ffmpeg:
    class: FFMpeg\FFMpeg
    autowire: true

I understand that as there are two parameters in the costructor,
we need to pass two arguments in service definition
but the class doesn't have factory method.
So, what arguments should I pass?
Answer: Factory services are nothing more than classes that instantiate and return objects as an injectable (e.g. LoggerChannelFactory creates LoggerChannel instances as logger services). You can create a factory that instantiates FFMpeg\FFMpeg, makes it a service, and inject it to whatever needs it. This still fulfills dependency-injection duties. Your code won't be using FFMpeg directly but via the factory, and you can mock away the factory during testing.
// my_module/src/FFMpegFactory.php
class FFMpegFactory {
  public static function get() {
    $ffmpeg = /* instantiate driver */
    $ffprobe = /* instantiate probe */
    return new FFMpeg($ffmpeg, $ffprobe);
  }
}

// my_module/src/OtherService.php
class OtherService {
  public function __construct(FFMpeg $php_ffmpeg) {
    $this->ffmpeg = $php_ffmpeg;
  }
}

// my_module/my_module.services.yml
services:
  my_module.php_ffmpeg:
    class: 'FFMpeg\FFMpeg'
    factory: ['\Drupal\my_module\FFMpegFactory', 'get']
  my_module.other_service:
    class: '\Drupal\my_module\OtherService'
    arguments:
      - '@my_module.php_ffmpeg'

Answer: The constructor arguments for the class are FFMpegDriver $ffmpeg and  FFProbe $ffprobe. Those are the ones to inject. You must create those object instances as services also.
Alternatively you can create a custom factory to build the object.


How Does One Test IIS7's OrphanWorkerProcess (along with OrphanActionExe and OrphanActionParams)?

Question: What's a valid way to test IIS7's OrphanWorkerProcess settings are working?  I have a script and all the settings in the configuration for my application pool.  However, it seems just simply recycling the application pool does not do the trick.  I've even validated that the script is never attempted to load by using ProcessMon.
I'm basically trying to do something similar to this:
http://support.microsoft.com/kb/828222
Here's the IIS 7 reference page:
http://msdn.microsoft.com/en-us/library/bb386513(v=VS.90).aspx
I think the problem I'm having may be I was simply expecting the process to be orphaned when I recycled the application pool, but that doesn't work.  The reference says:

"Specifies whether to assign a worker process to an orphan state instead of terminating it when an application pool fails."

So maybe the real question is possibly:

How do I invoke a failure to see if the script I have set for the orphanActionExe is working?
Answer: Use Process Explorer from SysInternals. It has a feature to suspend a process allowing it to pause communication with WAS.
http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx
Answer: You need to make it fail communication with WAS somehow. If pinging is enabled, you could try attaching a debugger and pausing the process; haven't tried it.
It doesn't happen on regular recycles, just when a reactive recycling event is encountered.


exception if module does not exist

Question: Is it possible to do try exception (or something else) if a module exists or not?
I have a code as(all of them are defined, just not included here):
import matplotlib.pyplot as plt
import numpy as np

def scf:
    A = np.array(plist, dtype="float")
    np.savetxt("foo.dat", A,
                delimiter=' ', fmt="%1.4e")

    plt.plot(A[:, 0], A[:, 4], label="foo", linewidth="4.")
    plt.show()

It writes foo.dat and also plots it. What I am trying to achieve is:
def scf:
    A = np.array(plist, dtype="float")
    # if matplotlib does not exists, write to file
    np.savetxt("foo.dat", A,
                delimiter=' ', fmt="%1.4e")
    #else if matplotlib exists, show plot, dont write to file
    plt.plot(A[:, 0], A[:, 4], label="foo", linewidth="4.")
    plt.show()

Can I do that?
Comment: Look here ... http://stackoverflow.com/questions/14050281/how-to-check-if-a-python-module-exists-without-importing-it
Answer: Importing a module that does not exist will raise ImportError, which you can catch like any other exception with a try/except block.

exception if module does not exist


error term in nlme::lme function

Question: I cant seem to find this info anywhere. What do the different sides of the | in the lme or lmer (in lme4) functions represent?
i.e.,:
(1|ID) vs (Time|ID)

Essentially, why is the 1 to the left of the | and why is the ID to the right?
Thanks!
Answer: The terms to the left specify components of the design matrix (as they would in any model formula), so a 1 to the left specifies an intercept, and the Time to the left specifies an intercept and a single numeric Time predictor (assuming the variable Time is numeric)
The terms to the right specify how many of these components exist and where. (1|ID) says there is different intercept for each unique value of ID. The term (Time|ID) says there is a different intercept and a different slope for Time for each unique value of ID.
[If, for some reason, you wanted a different slope for each ID but not a different intercept, you would do (-1+Time|ID) to ask for the individual Time models not to have their own intercepts]

error term in nlme::lme function


Position of a point on a line segent relative to the segent's length

Question: I would like to ask for help with clarifying the following formula for calculation of relative position of a point on a line segment with respect to the line segment's length in two-dimensional Euclidean space:
$$t = \frac{(P-A)(B-A)}{\lVert B-A \rVert^2}$$
where P is a point of line segment AB and $t \in [0; 1]$.
This is a formula we have had in our OpenGL course but unfortunately our teacher skipped the explanation saing it is elementary.
I tried to derive the formula somehow from the standard Euclidean distance $t = \frac{\lVert P-A \rVert}{\lVert B-A \rVert}$ but I wasn't successful at all. The only other source I was able to find citing this formula was an old OpenGL on-line manual, however, it doesn't provide any explanation either. The formulas seem to be equivalent anyway.
Thank you.
Comment: A point on the line segment can be written in vector form as $P = A+t(B-A)$ where t is in [0,1]. If t = 0 you are at A and if t = 1 you are at B. Now dot product $(P-A) = t(B-A)$ with $(B-A)$ and you are done.
Comment: Thank you, I really didn't think of it that way. This was nice and clear and I would surely accept it as an answer.
Answer: $t$ is a scalar and can be defined as:
$$t=\frac{||P-A||}{||B-A||}$$
Since $P$ is on the line segment $AB$, the vectors $P-A$ and $B-A$ would be in the same direction and $(P-A).(B-A)$ = $||P-A||||B-A||$. Using this condition and by multiplying numerator and denominator by $||B-A||$ in defintion of $t$, we arrive at the formula.
Comment: Oh, I am sorry for my mistake that I originally told that $t = \frac{P-A}{||B-A||}$ - I really meant the formula you have written in the beginning of our answer.
I just must be missing something in the condition where you claim that $(P-A)\cdot(B-A) = ||P-A|| \cdot ||B-A||$. Could you please explain how can $(P-A)\cdot(B-A) = (x_p - x_a)(x_b - x_a) + (y_p - y_a)(y_b - y_a)$ be equal to $||P-A|| \cdot ||B-A|| = \sqrt{(x_p - x_a)^2 + (y_p - y_a)^2} \cdot \sqrt{(x_b - x_a)^2 + (y_b - y_a)^2}$?
Thank you.
Comment: $X.Y = ||X|||Y||cos(\theta)$ where $\theta$ is the angle between $X$ and $Y$. In case of $P-A$ and $B-A$, $\theta$ simply is zero because $P$ is on the line segment $AB$. Therefore, $$(P-A).(B-A) = ||P-A||B-A||cos(0) = ||P-A||B-A||$$
Comment: @Kyselejsyreček, in your way of representing scalar product, use the fact that $$\frac{x_p-x_a}{x_b-x_a}=\frac{y_p-y_a}{y_b-y_a} = t$$ where $t$ is in $[0,1]$.
Comment: These equations are awesome, thank you very much. :-)
I feel really stupid for not realizing such elementary facts.


calculate surface normal with random sampling of points

Question: Given a surface in $R^3$ and a point P on the surface, I want to calculate the surface normal in this point, the vector that is perpendicular to the surface.
However, I do not know the whole surface, but merely a random sampling of points on the surface.
How can I calculate a good approximation of the surface normal?
The surface is non-intersecting, smooth and roughly planar, if that matters
Answer:
Select some number of close points of P. Within some radius, or the K closest neighbors.
Fit a plane to those points using Linear least squares. Possibly weigh points closer to P higher, using Weighted least squares.
$$ a \cdot \left( x - x_0 \right) + b \cdot \left( y - y_0 \right) + c \cdot \left( z - z_0 \right) = 1 $$
$$ A X = B $$
$$ \hat X = \left( A^\intercal A \right)^{-1} A^\intercal B \\
   \textbf{or} \\
   \hat X = \left( A^\intercal W A \right)^{-1} A^\intercal W B $$
A has one row for each point, minus P.
B is column vector filled with ones.
X is the vector $ \begin{pmatrix} a & b & c \end{pmatrix}^\intercal $.
$ \hat X $ is the estimation of X.
W is a diagonal matrix with the weight of each point.
Calculate the normal of the plane. This is just the norm of X in the above equations.

Here are some papers on the subject:

Estimating Surface Normals in Noisy Point Cloud Data - Mitra, Nguyen (2003)
Normal Estimation for Point Clouds: A Comparison Study
for a Voronoi Based Method - Dey, Li, Sun (2005)
Comment: Thanks! This is essentially what I am trying to do, but simply fitting a plane seems like a very rough approximation. Is there some way I can use the relationships between the points, such as weighting points that are closer to P higher, or weighting points that are close to each other lower? I an make up some weighting scheme, but ideally I am looking for a method that is based on geometric principles


Filtrar datas utilizando WP_query e Post meta no Wordpress

Question: estou desenvolvendo uma categoria de eventos em meu template utilizando o post padrão, neste post adicionei dois campos (Metabox) para data inicial e data final do evento. Já no WP_query eu preciso exibir os eventos que possuam a data inicial menor que a data atual, e a data de finalização menor.
Utilizando WP_query ou get_post_meta, ou qualquer outra função... Como posso fazer isso?
Comment: Esta salvando a data como? Em que formato?
Comment: Formato da data: d/m/Y
Comment: Sinceramente esta é a pior forma de salvar, se salvar como Ymd fica tranquilo para fazer as consultas.
Comment: Sim, mas meu problema é como fazer a consulta, pois não sei.
Answer: No caso isso depende da forma que você salva a data... Eu recomendo usar o formato:
YmdHis

Desta forma pode fazer uma consulta bem simples comprando números apenas:
'meta_query' => array(
    array(
        'key' => 'seu_meta_key',
        'value' => array( 'data_atual', 'data_termino' ),
        'compare' => 'BETWEEN',
        'type' => 'NUMERIC'
    )
);

Também pode tentar usar o type como DATE, mas para fazer isso também vai ter que usar um formato de data como falei.
Para mais detalhes consulte documentação do uso do meta_query em WP_Query.


When does a UMP test fail to exist?

Question: I have a sample $X=(X_1, ...,X_n)\sim N(\mu,\sigma^2)$ with $\sigma^2$ known. The hypotheses are  $H_0: \mu=\mu_0, H_1:\mu \neq \mu_0$.
I know that in such a case an UMP test does not exist and so that I should proceed using a LR test, in order to find the rejection rule.
My professor also told me that for a sample distribution that belongs to the Exponential Family in the case of simple vs bilateral hypotheses an UMP test does not exist.
Thus, my question is theoretic: why does an UMP test does not exist in such cases? Which are the conditions under which an UMP test does not exist?
EDIT: I have found an example in which, instead, although the alternative hypothesis is bilateral, the UMP test exists.
A sample $X\sim U(0,\theta)$. The hypotheses are $H_0:\theta=\theta_0, H_1:\theta\neq \theta_0$.
Comment: Simply put, a UMP test does not exist because the critical regions turn out to be different for $\theta> \theta_0$ and $\theta<\theta_0$. This means that there are only UMP tests for one-sided hypotheses, where you may still use the NP lemma.
Comment: @Alessandro: it depends on how deep you want to dive into it. I think the paper is interesting to learn which conditions are needed and why
Comment: I thought you were interested in exponential densities. The uniform distribution does not belong to the exponential family so there is no general rule there.
Comment: @JohnK Ok, that's clear. But how can I apply this idea to the two examples above? How can I show that it is actually the case?
Comment: I am not familiar with a general proof. Perhaps you can work something out starting from the definition of an exponential density. My guess is that it would be non-trivial.
Comment: @JohnK Thus, in your opinion, it is enough to take those cases as given? Are there other cases in which we are sure a UMP test does not exist?
Comment: Maybe this can help: https://projecteuclid.org/euclid.aoms/1177728259
Comment: @fcop Which part in particular? Reading the abstract it seems not so pertinent
Comment: @Alessandro: you don't have to read it, but maybe you can Google 'Karlin rubin uniform power monotone likelihood' and then judge whether it is pertinent or not...
Comment: @fcop Ok thanks. Since you've linked a paper, I thought I was supposed to read through it
Comment: After your edit: you say that an UMPT exists, that could be but , what is your test statistic, what is the critical region ?
Comment: @Alessandro: I am not giving an idea but I am asking you a question: you say that an UMP test exists for your hypothesis and I ask you (a) what is the test statistic and (b) what is your critical region ? If you say that there exists an UMPT test, then you should be able to give me the test statistic and the critical region ?
Comment: @fcop I've uploaded the source of my example. It is Lehmann, 1986 p. 111. It is an exercise, so I do not have already the answers to your questions
Comment: @JohnK Sorry for the delay. I was interested in general to situations in which an UMP test exists and in those in which, instead, it does not exist.
So, in the case of exponential family and simple vs bilateral hypothesis, the UMP test does not exist as a rule?
Answer: In the example that you have provided, go on to calculate the likelihood ratio and you will find that it comes out to be a function of the order statistics, X(1) and X(2). Question 8.33 of Statistical Inference by George and Casella will help. The solution is provided in the link below:
http://www.ams.sunysb.edu/~zhu/ams570/Solutions-Casella-Berger.pdf
Coming back to the existence of a UMP test, Karlin Rubin Theorem tells that the MLR should exist, so that the inverse operation can be applied to get the test. The example on the link below will surely help.
http://web.eecs.umich.edu/~cscott/past_courses/eecs564w11/25_ump.pdf

When does a UMP test fail to exist?


Do sus chords exist in Locrian?

Question: I have recently been exploring chords in the Locrian mode. Down to the flattened 5th and 9th degrees, I have come up with some pretty bizarre sus chords. This got me thinking: Are such chords still recognised as sus chords, in spite of their altered degrees?
A couple of examples:
F sharp, G, C- Can this be described as an F sharp sus flat 2 flat 5?
F sharp, B, C- Can this be described as an F sharp sus 4 flat 5?
m3 V sharp 9
One chord that threw me off was this one: F sharp, A, C, B.
To me, this should be seen as F sharp diminished with an added 11. However, I have seen it described as F sharp sus 4 flat 5 , sharp 9. So, when does a m3 become a sharp 9? Or are both ways of naming this chord as valid as each other?
Answer: I think that rather than asking whether suspensions "exist" in locrian, you should ask: how do you want the suspensions to be heard?
With sus chords you often get a quartal rather than tertian harmonic feel. Essentially the sound of chords in stacked fourths. If that is what you're after, it seems straight forward. Use sus labels to get the stack of tones you want, and a non-tertian sound.
But, if you want the sound of a real suspension, a dissonant tone that resolves to a consonance, then I think you need to decide what things should be treated as dissonant and then use the suspensions accordingly to create dissonances to resolve. The thing that might make this tricky is the fact that the tonality is locrian. With the tonic chord being a diminished chord - a traditional dissonance - then locrian sort of turns the sense of consonance/dissonance upside down, or at least makes it unconventional. I don't mean to suggest it wouldn't work. It would just be unconventional and that's an opportunity to experiment.
Answer: Yes, if in context the chords are suspending notes in place of the third then it would make sense to call them suspensions. The actual chord labels will be a bit tricky, since the examples in the question have diminished fifths and minor seconds and any prospective symbol will have to make that explicit.
Also, in a tonality like Locrian, it can be easy to accidentally lead the listener to a different harmonic interpretation than was intended. So it's worth double-checking whether the music is actually being perceived in the way that the notation suggests.

I'll leave it to OP to sort out good chord symbols, but that last example "F sharp sus 4 flat 5 , sharp 9" is awful. It does technically describe the correct notes, but it obscures the quality needlessly - as written, it's saying "okay, F# major chord. Then suspend the 4th, and then flatten the fifth, and then add the sharp ninth", which is extremely misleading - that set of notes isn't going to be heard as an F# major chord at all, nor will it be heard as a suspension because the minor third is present, nor will the A be heard as #9 since there is no major third in the chord (you should really only be using #9 when the chord already has a major third, otherwise it's just the m3). "F#dim(11)", by contrast, is much better at describing the sound of the chord: "F# diminished chord, then add the 11th". See? Much better.
Comment: I think you make a good point about `dim` versus `♭5`. If the critical thing with locrian is the diminished tonic chord as _diatonic_, and to the extent that `♭5` shows an _alteration_ from a diatonic perfect fifth, then `dim` is the right choice. The locrian tonic is diatonically diminished, not an altered chord. Not altered like a dominant seventh flat five.
Answer: Any chord name that describes all of the notes in the chord is valid.  All the ones you have mentioned seem to instruct a musician to play the intended notes!

Do sus chords exist in Locrian?