Taking random items out of a container with replacement

Question: I take vitamins in the morning, but one of them I only take a half tablet.
So, I have an initial container with 100 full tablets, and every morning I take out a random tablet.  If it's a full tablet, I break it in half, put half back, and take half.  If it's a half tablet, I just take it.  Given that, how many days must I do this before I get a $> 50\%$ chance of getting a half tablet?  (Or, what's the % chance I get a half tablet after $X$ days?)
NB: This isn't homework; it just occurred to me as I was doing my morning routine, and I really have no idea where to start on trying to solve this.  Pointers welcome.  It feels like something with an infinite series, but I'm not sure.
Comment: Are you familiar with Polya's urn? It's a similar process, though not identical.
Comment: A few brief observations to get started: (**1**) Clearly if we start with $n$ tables, then after *exactly* $2n$ draws, there will be no tablets left; (**2**) The first time that you could possibly have $> 50\%$ chance is after $n/2$ draws and this happens with probability $\prod_{i=0}^{(n/2)-1} (1-\frac{i}{n})$; (cont.)
Comment: (cont.) (**3**) Let $(H_t,W_t)$ denote the ordered pair of half tablets and whole tablets after $t$ draws. Then, there are $\lceil(t+1)/2\rceil$ possibilities and they are $(2k,n-t/2-k)$ for $0 \leq k \leq t/2$ if $t$ is even and $(2k+1, n-(t+1)/2-k)$ for $0 \leq k \leq (t-1)/2$ if $t$ is odd. This works up to time $n$. After that the number of possibilities starts to shrink again, since there is the possibility we've already split all whole tablets.
Comment: Since the process $X_t = (H_t, W_t)$ is Markov (though *not* time homogeneous), and evolves according to a recombinant tree, then the probabilities of each outcome can be easily solved for recursively. I have not (yet) tried working out explicit solutions for each.
Comment: Note that until you draw a half-tablet: 1) there are always 100 items (= # tablets + # half-tablets) in the container, 2) Just before you make your $N^{th}$ draw, there are $N-1$ half-tablets in the container, one for each full tablet you've drawn so far and replaced with a half-tablet.
Answer: In a certain sense, the answer depends on how lazy you want to be.
If you are willing to do some very mild bookkeeping, then it is easy to calculate on any particular day the exact probability of select a half-tablet based on your previous draws. This is a form of conditional probability calculation. If you don't like to do any bookkeeping at all, then a marginal probability calculation can be obtained. The former gives a very simple expression, while the latter is more complicated. (This is the price you pay for additional laziness.)
A simple observation
Note that at any point in time, if we draw a whole tablet, then (i) the total number of tablets stays the same, (ii) the number of whole tablets decreases by one and (iii) the number of half-tablets increases by one.
Otherwise, if we draw a half-tablet, then the total number of tablets and the number of half-tablets both decrease by one, and the number of whole tablets stays the same.
Hence, knowing only the number of whole tablets chosen over the total number of days, we can calculate exactly how many half-tablets and whole tablets are left in the jar. Specifically, let $X_t$ be the number of whole tablets drawn up to time $t$ (inclusive). Then, the number of remaining whole tablets is $W_t = n - X_t$ and the number of half-tablets is $H_t = X_t - (t-X_t) = 2 X_t - t$. (The last quantity can be seen to arise from the $X_t$ half-tablets created by drawing each of the $X_t$ whole tablets and replacing them with a half-tablet minus the $t-X_t$ half-tablets we must have consumed.)
Conditional probability
Thus, by keeping track only of what day we are on and a running total of how many whole tablets we've drawn, we can find the conditional probability of drawing a half-tablet on day $t+1$ as
$$\renewcommand{\Pr}{\mathbb P}
\Pr( \text{draw half-tablet on day $t+1$} \mid (t,X_t) ) = \frac{H_t}{H_t+W_t} = \frac{2 X_t - t}{n - t + X_t} .
$$
So, by using very simple bookkeeping, we can calculate the probability of drawing a half-tablet on each day for each individual realization of this process. In particular, this allows us to determine exactly the first day on which we have greater than 50% chance of drawing a half-tablet.
Unconditional (marginal) probability
If we are too lazy to keep track of how many whole tablets we've drawn (or simply don't have a pen), then we can completely ignore the past and rely on marginal probabilities of drawing a half-tablet. From the above observation, it's apparent that $H_t$ follows a time-imhomogenous Markov process satisfying
$$
H_{t+1} =
\begin{cases}
H_t - 1 & \mathrm{w.p.}\; H_t / (H_t + W_t) \\
H_t + 1 & \mathrm{w.p.}\; W_t / (H_t + W_t)
\end{cases} \>.
$$
We can, therefore, use a simple recursion to calculate $\mathbb P(H_t = h)$ for each valid $h$. Some $R$ code to implement the recursion is found below.
Results for $n=100$
When we start with $n = 100$ tablets, then the first time that we have over a 50% chance of getting a half-tablet is at $t = 90$, i.e., after 90 tablets have already been drawn from the bottle (or in other words, on the 91st day). The probability is
$$\mathbb P(\text{half-tablet on 91st draw}) \approx 0.502571 \>.$$
Below is a graph of the probability of getting a half-tablet as a function of $t$.

Here is some very simple (and very inefficient!) $R$ code to calculate the probability of being in each state as a function of $t$. At the end is the calculation of the probability of drawing a half-tablet at each point in time.
<code># Eat-your-vitamins stochastic process
n <- 100
P <- matrix(0,n+1,2*n+1)

P[1,1] <- 1
for( t in 0:(2*n-1) )
{
    j <- t + 1
    offset <- 1 * (t %% 2 != 0)
    M <- min(t,2*n-t)

    for( h in seq(offset,M,by=2) )
    {
        i <- h + 1
        w <- n - (h+t)/2
        if( h > 0 )
            P[i-1,j+1] <- P[i-1,j+1] + P[i,j] * h / (h+w)
        if( w > 0 )
            P[i+1,j+1] <- P[i+1,j+1] + P[i,j] * w / (h+w)
    }
}

# Probability of getting a half-tablet as a function of time.
H <- matrix(0:n,nrow(P),ncol(P))
W <- n - H/2 - t(matrix(0:(ncol(P)-1),ncol(P),nrow(P)))/2
pr.half <- colSums( P*H/(H+W) )
</code>
Comment: (+1) excellent answer.  I like how it flattens out at step 198 to 199, then jumps up to 1 at 200 (which you can just pick out from your graph).
Comment: @G.JayKerns: Thanks. At one point several weeks ago when I was thinking about this more, I thought I had worked out the explicity probability at times $2n-1$ and $2n-2$. The discontinuity is certainly intriguing and it might be fun to determine how it behaves as $n$ gets large.
Comment: Thanks cardinal; I'm in *way* over my head here, so I'm going to have to trust your maths.  I'll go over it to see if I can understand what's going on, but I think my problem was much more easily stated than solved!  Now, for x^k + y^k = z^k for x, y, z, and k > 2...  ;-)
Comment: There are a couple points I've thought of since I posted this which might help a bit with intuition. I'll edit them in to the post in a bit.


Want to find the degrees with the cosine similarity value

Question: Suppose, I am getting 0.87456 as a cosine value through cosine function in python language.
I want to know the degree to plot in X-Y plane graph? How can I get the value in degrees.
Answer: I just did the following test and I believe it to be correct:
>>> import math
>>> math.degrees(math.acos(0.87456))
29.007055526563033

So, as you can see, the math library contains acos (for inverse cosine) and degrees (for converting radians to degrees).
Comment: @JatinChopra. You're welcome. Please accept my answer, so it can be used as a reference.


How do I show that $P(|X-Y|>1/n)=0 \forall n \in \mathbb{N}$ then $X=Y$ a.s

Question: How do I show that if  $P(|X-Y|>1/n)=0 \forall n \in \mathbb{N}$ then $X=Y$ a.s
Though this looks fairly obvious but how do i put it down rigorously . Can I say that $P(|X-Y|>0)=P\big(\bigcap_{n \in \mathbb{N}}\{|X-Y|>1/n\} \big) \leq P(|X-Y|>1/2)=0$ which implies that $P(X=Y)=1$ i.e. $X=Y$ a.s
Is the reasoning correct?
Comment: You confused intersection and union. Being positive means being greater than some $\frac{1}{n}$. So you have to put a union there. The result follows then from the continuity of a measure.
Comment: What if X=Y+1/10? then P[X=Y] =0, but P[|X-Y|>1/2]=0
Comment: @PeterR Why does $X-Y=10 \implies P[X=Y]=0$ ?
Comment: @MooS That was very stupid of me. Thanks you
Answer: We know that
$$\mathbb{P} \left(\left[\vert X - Y \vert > \frac{1}{n}\right]\right) = 0 $$
Then
$$[X \neq Y] \subset \cup_{n} \left[\vert X - Y \vert > \frac{1}{n}\right] $$
Therefore
$$\mathbb{P} \left( [X \neq Y ]\right) \leq \mathbb{P} \left(\cup_{n} \left[\vert X - Y \vert > \frac{1}{n}\right]\right)\leq \sum_n\mathbb{P} \left( \left[\vert X - Y \vert > \frac{1}{n}\right]\right) = 0 $$
We conclude that $\mathbb{P} \left( [X = Y ]\right) = 1$ that is $X = Y$ a.s.
remark: we denote $[X = Y]$ the event $\{\omega \in \Omega: X(\omega)  =Y (\omega)\}$ and  we consider $X, Y$ random variables on a probability space $(\Omega, \mathcal{B}, \mathbb{P})$
Comment: Thanks your answer was nice and clear.


Mostrar linha de código de acordo com a data

Question: Tenho uma página estática que vai trabalhar offline com a proposta de ser um painel de controles que terá a "programação do dia" de uma igreja.
Em uma das colunas (como mostra na imagem) um dos vídeos será alterado diariamente e todo restante permanecerá intacto. A pergunta é: existe a possibilidade de deixar todas as tags  dos videos que usarei já listadas (porém ocultas) e mostrar apenas o video que preciso para aquele dia, predefinido por um comando que leva em consideração a data?
Linha de código atual:

<video class="borda-player" src="videos/1.mp4" controls="true"></video>
Comment: Vais ter videos para todos os dias? Como estão armazenados os videos/tags? Vêm de uma base de dados? Devias colocar o código relevante acerca dos videos/tags, https://pt.stackoverflow.com/posts/265301/edit
Comment: Boa tarde Miguel! Vai ser um vídeo diferente para cada sábado do mês. essa é a linha que estou usando:
Comment: Seria qualquer coisa como isto: https://ideone.com/Do6ehs . em que as chaves do array serão os dias dos sábados do mês? podes testar colocando 26 como uma das chaves do array que é o dia de hoje
Answer: Boa tarde Talles,
Dá para fazer de 2 maneiras:
No próprio código você coloca uma clausula IF com o Now() para verificar a data e apresentar o vídeo que que.
Ou então fazer um banco de dados para e no banco de dados (pode ser um mysql simples) e cadastrar qual o caminho do vídeo que você quer para aquele dia.
Espero ter ajudado.
Comment: Boa tarde Rodrigo! obrigado pela ajuda! Poderia me dar uma luz? Isso vai além do conhecimento básico que ainda tenho.rs Minha linha de código está bem simples. Veja:
Comment: if(strtotime('2017-12-25') == now())
{
echo();
}
elseif(strtotime('2017-12-31') == now())
{
echo();
}
else
{
echo();
}

Mais ou menos isso ai


Formally prove that a subset S of R^n, whose members are all isolated, is at most countable

Question: There was a previous post I saw in May that looks like addressed a slight variation to this question but I'll ask anyway for clarity.
If I have a set $S \subset \Bbb R$ (I will focus on the real line first and then make an argument that the proof holds for all n-space) and every point $p \in S$ is isolated, then how do you prove that S is at most countable? Let me show what I've done so far.
If all points are isolated, then for every $p \in S$, p is not a limit point of S. This means that for each point p, $\exists$ some open ball of p $B_r(p)$ with no $q \neq p$ such that $q \in S$. If S is finite, then it is clearly at most countable, just by the definition.
If S is infinite, we can separate it into its rational and irrational parts. Let I be the set of $p \in S$, where p is irrational. And if I is finite, then I is clearly at most countable. But now assume that I is infinite. Because $\Bbb Q$ is dense in $\Bbb R$, $\exists$ 2 rational numbers a < b such that $(a, b) \cap S = \{p\}$. So for every 2 rationals a and b, there exists an open set with only p. Because $\Bbb Q$ is countable, I is countable.
Let A be the set $q\in S$, where $q \in \Bbb Q$. If A is finite, it is clearly at most countable. If A is infinite, then it must be countable because the set of $\Bbb Q$ is countable.
Therefore, S is at most countable. And if it's at most countable in 1 dimension, then it follows by induction that it's at most countable in n dimensions. Any improvements or suggestions?
Thanks
Answer: You can do the proof in $\Bbb R^n$ from the start.  At the end of your third paragraph, don't bother with whether $S$ is finite or infinite.  Just use the balls that you have observed the existence of.
Specifically, shrink all of those balls by a factor of 1/2, so that they do not overlap.  Then for each ball, pick one element of $\Bbb Q^n$ that is inside the ball.
(If you want to make this "picking" concrete, then since $\Bbb Q^n$ is countable, you can use a bijection between $\Bbb Q^n$ and $\Bbb N$ to pick the "first" rational point in the ball.)
This provides an injection from $S$ into the countable set $\Bbb Q^n$, so $S$ must be countable.
Comment: Thanks Matt for your reply. I don't understand your suggestion of shrinking the balls by 1/2 so that they don't overlap, and then pick an element of $\Bbb Q^n$ inside each ball. Each $B_r(p)$ by definition only includes p, so they wouldn't overlap, right? I also don't understand why there must be an element of $\Bbb Q^n$ inside the ball..what if one or more of the coordinates of p were irrational? Then since $B_r(p)$ only contains p, it wouldn't contain any element of $\Bbb Q^n$.
Comment: Since a ball only contains $p$ (of elements of $S$), it will not contain the _center_ of any other ball, but it could still overlap another ball (without there being any element of $S$ in the overlap region).  Shrinking them by 1/2 ensures that they don't touch each other, since then every ball extends less than halfway to any other point of $S$, and so lies strictly within the set of points in $\Bbb R^n$ that are closer to $p$ than to any other point in $S$.
Comment: @Jeff Regarding finding an element of $\Bbb Q^n$ inside the ball, the ball has some size greater than zero, and cannot be empty of elements of $\Bbb Q^n$, because $\Bbb Q^n$ is dense in $\Bbb R^n$.  If $p$ is not in $\Bbb Q^n$, it is still a limit point of a sequence of points in $\Bbb Q^n$, and so this sequence must enter the ball.
Comment: OK, I think got it! So each $p \in S$ can therefore be mapped to a unique $y \in \Bbb Q^n$. This is true for 2 reasons. 1) $\Bbb Q^n$ is dense in $\Bbb R$, which means that for each $x \in \Bbb R$, either $x \in \Bbb Q^n$ or there is a member $y \in \Bbb Q^n$ arbitrarily close to x. And 2) each $B_{r/2}(p)$ do not overlap. Letting Y contain all these chosen y, there is a bijection between S and Y. Y is countable, so S is countable.
Comment: @Jeff That's right, the point of your step (1) being that you can always (i.e. for each $p$) choose a $y \in \Bbb Q^n \cap B_{r/2}(p)$, because $\Bbb Q^n \cap B_{r/2}(p)$ cannot be empty, because $\Bbb Q^n$ is dense in $\Bbb R^n$.


Binding MySQL to run from the public or private LAN IP address - which one is faster

Question: So we have 2 servers all running at the same web host. We have bind MySQL to listen on the public ip-address of the database server and the web server connects to it from the public ip. Both servers run on the same private network.
Currently, the DB connect method from our php script takes about 3ms to connect to the MySQL database server host.
My question is, would MySql data interaction from the web server be faster if we bind it to listen on the private lan address on the database server instead of the public IP? or is it the same regardless and it wont make a different.
Comment: Do you know what the network looks like in between the systems for the public vs private network - differences in switching, routing, etc?  If not, then it might be a situation where you'll just need to test each option to see which is faster.  And by the way, if you're binding MySQL to a publicly accessible interface, make sure that it's firewalled so that only certain IP addresses can connect.
Comment: it looks like your mysql server tries to resolve connecting client
add `skip-name-resolve` to `mysqld` section of your my.cnf and restart mysql service
Comment: @eicto I tried the skip-name-resolve and that works as expected but we still cant make mysql start once the bind address port is set to the local ip
Answer: Packets to the public ip most likely travel through your firewall, and packets to the private ip most likely don't. So yes, it will probably be (slightly) faster to use the private ip.


Generate Certificate stuck Java

Question: I'm trying to generate a certificate from a socket input stream but it seems to get stuck when I use the method form CertificateFactory. The program keeps running in the console when it should end.
Here is the code:
<code>public PublicKey getCertificate() throws IOException, CertificateException
{
    String resp= br.readLine();
    System.out.println(resp);
    CertificateFactory  cf = CertificateFactory.getInstance("X.509");
    System.out.println("GOING TO CREATE CERTIFICATE");
    Certificate certificate =  cf.generateCertificate(socket.getInputStream()); //GETS STUCK

    System.out.println("SUCCESS");
    pw.println(RTA+":"+OK);

    return certificate.getPublicKey();
}
</code>
The console shows no error whatsoever so I don't know what could be wrong, also I know the socket is getting the information since this is part of a larger communication protocol and the previous communications worked
Comment: Why would you want to get a certificate from a socket?
Comment: @EJP  I'm simulating a client and a server, they comunicate through a socket  so here I'm triying to get the server's certificate so I can continue with the client protocol
Comment: In other words you're reimplementing the SSL handshake? Don't. It's already done. There's a lot more to it than just tranmitting certificates around if you want it to be properly secure.
Answer: Whatever you're connected to either isn't sending a complete binary certificate or isn't closing the socket.

Generate Certificate stuck Java


Prove that ($\mathbb{R}$, $\le$) is a partial order

Question: I was told that the relation $\le$ is a total order on R, it is dense, and it has a least upper bound property. I actually have don't understand those 3 properties... :/
Answer: Total order means, that the order relation $\leq$ is antisymmetric (if $a\leq b$ and $b\leq a$ then $a=b$), transitive ($a\leq b$ and $b\leq c$ implies $a\leq c$) and total (for all $a,b$ holds $a\leq b$ or $b\leq a$, compare e.g. with the subset relation which satisfies the first two, but not totality).
Dense means that for $a,c$ with $a < c$ there is some $b$ with $a < b$ and $b < c$.
The least upper bound property means that for each set that is bounded from above the supremum exists, e.g. $(-\infty,\sqrt{2})$ has least upper bound $\sqrt{2}$ which does not exist in $\mathbb{Q}$ (which satisfies the two other properties).
$\mathbb{R}$ is determined as the (up to isomorphism) unique field that has a total order and the least upper bound property.
Answer: In contrast to a partial order the a total order is defined everywhere. This means that given arbitrary a and b either a<=b or b>=a.
Comment: In a total order, each pair of elements is comparable (either $x \le y$ or $y \le x$ or both).  In a partial order you can have a pair of elements incomparable (neither $x \le y$ nor $y \le x$).


Utilizo PHP dentro de um HTML ou um HTML dentro de um PHP?

Question: Fiz todo meu site em HTML e CSS, só que agora estou precisando utilizar o PHP para enviar alguns dados para um banco de dados. Só que estou com uma dúvida, se modifico todos os meus documentos para .php ou se utilizo o PHP dentro do HTML (se é que é possível).
Comment: Minha opinião? Faça ambos separados e a comunicação entre eles via Ajax.
Comment: Eu recomendo não utilizar php no seu html, faça o PHP trabalhar somente em camada back-end, trazendo tudo por API RestFul..., via javascript. Vai sofrer menos.
Comment: [+] só precisa saber trabalhar com objetos do javascript e interpretação de JSON, que é muito similar ao XML
Answer: Respondendo a sua 1ª pergunta
Preciso alterar todos os meus arquivos apenas para enviar alguns dados para o php e então processá-los e salvar no banco de dados?
Não! Basta você manter o seu arquivo que contém o formulário por exemplo, e setar a action dele para o arquivo .php, por exemplo:
seu_formulario.html
<form action="processa_dados.php" method="post">

</form>

Pronto. Com isso você já consegue fazer de maneira simples o que você quer.
processa_dados.php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  // valida e processa os dados
  // redireciona para uma página de sucesso ou erro
}

Respondendo a sua 2ª pergunta
É normal, e não é má prática criar um arquivo por exemplo index.php, com todo seu html padrão (DOCTYPE, html, head, body, etc) junto ao PHP para mostrar variaveis, utilizar condições (if, else, foreach, while). Como no exemplo abaixo (CakePHP):
<!doctype html>

  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>
    <?php
      if(isset($titulo)) {
        echo $titulo . ' | ';
      }
    ?>
    StackOverflow
  </title>

  <?php include('cabecalho.php') ?>

  <?php echo $conteudo ?>

  <?php include('rodape.php') ?>

O que é má prática pelo contrário, é criar uma classe por exemplo, que retorna o HTML da sua página por completo, concatenando já as variáveis, etc.
<?php

class Exemplo
{

  public function resposta()
  {
    echo '

                <input type="hidden" name="_id_" value="7706">
                votar a favor
                3
                votar contra

Um arquivo HTML com extensão .php vai se comportar exatamente como HTML. O interpretador PHP só entra em cena para o que estiver entre <? ... ?>.

Neste contexto o ideal é usar tudo .php.

';
  }

}

Sim, acredite... tem programadores que fazem isso. Então NUNCA faça isso.
Comment: @JorgeB. por "n" motivos, vou listar alguns: 1) difícil manutenção do código. 2) difícil indentação do código. 3) caractere de escape necessário as vezes. 4) faz com que seu código/classe se torne bem maior. 5) pequena perda de performance dependendo do tamanho e/ou operações dentro do código/html. Mas a principal questão é a legibilidade do código, sendo assim, é melhor manter isso em um arquivo externo e apenas injetar/chamar ele no momento da resposta.
Comment: Porque é que é má prática fazer dessa forma?
Answer: Um arquivo HTML com extensão .php vai se comportar exatamente como HTML. O interpretador PHP só entra em cena para o que estiver entre <? ... ?>.
Neste contexto o ideal é usar tudo .php.
Comment: pelas normas do PHP, sempre utilize  ou  para impressão
Answer: Quando você pergunta:

se modifico todos os meus documentos para .php ou se utilizo o php
  dentro do html

Na verdade não são opções mutuamente excludentes: para "utilizar o PHP dentro do HTML" você precisa modificar o documento para ".php"! :-)
Você pode, alternativamente, manter os arquivos HTML como estão, e fazer o PHP em separado.
Assim mesmo, em algum momento, você usaria o PHP para ler esse arquivo HTML e modificá-lo.
Em geral, os frameworks PHP solicitam alterações no arquivo HTML, seja usando uma linguagem de template específica (Blade, Twig, ou outra), ou utilizando o próprio PHP como linguagem de template, para integrar os dados obtidos no banco de dados com o markup.

Retomando a questão por outro ângulo...

Utilizo Php dentro de um Html ou um Html dentro de um Php?

Você pode incrementar o seu site feito em HTML e CSS acrescentando primeiramente JavaScript.
O ideal seria fazer a comunicação entre o lado do cliente, onde habitam HTML, CSS e JS, totalmente com JS - inclusive viabilizando que esse mesmo site use qualquer linguagem no lado do servidor, sem ser modificado.
Você usaria uma biblioteca como jQuery ou AngularJS ou Breeze ou outra para solicitar os dados do servidor via Ajax, fazendo as requisições para ler, criar, atualizar ou remover dados do servidor (CRUD = Create, Retrieve, Update, Destroy = INSERT, SELECT, UPDATE, DELETE...)
Desse jeito, você não mistura PHP com HTML. Ou seja, nem PHP dentro de HTML, e nem HTML dentro de PHP. Este seria o ideal.
O máximo que você puder fazer para evitar a mistura de PHP com HTML, faça.

Por outro lado, você pode enxergar o PHP como uma linguagem de templates.
Com um uso muito bem disciplinado, você pode aproveitar as estruturas de controle que a linguagem oferece para montar o seu HTML a partir do servidor incluindo variáveis:

Seja bem vindo, <?php echo htmlentities($usuario); ?>.

Essa utilização do PHP dentro do HTML, como uma linguagem de template, é aceitável, e existem frameworks que te ajudam muito a manter as coisas nos seus devidos lugares (sou fã do Laravel 4).
Outro exemplo:
<?php foreach ($itens as $item): ?>

Item <?php echo htmlentities($item->nome); ?>

<?php endforeach; ?>

Isto é PHP dentro de HTML ou HTML dentro de PHP? Fica difícil dizer. No caso, ainda estamos usando o PHP como "linguagem de template".
O HTML dentro do PHP propriamente dito seria assim:
<?php
    foreach ($itens as $item) {
        echo '
Item ' . htmlentities($item->nome) . '
';
    }
?>

Esse tipo de coisa deve ser evitado.
Quando o teu código conecta o banco de dados, faz consultas, updates, verifica se o usuário mandou dados, valida formulários, e no meio disso tudo vai soltando uns HTMLs... isso é comum, mas é medonho - é o código "espaguete", que naturalmente vai se formando para iniciantes, mas deve ser evitado a todo custo.

No fim das contas, não há diferença entre "PHP dentro de HTML" e
  "HTML dentro de PHP".

Na prática, quando o arquivo contém a extensão ".php" fazendo com que, por padrão, ative o interpretador da linguagem PHP ao ser servido por um servidor HTTP (como o Apache ou o NginX), ambos, a marcação HTML e o código PHP (envolvido dentro de <?phpe ?>) serão processados. O HTML fica inalterado, enquanto que o que está dentro das tags mencionadas é executado (eventualmente repetindo o HTML, como vimos).
Answer: Para ativar o php dentro do html, vc teria que configurar o seu servidor (Apache, IIS etc.) para processar arquivos html utilizando o PHP. Essa não é a configuração mais comum.
O normal mesmo é processar com o PHP apenas os arquivos com extensão .php
Comment: Os links também podem ser mantidos como estão, configurando o apache para reescrever as urls.
Comment: Sim. O interpretador PHP só processa código dentro das tags ``, o resto é passado sem alteração. Normalmente arquivos HTML podem ser renomeados para .php sem nenhum efeito inesperado.
Comment: Entendi, mas no caso se eu transformar meus arquivos .html para .php, eles vão funcionar normalmente ?
Comment: Verdade, Havenard. Porém você precisa lembrar também de alterar qualquer link que aponta para um endereço "blablabla.html" para "blablabla.php" // o seu programa editor deve ser capaz de fazer essa conversão dos links automaticamente para você.
Comment: Claro. Naturalmente os arquivos que os links apontam precisam existir. Alterar a extensão implica que o nome do arquivo foi alterado, e os links apontando pra ele precisam ser corrigidos.
Comment: Mas quando eu terminar meu site e for publicar, alguma dessas alterações, tanto modificar para .php, quanto configurar o apache, vai ter alguma influência no funcionamento ?
Comment: No caso do apache, você configura a reescrita de urls num arquivo htaccess na raiz do site. Esse arquivo precisa ser publicado junto com os outros.
Comment: Valeu gnt, brigado..
Answer: O que for estático, mantenha estático.
Exemplo, uma página HTML na qual não há necessidade em usar banco de dados ou recursos do PHP, não há motivos para usar PHP.
Simples assim... a menos que tenha algum motivo muito específico para parsear um determinado conteúdo estático dentro do compilador do PHP.
Answer: Eu imagino que não seja essa exatamente sua dúvida, mas o ideal é manter a mistura entre HTML e PHP ao mínimo. Isso facilita mudar as coisas dos dois lados, então sempre busque escrever um arquivo PHP com todas as funções necessárias - de preferência, que comece com <?php e nem feche a tag - que vai ser invocado por algumas partes do seu HTML.
Voltando à sua pergunta, a configuração mais comum é que o seu HTML inclua algumas tags PHP e tenha extensão .php. Você pode também fazer com que o HTML seja apenas um modelo, que é carregado pelo código PHP e modificado nas partes dinâmicas.


Uniform thickness border around skewed ellipse?

Question: I have an ellipse with a given major and minor 'radius'.  I then apply a 2D skew affine transformation to it.  Then, I want to draw a uniform border inside this new shape, as if a circle were rolled along the interior edge of the newly transformed ellipse, and everywhere the circle touched was drawn in a different color.  Or as if the new shape had been outlined with a marker.
This essentially divides the ellipse into an "outer" shape which separates the border from the rest of the scene, and an "inner" shape that separates the border from the interior of my shape.  See the diagram at the end of my post.
In the case of this diagram, the very edge of the black outline would be the outer shape, and the shape defined by the transition from green to black would be the inner shape.
The outer shape is an ellipse, I'm fairly certain, as it's just an affine transformation of my original ellipse.  I'm not sure if the inner shape I want is also an ellipse.  If I assume that the inner shape has the same affine transformation as the out shape, and I just adjust the major/minor axis radii, I get something like in the diagram.  The inner shape doesn't intuitively match up with outer shape.  It's as if I've drawn a completely arbitrary green ellipse inside my black ellipse.  The green ellipse seems to have a different rotation even.
So my questions:  Is the inner shape I actually want an ellipse?  If so, what are its major/minor axes, and does it have a different affine transformation from its parent?  If it does have a different transformation, how do I find it?  If it's not an ellipse, what is it?
...
I couldn't upload an imagine because I don't have the reputation points (ugh), but this is the code for it in SVG:
<code><svg width="100%" height="100%" version="1.1" xmlns="http://www.w3.org/2000/svg">
    <g transform="skewY(30) rotate(-32)">
        <ellipse cx="250" cy="225" rx="225" ry="125" style="fill:rgb(0,0,0);"/>
        <ellipse cx="250" cy="225" rx="175" ry="75" style="fill:rgb(0,100,50);"/>
    </g>
</svg>
</code>
Chrome and Firefox can both display this if you put this into a text file with a .svg extention.  If someone can post an image of it for me, I'd appreciate it (not all sites like svg extensions...  You might need to rasterize it into a png first).
It also makes it very easy to play around with different transformations and settings for the ellipses.  The SVG manual is useful for understanding how the transforms and skews are interpreted.
Comment: Related: [Does using an ellipse as a template still produce an ellipse?](http://math.stackexchange.com/q/64840/856)
Answer: The inner shape is indeed not an ellipse, as Skatche explains. It is a parallel curve of the original ellipse. I don't think it has a specific name. If you need equations, the Wikipedia article has a parametric form.
Comment: Ah, that looks very promising.  I'll look into it and see if I can get what I need from the parametric form.
Answer: I think you're right about ellipses being preserved under affine transformations.  However, notwithstanding that, it's not true in general that the interior shape you're drawing will be an ellipse.
Let's start with an outer circle, call it $C$, of radius $D>d$, where $d$ is the thickness of the border.  You can get the border by rolling a circle $c$ of radius $d$ around the inside of $C$.  Now start stretching $C$ horizontally into an ellipse, so that it reaches its maximum curvature at the leftmost and rightmost points.  Eventually, the maximum curvature of $C$ will be greater than the curvature of $c$, at which point your inner border will develop "corners" (you can imagine $c$ getting stuck when $C$ becomes too narrow and rebounding), so it can't possibly be an ellipse.
Comment: Hmm...  what if instead of rolling the circle around the interior, I trace the ellipse with a circle twice as large, and clip the result so it fits inside the ellipse?  That would seem to prevent discontinuities, and I think it would give (basically?) the same thing.


"numrt": identifyer not found despite of defining that function

Question: I'm writing a library of mathematical functions in C++. I made the sqrt function and it works well. I also tried to make a root function that counts n'th root of a number. I have 3 files - emath.cpp, emath.hpp, main.cpp (emath is name of my library).
emath.cpp:
namespace emath
    {
    class emath
        {
        public:
           /* ... */
        //Returns value of square root of a number.
        static double sqrt(double tur);

        //Rerurns value of a root of a number.
        static double numrt(int stopien, double tur);
    };
}

emath.hpp:
#ifndef EMATH_HPP
#define EMATH_HPP

using namespace std;

namespace emath
    {
    class emath
        {
        public:
        /* ... */

        int emath::derivative(double x)
        {
              return 0;
        }
        //****************************************************************
        double emath::derivative(double number, int pow)
        {
              double result = 1;
              for (int i = 1; i < pow; i++)
              {
                    result *= number;
              }
              result *= pow;
              return result;
         }
        //************************************************************************
        double emath::derivative(double number, int pow, double numbey)
        {
             return ((derivative(number, pow) + derivative(numbey)));
        }

        //************************************************************************
        double emath::sqrt(double tur)          //This function
        {
    int a;

    static int i = 0;
    for (; i * i <= tur; i++)
    {

    }
    if (i * i == tur)
    {
        return i;
    }
    a = i;
    return sqrtl(a);
}
//************************************************************************
double emath::numrt(int stopien, double tur)          //This function
{
    int a;

    static int i = 0;
    for (; i * i <= tur; i++)
    {

    }
    if (i * i == tur)
    {
        return i;
    }
    a = i;
    static int mul = 1;
    for (int p = 0; p < stopien; p++)
    {
        mul *= i;
    }

    return numrtel(mul, i, a);
}

private:
//****************************************************************
double emath::sqrtel(double tur, static int k = 0)  //Implementation of Newton's Method
{
    double a;                                                      //Creates a - our xn.
    if (k == 1000000)
    {
        return a;
    }
    a = a - ((a * a - tur) / derivative(a, 2, - tur));          //Proper implementation os Newton's Method
    ++k;                                                        //k is counter
    return sqrtel(a);
}
//***************************************************************
double emath::numrtel(int mul, int i, double tur, static int k = 0)
{
    double a;                                                      //Creates a - our xn.
    if (k == 1000000)
    {
        return a;
    }
    a = a - ((mul - tur) / derivative(a, i, - tur));          //Proper implementation os Newton's Method
    ++k;                                                        //k is counter
    return numrtel(mul, i, a);
}
};  //end of class
}   //end of namespace

#endif // EMATH_HPP

If my main.cpp is
#include <iostream>
#include "emath.hpp"

using namespace std;
using namespace emath;

int main()
{
    double number;
    cin >> number;

    cout << sqrt(number);

}

it works very well, but if main.cpp is
#include <iostream>
#include "emath.hpp"

using namespace std;
using namespace emath;

int main()
{
    double number;
    cin >> number;

    cout << numrt(3, number);

}

I get a compiler error: "numrt": identifyer not found.
I'm using MS VS Studio 2012 Compiler with Qt Creator.
Why is that?
Comment: Do you tried to call with emath::numrt(3, number)?
Comment: Your .hpp declares `numrt` to be non-static, meaning that you need to call it on a `emath` instance.  Or make the function static.
Answer: Since you declared numrt() inside a class emath, you have to state that class name in the function call:
emath::numrt()

(The full call, including the namespace name is emath::emath::numrt().)
I wonder why the call to sqrt() works, since for your code to execute, you'd have to call it with emath::sqrt() as well. Are you sure that your code is executed and not some code from standard libraries?
Comment: Yes, now it works - thanks to you I realized that my function doesn't retur good value :/ Thank you :-)


Is there a way to have tabs with independent content in them, without extending TabActivity or using fragments?

Question: Is there a way to have tabs with independent content in them, without extending TabActivity or using fragments?
I am a newbie in android development and I am confused with TabHost and TabView
Answer: The design support library has a TabLayout that you can easily use.

The Design library's TabLayout implements both fixed tabs, where the
  view's width is divided equally between all of the tabs, as well as
  scrollable tabs, where the tabs are not a uniform size and can scroll
  horizontally. Tabs can be added programmatically
  However, if you are using a ViewPager for horizontal paging between
  tabs, you can create tabs directly from your PagerAdapter's
  getPageTitle() and then connect the two together using
  setupWithViewPager(). This ensures that tab selection events update
  the ViewPager and page changes update the selected tab.

TabLayout tabLayout = ...;
tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));

With API level 21 , actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS) has been depricated in favor of TabLayout.
For more, http://android-developers.blogspot.co.uk/2015/05/android-design-support-library.html
Without using fragments? Well, that's not possible. You will have to use a ViewPager, make a few Fragments and make a fragment adapter that wires them all up.


Why my code is Time Limit Exceeded (leetcode104)

Question: I am solving some exercises at leetcode 104
Desciption : Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Here  is  my  solution
  public int maxDepth(TreeNode root) {
      if(root ==null ) {
         return 0 ;
      }
      return ( maxDepth(root.left)+1) > (maxDepth(root.right)+1 ) ?
             (maxDepth(root.left)+1):(maxDepth(root.right)+1);
  }

But it throws  Time Limit Exceeded .
Then  I  change it  to  this  ,it runs well and  accepted
 public int maxDepth(TreeNode root) {
          if(root ==null ) {
             return 0 ;
          }
          int left  = maxDepth(root.left)+1;
          int right = maxDepth(root.right) +1 ;
          return left > right ? left :right ;
        }

But  I don't think  they have any differences . Please  help  me  to understad where I had made the mistake .
Thanks for  your guide, cheers!
Comment: Add a println statement to your `maxDepth` method and you will see the difference between the two approaches.
Comment: thanks a lot  for  your help
Answer: probably four method call
(maxDepth(root.left)+1) > (maxDepth(root.right)+1 ) ?
(maxDepth(root.left)+1):(maxDepth(root.right)+1)

Here you are calling the maxDepth method 4 times which is not efficient.
Calculations for root.left and root.right are duplicated recursion calls which are not necessary. Try to think and optimize your solution by reducing the number of method calls and this will make your code execute within much faster.
Your second code snippet involves only 2 recursive method calls, making it a better performing solution.
You can even use a much simpler solution:
if (root == null) {
    return 0;
}
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;

Comment: it is useful   ,could you tell me  which is . faster  'Math.max()'     method  or      'Ternary Operator'
Comment: just  in compare


Difference-in-difference with multiple periods and one more interaction

Question: I have a question with the non traditional diff in diff with multiple periods. I currently have a balanced panel data with simple diff in diff in multiple periods treatment which could be written as:
$Y_{ist}=α+γs(\text{Treatments})+λ(\text{year dummy}_t)+δD_{st}+ϵ_{ist}$
The above equation allows me to measure the policy after treatment time ($D_{st}$) effect on $Y$.
Now, I would like to measure the effect of another variable (say $Z$) at the post-treatment period from treated group on $Y$ controlling the nature difference of the effect from $Z$ on $Y$ on other dimensions (treat and control, pre and post).
I wonder if this is a triple difference, or a diff-in-diff but with one more interaction of the variable $Z$ on everything.
Answer: If theory tells you treatment effect should be larger for particular subset of observations, then you can interact additional variable (in your case Z) with other variables in your regression. In that sense, it measures sensivity to treatment. But you have to use ex-ante measures because your variable (e.g. Zt-1), Z itself might be affected from your treatment.
It is called triple difference, but you can still call it diff-in-diff with interaction if you will.


How to update function signature after modification with rlang::fn_fmls?

Question: rlang::fn_fmls<- allows us to modify function signatures:
f <- function(a, b, c) print(paste(a, c))
f_args <- rlang::fn_fmls(f)
f_args["b"] <- NULL
rlang::fn_fmls(f) <- f_args
f(1, 2)
#> [1] "1 2"

Created on 2020-04-07 by the reprex package (v0.3.0)
Clearly we've removed b from the function's signature. However, if we print the function itself:
f
#> function(a, b, c) print(paste(a, c))

b still appears in its signature. Using args(f) (which only prints the signature) actually works and b is omitted.
What should I do to get the function (with body) to print correctly, with b omitted?
Comment: @akrun yes, I mention that in my question. Is there a way of modifying the simple `f` though?
Comment: Check `attr(f, 'srcref')`.
Answer: The problem seems to be that print.function() has useSource = TRUE, which forces the use of the original function signature and body.
A solution I found would be to modify the function's class and create a custom print function.
f <- function(a, b, c) {
  b <- 1
  print(paste(a, c))
}
f_args <- rlang::fn_fmls(f)
f_args["b"] <- NULL
rlang::fn_fmls(f) <- f_args
class(f) <- c("myfunction", "function")

print.myfunction <- function(f) {
  class(f) <- NULL
  print(f, useSource = FALSE)
}

f
#> function (a, c)
#> {
#>     b <- 1
#>     print(paste(a, c))
#> }

Created on 2020-04-07 by the reprex package (v0.3.0)
Comment: Either create a custom `print` function, or modify the source attribute.


What are the differences between Lloyd's, MacQueen's and Hartigan's algorithms for K-Means?

Question: There are three distinct algorithms for the K-Means function in R. These are:

Lloyd's
MacQueen's
Hartigan's

I believe I understand how Lloyd's works. 1. The cluster centers are chosen. 2. Points are assigned to the nearest center. 3. Centers are shifted to the mean of the points assigned to them.
My question is about how MacQueen's and Hartigan's algorithms differ to it. Here are some more specific questions, but any information about these methods would be helpful:

Supposedly MacQueen's is more efficient, because it updates centroids more often. (Source).
At what stages does MacQueen's update centroids that Lloyd's algorithm does not? (the source is unclear to me)
Why does this make it more efficient?
What exactly does 'more efficient' even mean? (My tests show that MacQueen's and Lloyds and Hardigan's all run at the pretty much the same speed for any data).
My tests show that Hartigan's algorithm is more accurate because it does not seem to be affected as much by the random initial centroid positions. Here is the test I did:

There are 4 points. The vertical distance between them is 1, and the horizontal distance between them is 1000.

Assuming there are 2 clusters, clearly the correct clusters (with the lowest sum of squares) would be clusters of points above and below each other.

But because of the random initial centroid positions, sometimes the algorithm converges to a local optimum, and produces this obviously wrong result.

After doing >1,000,000 runs on each of the three, I found that Lloyd's and MacQueen's were both correct 2/3 of the time, and wrong for the other 1/3. However, Hartigan's was correct 100% of the time.
How does Hartigan's method even work? And how does this make it more accurate in terms of 'fixing' the wrong results that are caused by the initial random centroids?
Comment: Orthogonal comment: Your graphs are not crisp and clear. The contrast between the data points and the grey backdrop is not strong. Larger open markers or point symbols are easier to spot than small dots. The grid machinery is too obtrusive and not needed for your purposes any way. The numeric labels on the axes are very small. These are small points, and partly matters of taste, but they combine to make your graphs distracting as well as helpful.
Comment: @NickCox Thank you for the suggestions, I have redone the graphs, although the old ones at _normal_ size (click on them) were not bad. In any case, I hope people focus on the actual question, as the graphs were just one example of the different outputs of these algorithms.
Comment: Thanks for the attention. The point was that with clearer graphs (now achieved) people should indeed be able to focus on the question.
Answer: Could't figure out much from the graphs but to answer your questions-
At what stages does MacQueen's update centroids that Lloyd's algorithm does not? Macqueen recalculates the center every time an iteration is completed like Lloyd's but also everytime a data point changes it's subspace (Cluster). So many more centroid calculations in Macqueen.
Why does this make it more efficient? It might not be efficient always, Consider a scenario where both the clusters are easily separable. Macqueen moves slowly as calculating new centroids while Llyods would jump towards right centroids in every iteration in lesser centriod calculation. So i think efficiency is not guaranteed.
What exactly does 'more efficient' even mean? (My tests show that MacQueen's and Lloyds and Hardigan's all run at the pretty much the same speed for any data).  - Overall performace, like there can be a case where K-means will lead to an empty cluster. While macqueen and Hartigan algos may give different results for same datasets( if order of points is high)
How does Hartigan's method even work? And how does this make it more accurate in terms of 'fixing' the wrong results that are caused by the initial random centroids?  Please read the below paper- goto page 17. It takes within cluster sum of squares rather than distance as metrics to classification a point in any cluster.
https://core.ac.uk/download/pdf/27210461.pdf


Wordpress menu cannot be centered

Question: I am working with the site cardinalmma.com/ but you can see that the menu is not centered. For example see the news menu its in the left portion but with some padding. I want it to be centered can anyone help me.
thanks
Somdeb
Comment: Vertically or horizontally centered?
Comment: at least try to find your self.if then any issue occur then post your effort here.this question is not clear.
Answer: You want the individual navbar labels centered, correct?
li.menu-item {
    text-align: center;
}

This targets the
 tags in your menu, identified by the .menu-item class. The text-align: center; rule takes care of centering the  tag with your text in it.
In my browser, this modification makes it look like this:
Answer: Try something in your css stylesheet to make the menu items be align center.
try something with the class menu and the li part:
.menu {
    text-align: center;
}

Or something in that direction
Answer: Please update your css. This should resolve your issue.
.menu_top a {
color: #eee;
font-weight: bold;
line-height: 3.4em;
padding: 0 14px;
text-decoration: none;
height: 50px !important;
text-align: center;
display: block;
}

.menu_top ul ul li a {
 text-align:left;
 }

Answer: To center the navbar labels use this css courtesy of Surreal Dreams:
li.menu-item {
    text-align: center;
}

Now to elaborate on how to find this solution. The best way to edit/develop CSS for wordpress is to use firebug or Chrome's developer tools to find the element you want to modify.Then you can add CSS right there and see the results real-time (these changes are not permanent). I would say it is likely this is how Surreal Dreams found the solution.

If you want to learn more about using the Chrome dev tools tool go to this page: https://developers.google.com/chrome-developer-tools/.
If you are new to CSS (I dont know if you are new to CSS or if youre problem is strictly editing CSS) for wordpress you should go check out http://www.codecademy.com/tracks/web

Wordpress menu cannot be centered


Prove that for all $\phi, \psi \in M$, $S(\phi \circ \psi) = S(\phi) S(\psi)$

Question: Problem:
Let $[n] = \{1,2, \dots, n\}$. We define $M$ to be the set of bijections $\phi : [n] \rightarrow [n]$, and $S: M \rightarrow \mathbb{R}$.
The map $S(\phi) = \prod_{i>j=1}^n \dfrac{\phi(i) - \phi(j)}{i-j}$.
I must prove that $S(\phi\psi) = S(\phi)S(\psi)$

I've tried defining $S(\phi)$ and $S(\psi)$ and multiplying them together to see if I can get something of the form $S(\phi\psi)$, but I'm having big issues with the $\Pi$ symbol. I would like some hints, or if this problem looks familiar in terms of $S$, some general direction.
Edit: Perhaps, is the range of this function $\{1, -1\}$ and how would I go about showing that, if so? I suppose there's a proof by contradiction approach?
Comment: Have a look at https://en.m.wikipedia.org/wiki/Parity_of_a_permutation
Comment: Is $\phi \psi$ meant as composition or pointwise multiplication?
Comment: You can begin by showing a direct equivalent definition of  $S$,  that is $$S(\phi) = \prod_{ \text{ pair }(i,j)\\ \text{ such that }1\le i ,j \le n ; i \ne j  } \dfrac{\phi(i)-\phi(j)}{i-j}  $$
Comment: @ParesseuxNguyen I don't think it is. For $\phi = (1\,2)$ we get $$S(\phi) = \frac{\phi(1)-\phi(2)}{1-2}\cdot \frac{\phi(2)-\phi(1)}{2-1} = (-1)\cdot (-1) = 1$$
and it should be $-1$. The point is that if $i \ne j$, we can take $(i,j)$ or $(j,i)$ in the definition of $S$.
Comment: @mechanodroid: This a product by unordered pair. Not tuple.
Answer: We have
$$S(\phi\psi) = \prod_{i > j} \frac{\phi(\psi(i)) - \phi(\psi(j))}{i-j} = \prod_{i > j} \frac{\phi(\psi(i)) - \phi(\psi(j))}{\psi(i)-\psi(j)} \cdot \prod_{i > j} \frac{\psi(i)-\psi(j)}{i-j} = S(\phi)S(\psi)$$
Indeed, we have
$$\prod_{i > j} \frac{\phi(\psi(i)) - \phi(\psi(j))}{\psi(i)-\psi(j)} = \prod_{i>j} \frac{\phi(i)-\phi(j)}{i-j}$$
because $\psi$ is a bijection. If $\psi(i)>\psi(j)$ then leave the term as it is, and if $\psi(i)<\psi(j)$ we use the fact that
$$\frac{\phi(\psi(i)) - \phi(\psi(j))}{\psi(i)-\psi(j)} = \frac{\phi(\psi(j)) - \phi(\psi(i))}{\psi(j)-\psi(i)}.$$
Comment: I missed that $\psi$ is a bijection! The rest falls out!


Where to use 'GL_EXT_color_buffer_half_float'?

Question: Nowadays, iOS support an extension named 'GL_EXT_color_buffer_half_float', and it can let the half float format accepted by the  parameter of glRenderbufferStorage.
But, in iOS, renderbuffer should be connected to CAEAGLLayer of the view like this:
<code>- (BOOL) renderbufferStorage:(NSUInteger)target fromDrawable:(id)drawable
</code>
and only one renderbuffer can be created for one framebuffer. So, I think I should create another framebuffer to attach a new renderbuffer, and specify the internal format of it for 'half float'. Am I right?
Another question, there is another extension 'OES_texture_half_float' can be used by glTexImage2D, and we already can create half float texture attached to framebuffer directly. It seems that we have no need to render a half float renderbuffer attached to framebuffer. so what is the use scenario of 'GL_EXT_color_buffer_half_float'?
Answer: Renderbuffers do not have to be connected to a CALayer. There are many times where you need to do offscreen rendering of some sort, and having a half-float output type can be useful in some of those cases.
Apple showed one such example in the WWDC 2011 OpenGL ES sessions, where they presented deferred lighting working on an iPad 2. Kearwood Gilbert describes this technique in a blog post here, although with only the standard 8-bit-per-channel color depth. Simon Yeung shows how to do this with half-float targets in his article here.
Personally, I've used it for image processing applications in machine vision. For example, I was recently working on a Hough transform line detector (based on the work of Dubská, et al.) where one of the steps required the detection of local maxima in a parallel coordinate space. Using the standard additive blending to accumulate the Hough transform votes was saturating the 8-bit color channels of my RGBA colorspace, but a half float would give me a lot more dynamic range to pick out true local maxima. Using this greatly reduces the noise in this process (although iOS 6's new framebuffer read operations may let me use a custom blend to encode higher-dynamic-range values in the four color channels).
Rendering to a half-float output does have some performance consequences, but it may be the only practical way to achieve certain effects.
Comment: Thanks for reply. But I still feel puzzled that when Apple introduced this extension in WWDC 2011, they said it could be used in implementing a HDR effect. But in my opinion, if you want to do a HDR effect, you must use the fragment shader to calculate the tonemapping, so you also must use a texture attached from an offscreen framebuffer. No render buffer is needed in this process. Am I right?


With different versions of skates, is it worth getting a better one for an extra 20 dollars?

Question: When I go and buy skates, lets say Bauer supreme there are usually different versions like *Bauer supreme*140 or Bauer supreme 150, 160 etc. The man helping me with my skates said that each one is a little better but is it really worth the extra 20 dollars to get a 140 over a 150? Can someone just tell me the main differences so I can figure out what which version to buy?
Comment: I think you could salvage this question by asking something along the lines of "In general, what features make a skate better as the model numbers increase?"
Comment: We can't answer this question for you - we don't know how significant $20 is to you, and we don't know if a little more performance will make a big difference to whatever you're trying to do on the skates.
Comment: Sorry, I forgot to add that what I needed was something highlighting the main differences.
Comment: Sorry, but [shopping questions aren't something we do either](https://blog.stackoverflow.com/2010/11/qa-is-hard-lets-go-shopping/). Did you consider just asking the guy in the store?
Comment: This question is off-topic because it is a [shopping recommendation](https://blog.stackoverflow.com/2010/11/qa-is-hard-lets-go-shopping/).
Answer: This is not an exhaustive list and I'm not an expert, but, in general:

lower priced models often can't be baked--so will take longer to wear in.
lower priced models have non-replaceable blades, higher priced models can be replaced
the more expensive the model, typically the lighter the overall skate due to lighter weight materials
the more expensive the model, the higher quality materials

We can't tell you which model is right for you. It all depends on your personal preferences, your budget and how much you play.


How to design content for sub-pages

Question: Just looking for more experienced drupal developers to steer me in the right direction, it's kind of a basic question:
What is the best way to design the content of the pages, as in, I have the page templates done (front/sub-pages), now I have a bunch of informational sub-pages that I have to design the content for. I thought I could just populate them using the wysiwyg editor, but starting to realize that has limitations. So what's the protocol?
thanks
Answer: I think you should try Display Suite
Display Suite allows you to take full control over how your content is displayed using a drag and drop interface. Arrange your nodes, views, comments, user data etc.
This is a great tutorial to understand how Display Suite works.
Hope this answer may help you.
Comment: Great, definitely worth exploring more. There's a million ways to do things in Drupal, which sometimes results in too many options!
Answer: If I understand you correctly: change your input type to "Full HTML". Then write your own HTML.
Comment: Thanks for the reply. I suppose what I need is an editor with more HTML options in it. Full HTML still adds tags to the content area. I actually set it on PHP code and that creates a clean output.

How to design content for sub-pages


What is more important, avoiding parallel octaves between non-chord tones, or keeping a stretto exact?

Question: I'm writing a fugue, and I've managed an almost perfect two-voiced stretto. Except that I get parallel octaves between two notes in the figuration. See image, last beat of m. 15.
Which would be considered a greater blemish on my fugue? Keeping the parallel octaves, or breaking the exactness of the stretto? The intended tempo is Moderato, at quarter note = 90, by the way.

Addendum:
Thanks to everyone's kind suggestions I've decided to tinker a bit with the fragment, which now stands thus:
Comment: Shouldn't the stretto part enter a 5th or 4th differing from the dux?
Comment: @AlbrechtHügli: Yes, an ordinary stretto enters at the dominant. But I call any imitation of the subject a stretto, and I wanted the reserve the "normal" stretto for the latter part of the fugue.
Answer: Your passage is entirely musically valid.
You have parallel octaves when you have two notes that are a perfect octave, in the same voice that repeats. This is also true for the unison.
What you have here is one chord that is held for the whole measure and a little floral pattern that moves a bit in the Soprano voice, this is not parallel octaves.
I'm not entirely convinced you can have one chord in a bar and have parallel octaves, you do seem to need two chords. The E - E in the second bar is not in the same voices as the E - E in bar one, so that disqualifies it from being parallel.
What I see here that bothers me is not parallel octaves, I'm seeing that D# in the soprano being lower as the alto note (E) in the second bar. You may want to work on your voice leading as the D# is still going to be fresh in the audience's ears and it can clash.
Comment: I agree this is musically valid. For me the test is whether it sounds right rather than whether it is theoretically correct,
Comment: Thank you for your reply. I was a bit confused whether (in a quasi-baroque style) the rule against consecutive octaves also applies to diminutions, or only to the harmonic "skeleton". You're absolutely right about the voice-overlap; I will correct it by making the E a B.
Answer: The "rule" applies everywhere in that having parallel octaves causes the music to sound like an instrument or voice dropped out. The texture suddenly becomes thin. Similarly for parallel fifths or covered fifths or covered octaves. The effect is strongest between outer voices. Even in pop or country, one tries to avoid parallels between the bass and melody.
In non-polyphonic music, doubling of a line at an octave (or even a fifth) id only a voice thickening or coloring, not a parallel. The rule only applies between independent voices.
Answer: I think this is an nice theme and I wonder how you have been "harmonizing" the previous entries.
I can hear the chord progression I vi IV (ii) V.
In this case you could give the bass line to the 2nd part: e c# a b e  (bar 15) avoiding the dim. 5th parallel (c#-d# and g#-a).
To avoid the octave parallels you could slightly change the  theme (soggetto) in the dux notating the two 16th notes a 3rd up (b c# b). No one will hear the deviation.
Btw.:
What happens with the 4. part?
Comment: So if this bar has only 3 parts " breaking the exactness of the stretto" might be the better solution.
Comment: Hi Albrecht, thanks for your contribution. I wanted to keep the harmony relatively simple, so I harmonized the previous entries according to the Rule of the Octave as I - vii6 - I - ii6, if that means anything to you. This is already the second round of entries (in the dominant), by the way. In this section I stick to a three-part texture, with the 4th part reserved for when I bring in the inverted subject.
Answer: Not commenting on anything else in the music, my first reaction is: the harmonizing voice moves in parallel with the subject, that's a counterpoint/voice leading problem with the harmonizing voice. Change the harmonizing voice(s.)
Being passing tones mitigates the problem somewhat, but the fact they are in the outer voices is a problem.
Sometimes the way out of parallel/direct motions looking for the minimum voice leading change to get another relative motion. In other words, if the harmony is good, keep it and change one of the parts to get contrary or oblique motion. Probably best to keep strong beat harmonies as it and try to make the change on a weak beat (or whatever seems a subordinate harmony.)
wouldn't making the neighboring motion contrary and then delaying the move from G#5 up to B5 work?

...everything seems mostly the same, but the parallel movement is removed.
I suppose this is even the simplest...

...sort of an escape tone from G#5 then up to B5.
I'm not sure I agree with the comment in the accepted answer that the parallel octaves are OK because it's the surface, melodic detail of the harmonic skeleton. I've always had the impression the attitude was the other way around. Skeletal harmony in parallel motion can be glossed over with disguising melodic motion. Here is an example I like from L. Mozart's Nannerl Notenbuch...

...Red highlights the parallel fifths in the harmonic skeleton, blue highlights the "disguising" melodic to intervening thirds. I've seen that kind of thing rather than parallel melodic motion in outer voices.
And of course we aren't talking about instrumental doubling at the octave.
Comment: Thank you for your suggestion Michael! In the end I ended up incorporating your suggestion and then I decomposed the dotted D# in the alto into three eighth notes as seen in my addendum.
Comment: Ah, that's funny! I too played around with the alto `D#/F#` but for the sake of the revision exercise I thought it better to keep to a minimal change.
Comment: Just wanted to mention the detail that escape tones very rarely leap up.  The vast majority of the time, they leap down by 3rd, occasionally by 4th.  Upward escape tone leaps are rare enough to say "avoid" if you want to write in strict counterpoint in classical style.  (Not that composers never did this; it's just pretty rare.)  All of that said, assuming this fugue is for one instrument (like keyboard), the potentially rare leap from a dissonance is mitigated by the fact that the F# sounds like it might connect to the E in the middle voice on the next beat (and is thus a quasi passing tone).


Views Exposed filter Multiple times on a Page Or Different id for views exposed filter if added one more time

Question: I added a views exposed filter to block and I want to show the block multiple times on the dashboard page each can have different choices. Can it possible without adding any other display?
Or Can it be possible to change the make the id unique for each occurrences of same exposed filter?
My Actual Need is :
I am using Homebox module for creating a Dashboard for user. I created a view with block display so user can add it in their Dashboard multiple times. I added the Exposed filter of taxonomy terms and I entered the choices of user in my custom table. Now user can add same block with different choices. My questions is how to manage different choices with blocks,because exposed filter have same form id on each occurrences.
Comment: Hi ; I don't quite understand well. Can we say you need to filter several views by one unique exposed filter ?
Comment: No, I need to same view multiple times on a page having exposed filter. I added remember last choice in views expose filter. If I added it multiple times on my dashboard page, and select any choices then it changes in all block of same type. But I don't want to change in all block.
Comment: Similar: http://drupal.stackexchange.com/questions/3827/multiple-copies-of-views-filter-form-exposed-filters
Answer: While adding a filter there is a dropdown at the top as 'For', by default 'All displays' are selected, by selecting the specific block that particular filter will be displayed on selected block only. Please try and let me know if it worked.
Comment: I didn't found any option?
Comment: And also I am using only one display. So there is no need of that option as you said.
Comment: you are right, if the same block is being duplicated on the homebox. I am unsure about this doing using the frontend configurations. May be some php patches could do this for you based on the specific form ID.
Comment: Yeah but I didn't found any `patches` for it and I am not so expert to create a `patch` for `views`.


iText PdfAcroForm GetAcroForm not applicable for the types given

Question: I haven't been programming for a long time, and have never used the iText library before - I am sure that this will be a simple problem that I just do not understand correctly. I am trying to get the PdfAcroForm from a PdfDocument instance called 'pdf'. Here is the code I am trying to run:
import com.itextpdf.kernel.pdf.*
import com.itextpdf.kernel.pdf.PdfDocument
import com.itextpdf.forms.*
import com.itextpdf.forms.fields.PdfFormField
import com.itextpdf.forms.PdfAcroForm

//Initialize PDF document
PdfDocument pdf = new PdfDocument(new PdfReader("C:/Users/Andy/Desktop/VA_Form.pdf"), new PdfWriter("C:/Users/Andy/Desktop/New_VA_Form.pdf"));

PdfAcroForm form = PdfAcroForm.GetAcroForm(pdf,true);
//Map<String, PdfFormField> fields = form.GetFormFields();

This is returning the error:
groovy.lang.MissingMethodException: No signature of method: static com.itextpdf.forms.PdfAcroForm.GetAcroForm() is applicable for argument types: (com.itextpdf.kernel.pdf.PdfDocument, java.lang.Boolean) values: [com.itextpdf.kernel.pdf.PdfDocument@101978d4, true]
Possible solutions: getAcroForm(com.itextpdf.kernel.pdf.PdfDocument, boolean), getXfaForm()

I cannot determine whether I have not created a PdfDocument correctly, or whether I am just making a mistake with how to get the AcroForm from this PdfDocument? Any help is much appreciated.
Answer: The first "possible solution" in the error message most likely is the solution, iText PdfAcroForm has a method:
getAcroForm(com.itextpdf.kernel.pdf.PdfDocument, boolean)

but you used:
PdfAcroForm form = PdfAcroForm.GetAcroForm(pdf,true);

I.e. the initial 'g' in the method name has to be lowercase, not uppercase.
Comment: Thanks @mkl, I had tried that before but had discounted it due to getting a new error message `Script1.groovy: 1: unable to resolve class com.itextpdf.kernel.pdf.PdfDocument
 @ line 1, column 1.` which I was unsure of as well. Thank you for your help - do you know what the new error means?
Comment: Sorry ignore the last comment, I was having problems with the ScriptMaster for Filemaker file recognising new jar files that I added. Thanks again


Compressive Sensing matrix

Question: I am working with compressive sensing recovery with image and I test with various sensing matrices:
Case 1: Sensing matrix A of size MxN is i.i.d Gaussian matrix.
Case 2: Sensing matrix A is size of MxN is DCT matrix (it means that I pick up M rows from an NxN DCT matrix).
I see that the case 2 gives better reconstructed images than case 1 (I used total variation for recovery).
I try to search this scenario, and really that no one uses an DCT base as a sensing matrix.
Could you explain why?
Thank you very much.
Comment: What makes a sensing matrix good is application specific, so there very well could be cases out there where the DCT is used and gives good performance. However, in general I suspect that the DCT concentrates too much energy into too few samples so that when you randomly sample it, the likelihood is too high that you miss nearly all of the signal's energy. The rule of thumb is that you want the sensing matrix to spread the signal's energy around equally so that regardless of which samples the subset you choose contains, they will have enough information to reconstruct the signal.
Comment: Let see my test:
Answer: Let see my test: an image denote x, and its measurement y is sensed by:
y=Ax;
Now, we have two case:
 case 1: A is Gaussian matrix;
 case  2: A is DCT matrix.
Note that in some papers, The acquisition base $\Phi =A\Psi $; however, prof. Romberg states that $\Psi$ can be moved to the decoder for a simpler encoder. It means that image x is directly sensed by the sensing matrix A.
I don't know why the sensing matrix generated by DCT matrix is better than Gaussian matrix. :(
Comment: This doesn't add any information about your question. You need to look at what each sensing matrix is actually sensing.
Answer: Because you are comparing apples and oranges. In the Gaussian case, you are expecting the image to be sparse in the Haar basis, whereas in the DCT case, you are expecting the gradient of the image to be sparse in the DCT basis.

Compressive Sensing matrix


Ordenar 2 arrays com diferentes tamanhos em jQuery

Question: Estou com o seguinte problema, no meu cenário estou capturando os Ids de um checkbox, possuo uma lista de objetos JSON onde preciso comparar esses Ids com os Ids da lista de objetos JSON. O problema é que eles possuem tamanhos diferentes.
Meu Código
var obj = [
                    { "Id": 1, "Nome": "José" },
                    { "Id": 2, "Nome": "João"},
            { "Id": 3, "Nome": "Maria"}
            ];

var ids = [1, 2];

var j = 0;

var usuarios = [];

for(var i = 0; i < obj.lenght; i++){

  j++;

    if(obj[i].Id == ids[j]){

    usuarios.push(obj[i]);

  }

}

console.log(usuarios);

Answer: Deveria percorrer a array ids[] e verificar se no JSON existe ocorrência em que a chave Id possui o valor de cada item da array. Pode usar o método .filter() e verificar os dados:

var obj = [
{ "Id": 1, "Nome": "José" },
{ "Id": 2, "Nome": "João"},
{ "Id": 3, "Nome": "Maria"}
];

var ids = [1, 2, 4];

var usuarios = [];

for(var i = 0; i < ids.length; i++){

   obj.filter(function(a){
      if(a.Id == ids[i]){
         usuarios.push(a);
      }
   });

}

console.log(usuarios);

Outra forma é fazer o contrário usando .indexOf(), sem precisar iterar a array com for:

var obj = [
{ "Id": 1, "Nome": "José" },
{ "Id": 2, "Nome": "João"},
{ "Id": 3, "Nome": "Maria"}
];

var ids = [1, 3, 4];

var j = 0;

var usuarios = [];

obj.filter(function(a){
   verifica se o valor da chave Id existe na array
   if(~ids.indexOf(a.Id)){
      usuarios.push(a);
   }
});

console.log(usuarios);
Comment: Vlw, ajudou muito.
Comment: Blz... adicionei uma segunda solução que achei até melhor.


Span a particular word in android

Question: Hello All

In my android project i would like to display a particular word say TRIAL in string This is for my Trial.This Trial is just for fun.
How can achieve this in android.
I tried using below code which will format only the string from 15 to 30.
TextView TV = (TextView)findViewById(R.id.mytextview01);
Spannable WordtoSpan = new   SpannableString("I know just how to whisper, And I know    just how to cry,I know just where to find the answers");
 WordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 15, 30,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
 TV.setText(WordtoSpan);

Please let me know if i could do this in android.
Please forward your valuable suggestions.
Thanks in advance :)
Comment: I don´t get what you´re trying to do
Comment: I would like to give the user a facility like if there is a lengthy text and he needs to find some text in that,the particular search text should be in red while rest in black :)
Answer: Try using the indexOf(String str) method in the String class. That'll give you the first occurence of the word you're searching for in your Spannable (which's an extended String). Then you can apply your Color-span accordingly.
Answer: Expanding a bit on Scythe's answer, replace them all with:
public class Junk extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        TextView tv = (TextView) findViewById(R.id.textView1);
        String tvText = "This is for my Trial.This Trial is just for fun. Just a Trial";
        tvText+="A Trial. Only a Trial. It's a Trial";
        String lookFor = "Trial";
        tv.setText(formatString(tvText, lookFor));
    }

    private Spannable formatString(String targetStr, String lookFor) {

        Spannable spanString = null;
        spanString = new SpannableString(targetStr);
        int fromIndex, startSpan, endSpan;

        fromIndex = 0;
        while (fromIndex < (targetStr.length() - 1)) {
            startSpan = targetStr.indexOf(lookFor, fromIndex);
            if (startSpan == -1)
                break;
            endSpan = startSpan + lookFor.length();
            spanString.setSpan(new ForegroundColorSpan(Color.BLUE), startSpan,
                    endSpan, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            fromIndex = endSpan;
        }
        return spanString;
    }
}

.
Comment: In this case, if you loop to `targetStr.length() - 1` you exclude last character.

Span a particular word in android


Drupal 8 Customize CKEditor Format Options

Question: Drupal 8.4.x
I am trying to add custom formats to the ckeditor dropdown.
Having the Geshi Filter module installed it would be nice to have the tags associated with the different languages available as a format option for users.
Following a reply here: https://drupal.stackexchange.com/a/244331/79805, I have success adding the "div" tag, but seem unable to add anything else like a "css" tag or even a "span" tag.
Is it possible to add custom tags to the format list?
This is the function running right now from user @rémy:
function ckeditor_add_format_tags_editor_js_settings_alter(array &$settings) {

    foreach (array_keys($settings['editor']['formats']) as $text_format_id) {
        if ($settings['editor']['formats'][$text_format_id]['editor'] === 'ckeditor') {
            $settings['editor']['formats'][$text_format_id]['editorSettings']['format_tags'] .= ";div";
        }
    }

}

Answer: CKEditor's format drop down is intended for block-level elements only. So e.g. for headlines, divs, blockquotes, paragraphs and so on.
Inline-elements as spans, links (in CKEditor inline elements by default, even HTML5 specs state they can wrap block elements), i, b, strong, em and so on will have to use the styles drop down.
The css tag is neither block nor inline element, and you'd have to define it as custom block element first.
You can let CKEditor know about your block-level elements by extending the dtd setting, but this exceeds the scope of the Drupal Answers group, even Drupal 8 is using CKEditor by default. Please refer to the CKEditor docs for more information.
For your very special use case, I do have a suggestion:
In one of our projects, we have been using the GeSHi filter module in conjunction with the codesnippet module and added a text filter module codesnippet_geshifilter that "translates" codesnippet markup to GeSHi filter compatible markup.
The intention was to have JavaScript based syntax highlighting while editing the source code, but render pages with server-side generated GeSHi highlighting.
It works well for code blocks. There are some flaws with inline code however. These require tweaking the available CKEditor styles drop down.


Different scales for chords and melody

Question: I haven't had any real education in MT so I might ask the wrong questions or my confusion might be based on lack of fundaments so please bare with me and I will try to explain.
Starting to learn MT and harmony I've been only familiar with music that is based on one scale from where most of the chords are taken from and the same scale is also used for the melody and sólo. Of course I understand that non diatonic chords and notes can sound great at the right moment.
But then I seem to encounter exceptions to this that sounds amazing. But I'd like some explanation on how this works. These are some of the things I've encountered if I've understood them correctly.
In jazz improvisation it seems that each chord can be understood as a whole scale and the improvisation solo will change scale for each chord. So the i guess that song is not said to be played in a certain one scale?
I realised blues can be played with a scale more like the minor for the solo but the chords accompaniment being in the mayor scale? Is this correct?
Same seems to go for klesmer music using the freygish scale for playing solo but often when I see instructions for a backing track the chord seem to be from a normal minor scale?
Comment: If by "chord" you mean the chord symbols written in a lead sheet, or agreed on by the players, then an improviser can modify the scale several times even inside each chord. Think of a song that has "Cm" written for 32 bars. The question is, what can I make this Cm be, how can I mold the harmony.
Comment: Sounds like you've never heard of the [chord-scale system](https://en.wikipedia.org/wiki/Chord-scale_system). Granted, I can't get behind some of its more outlandish scale suggestions.
Answer: It would help if you have an example of a song.  Otherwise you will get some vague abstract answers.  Like the one I'm about to write.
First of all songs are often played on one scale.  Just because you learned that some other scale matches this or that chord does not mean that the simple Major scale will not work.
There are several items at play here.

Often music changes key.  One of the most common cord changes in Western classical music is I --> IV and I--> V, and reversed, IV-->I and V-->I, and any combination of movements within the set {I, IV, V}.  These are major chords on the root, 4th and 5th degree of the Major scale.  One can play the IV or V chord without changing key, but it sound very cool if you do change key.  To that end when classical (and jazz) pieces move from the I chord to the IV chord they will often add an accidental in the original key, i.e. a flat 7th.  As an example, a song in the key of C maj modulates to F maj by making B flat in the C major scale.  The reason I point this out is that if you think of the song as being in C then you have "out of tune notes that work".  But if you think of the song as modulating then all you did was play the melody in a new major scale.  The scales that start on the 1, 4, and 5 of any key share 6 out of 7 notes and are called compatible keys in Western music.

Along the lines of the above sometimes a composer or arranger will add many chords in the circle of 5ths or the circle progression to prepare the ear for the key change.  In Jazz this is most common and one sees an abundance of ii-->V-->I progressions where the I could be any chord in the original key, major or minor.  This always sound good because if focuses the ear to hearing resolutions to each chord in the original song.  To better understand this you need to learn about the perfect authentic and plagal cadences in Western music.  Suffice to say the inclusion of these extra chords has "meaning" in a classical sense because they are leading somewhere, yet they may all be outside the original key of the song.

Another trick in play involves chord substitutions, specifically the tritone or flat 5 substitution.  This type of substitution creates a chromatic chord progression that works but is "out of key" relative to the original chord.  This idea works because the two chords share enough common tones that have the correct movement that one hears good harmony.

Keep in mind that a single chord can belong to more than one key and more than one scale.  Some very exotic that don't even exist in classical western music.  A Jazz standard might be written on the Major scale but once a player begins soloing they might want to walk away from that template to create really exotic ethnic sounds.  This does not mean that the original song was somehow NOT in the major scale.  We take liberties to create more ideas than traditional theory would support.

One of the key ideas that is expression in some of the above items on the list is leading tones.  When we alter chords or add out of tune notes they aren't random.  They are usually inserted to strengthen resolutions, and these have semitones like 7-->8, 4--3.  In the case of the b5 sub you also have b2-->1.

The idea that chords have corresponding scales is somewhat artificial.  It has value and is a valuable way to connect melody lines to chords but it's not a foolproof algorithm to understanding improv or chord-melody relationships.  Sometimes things just work because they sound good.  Western music theory describes a small subset of things that sound good but is not necessarily the standard against which all other things should be compared.  Rather than asking "why does the blues work when there are notes that don't match the chord" one could ask "how is it than classical music sound good when they never use blue notes".
Answer: Whether a piece has chords (and associated scales) that all fit one pitch set, or whether each chord takes us into a quite different territory, there's one point that I think might have escaped you.
The notes of the chord or the 'scale of the chord' are a framework, not a restriction. Other notes may be (and frequently are) played.  A simple example is a 'blue' minor 3rd played along with a major triad.  Sometimes these out-of-scale notes (I won't say 'wrong' notes) are just decoration.  Sometimes they are used systematically to give a new flavour to the basic harmony.
Sometimes it's useful to think of the 'scale of the chord' as having different notes in the second octave to the first.
It's also useful to remember that while jazz is great, most music is not improvised over a chord sequence.  It's very specifically composed and orchestrated.  For some really wild stuff, look at how great composers from Bach to John Williams (to pick just two) constructed their music.
Answer: It's like just about everything we learn from scratch. In maths, we learn early on that we can't take 5 from 3. At that point, it's all we need to know. Negative numbers don't need to exist till later!
Music theory starts with diatonics, and the more simple songs that use them. Harmony based on that is a very good start point. If we didn't follow on with more maths studies, we might well not consider negative numbers!
Imagine being told in early music theory that any note can and will fit with any harmony (as it can and does). Not sure where that would leave us, except trying blindly (deafly?) to sort out music with no boundaries. So, we start with the more simplistic, easier to comprehend, 'facts'. And it would seem, from reading so many questions on this site, that that's about as far as it went. 'I learned about that, so it should apply to just about everything.'
That certainly was not a rant - just an observation.
Now - watching a film in monochrome (b&w) that suddenly changes to colour is a lovely experience. Analogy to that - a diatonic piece changing with some chromaticism. Literally as well as physically. And that's where your second paragraph comes from. Using notes/harmonies other than the diatonic ones make a piece more interesting. Those seven notes work well together, but suddenly there's something we maybe weren't expecting thrown into the mix. And why not? Certainly not 'cos theory says not!
On the jazz theory: some say each chord can begat its own scale, or set of notes. It's how a lot of us think, on occasions. It's a formula that's been proved to work, so why not?
On Blues: true, there are 'special scales' that are used in Blues - major and minor Blues scales - better players will not just stick to minor , over the commonly found major (or 7th) chords. Counting up the available notes, then, I think there are only two that won't be included. And I know at least when I play Blues, those two also come out to play!
So, to sum up, as I say to students (eventually!) 'any note, anywhere, in any key, can and will fit - if you know what you're doing'. Continue with your journey through music theory, and it will become more apparent, the more you delve!
Comment: "we can't take 5 from 3"... oh, how I hated it as a kid. Then you'd watch the news and they would say that the temperature was "2 below 0" degrees. After my mum explained what "below 0" was, next time I was asked to take 5 from 3 I replied "2 below 0". I was not popular with primary school teachers...
Comment: @mkorman - true! My reply was always 'try taking 5 sweets from someone who only has 3 then...' I was one of those teachers! But nobo dylike sa smar tarse...  (It's a motto).
Answer:
In jazz improvisation it seems that each chord can be understood as a
whole scale and the improvisation solo will change scale for each
chord. So the i guess that song is not said to be played in a certain
one scale?

Yes, you can improvise with the tones of the scale of the any chord of the lead sheet.

I realised blues can be played with a scale more like the minor for
the solo but the chords accompaniment being in the mayor scale? Is
this correct?

This is correct: you can use the notes of the parallel key (e.g. A => a-minor) and get
a bluesy sound.

Same seems to go for klesmer music using the freygish scale for
playing solo but often when I see instructions for a backing track the
chord seem to be from a normal minor scale?

Do you mean Phrygian?
All the modes contain the same tone reservoir of la ti do re mi fa so but they just start with another root tone. Aeolian = la, Dorian = Re, Phrygian = Mi etc. That's why you all tones will fit for the improvisation, but you must be aware what tone is the root tone, because this will have an influence  on the improvisation motifs.
Comment: Freygish scale, like Klezmer, ex. Hava Nagila.
Answer:
I've been only familiar with music that is based on one scale

Aside from folk and nursery tunes most music doesn't work that way. Two technical terms to learn are modulation and tonicization. Both are about temporary key changes, but modulations are relatively long, like a whole phrase or section, tonicizations can be as brief as two chords. Terminology aside even very short pieces usually have some kind of move to a new key/tonal center.

In jazz improvisation it seems that each chord can be understood as a whole scale...song is not said to be played in a certain one scale?

That is the "chord scale system." It's a teaching method. Historically jazz musicians didn't not use that. It was a teach method developed in the 1970's. The fact that many songs are not confined to a single scale is not a result of the chord scale system. That system provides no real insight to understanding tonality. Songs are not confined to one scale, because it is normal for songs to move in and out of different keys/tonal centers.

I realised blues can be played with a scale more like the minor for the solo but the chords accompaniment being in the mayor scale? Is this correct? Same seems to go for klesmer music using the freygish scale for playing solo but often when I see instructions for a backing track the chord seem to be from a normal minor scale?

Yes. The theoretical explanation is the basic tonal structure comes from the chord roots and the primary degrees of the tonic, subdominant and dominant, while the tonal or modal "color" comes from other harmonic tones, the thirds and sevenths of chords or the modal scale degrees. That's a lot of technical jargon. It's easier to simply describe the practice. For example, a basic blues sound is accompaniment with all dominant seventh chords on I IV V with melody based on minor pentatonic/minor blues scale.
The main thing to say is music which deviates from purely diatonic is not unusual. Chromatic chords, clashing tones like in the blues, etc. Those things are normal within various harmonic styles.
Comment: When saying based on one scale I meant that accompaniment and melody are in the same scale and key. I do know about modulation.
Comment: When people using wording like "from the scale" instead of "tonality" or conflating "scale" and "key" it's hard to tell what they are thinking, especially because of the chord-scale-system which IMO makes a mess of things.

Different scales for chords and melody


How to change Taxonomy admin page title?

Question: I simply need to change the title on the (Drupal 8.8.4) administrative page which lists the existing vocabularies.
As far as I know/read, the routing.yml should be modified, shouldn't it?  (Is only the *defaults_title parameter that needs to be changed?)
Inside the taxonomy.routing.yml file, I only get the form routes for taxonomy term, if I am correct.
Do I need to modify the route elsewhere?
I have tried with the system.routing.yml file, listing many administrative routes (I thought it was the jackpot) but there is no route for the taxonomy page.
Could someone tell me where to go and which static route to change?
Related questions

How do I set the page title?
How to set admin theme for a route?
Comment: What exactly didn't work with the related questions you linked?
Comment: Me :) Actually, examples are nice but I could not figure which entity name, which parameters, etc. I have to work with for Taxonomy page routing. If I could find the code to modify, it would be a start for me. Even if I am more a site builder.
Answer:
Could someone tell me where to go and which static route to change?

It's not a static route.  Like other entity collection routes, it is built with the aid of the comment annotations above the Vocabulary entity class.  VocabularyRouteProvider also comes into play, and it sets a _title_callback into TaxonomyController::vocabularyTitle for good measure.
At any rate, this is all a bit moot because you don't want to go modifying core files, because then when you update core you will have to patch them all over again.  Very tedious.  Instead you could implement your own RouteSubscriberBase::alterRoutes.
Answer: Maybe start with https://drupal.stackexchange.com/a/232783/15055, just implement the preprocess page title hook (without the code inside for now) in a custom module or a custom theme.
Then install the Devel sub-module Kint. And put ksm(\Drupal::routeMatch()->getRouteName()); inside this hook. Note, in the hook name replace MYMODULE with your custom module's or theme's machine name.
Then visit the page you want to override the page title from and flush the caches a few times. It now should tell you the name of the route.
Then use this name to build an if-request checking the route's name and replace $variables['title'] with your new title.
/**
 * Implements hook_preprocess_HOOK().
 */
function MYMODULE_preprocess_page_title(&$variables) {
  // ksm(\Drupal::routeMatch()->getRouteName());
  if (\Drupal::routeMatch()->getRouteName() === 'foo.bar.foobar') {
    $variables['title'] = t('My new English title');
  }
}

In the end you could to the same with hook_preprocess_html to replace the meta title by overriding $variables['head_title']['title'] in there.
Comment: @Toki – Kint is THE tool for debugging. It'll probably help you a lot in the future. As a side builder now doing the step to start using hooks. Kint can also be used in templates. With Twig debugging enabled simply put `{{ kint() }}` and it will tell you what variables and methods you can use in there; and then send new custom variables over to the template using preprocess functions. Have fun!
Comment: Thanks, it works like a charm. I have edited my question to detail your answer, please review if needed.


Alexandroff compactification question

Question: If $X$ is a locally compact and metrizable space such that its Alexandroff compactification is not first countable. Does this imply that no other compactification of $X$ can be first countable? Why?
Comment: The only extra info on $X$ you have is that it is not separable. Any metrizable $X$ has a metrizable compactification iff it is separable (for $X$ locally compact the Aleksandrov one will do, non-separable spaces will have others). So the question comes down to: does a non-separable metrizable space have a first countable compactification?
Answer: There can be locally-compact metrizable spaces with non-first-countable Alexandroff compactifications but with other first-countable compactifications.
This follows from a theorem of Banakh and Leiderman in "Uniform Eberlein compactifications of metrizable spaces" which states that a metrizable space $X$ has a first-countable uniform Eberlein compactification if and only if $|X|\leq\mathfrak{c}$.
This implies that the discrete space on $\omega_1$ (which is trivially locally-compact and metrizable) has a first-countable compactification.  But the Alexandroff compactification is not first-countable, since the open subsets of the "point at infinity" consist of all co-finite subsets of $\omega_1$ and any (sub-)basis must be uncountable.

Alexandroff compactification question


Sort chat conversation in Pandas

Question: I have a dataset of chat conversations that looks like this (where the message_id is an index for all of the messages in the database).:
| message_id | to_user | from_user | message      |
|------------|---------|-----------|--------------|
| 123        | al      | sal       | hi           |
| 871        | al      | hal       | hey          |
| 989        | al      | bob       | me too       |
| 900        | sal     | sal       | hello        |
| 107        | bob     | al        | i'm bob      |
| 242        | sal     | al        | how are you? |
| 101        | al      | bob       | hi, i'm al   |
| 898        | sal     | al        | i'm good     |

What I want to do is sort this table to reflect a conversation between two people. So it would first group all of the conversations from to_user and each from_user that they chatted with, and then for each conversation between a to_user and from_user sort them by their message_id so it would reflect the back and forth conversation.
| message_id | to_user | from_user | message      |
|------------|---------|-----------|--------------|
| 101        | al      | bob       | hi, i'm al   |
| 107        | bob     | al        | i'm bob      |
| 989        | al      | bob       | me too       |
| 123        | al      | sal       | hi           |
| 242        | sal     | al        | how are you? |
| 871        | al      | sal       | hey          |
| 898        | sal     | al        | i'm good     |
| 900        | sal     | al        | hello        |

How would I accomplish this in Pandas?
Answer: We can use np.sort to sort values across rows so that we have columns that specify the participants, but not direction, then sort by conversation and message id with DataFrame.sort_values:
df[['person_a', 'person_b']] = np.sort(df[['to_user', 'from_user']])
df = df.sort_values(['message_id', 'person_a', 'person_b'], ignore_index=True)

   message_id to_user from_user       message person_a person_b
0         101      al       bob    hi, i'm al       al      bob
1         107     bob        al       i'm bob       al      bob
2         989      al       bob        me too       al      bob
3         123      al       sal            hi       al      sal
4         242     sal        al  how are you?       al      sal
5         871      al       sal           hey       al      sal
6         898     sal        al      i'm good       al      sal
7         900     sal        al         hello       al      sal

We can drop these additional columns after we're done with them:
df[['person_a', 'person_b']] = np.sort(df[['to_user', 'from_user']])
df = df.sort_values(
    ['message_id', 'person_a', 'person_b'], ignore_index=True
).drop(columns=['person_a', 'person_b'])

df:
   message_id to_user from_user       message
0         101      al       bob    hi, i'm al
1         107     bob        al       i'm bob
2         989      al       bob        me too
3         123      al       sal            hi
4         242     sal        al  how are you?
5         871      al       sal           hey
6         898     sal        al      i'm good
7         900     sal        al         hello

Setup and imports (edited to match output):
import numpy as np
import pandas as pd

df = pd.DataFrame({
    'message_id': [123, 871, 989, 900, 107, 242, 101, 898],
    'to_user': ['al', 'al', 'al', 'sal', 'bob', 'sal', 'al', 'sal'],
    'from_user': ['sal', 'sal', 'bob', 'al', 'al', 'al', 'bob', 'al'],
    'message': ['hi', 'hey', 'me too', 'hello', "i'm bob", 'how are you?',
                "hi, i'm al", "i'm good"]
})

Comment: Thanks for this! I'm getting the following error for the line: `df[['person_a', 'person_b']] = np.sort(df[['to_user', 'from_user']])`
error:`KeyError: "None of [Index(['person_a', 'person_b'], dtype='object')] are in the [columns]"
`
Comment: Hm... that's odd. `['person_a', 'person_b']` is a list. Not an index. Also that's assignment not selection.... so it wouldn't do a column check.

Sort chat conversation in Pandas