How can I prove the existence of delta-incomplete / countable incomplete ultrafilters?

Question: I am reading a W.A.J Luxemburg paper about nonstandard analysis (https://www.jstor.org/stable/3038221). He presents the following definition

I am stuck trying to prove the existence of delta-incomplete ultrafilters. I suppose I have to construct a chain of filters over an infinite set with a certain condition such that, at the moment of using Zorn's lemma, the maximal satisfies the definition of delta-incomplete.
I have this, and I am more confused as how can I proceed.
Let $\mathcal{C}$ be a chain of filters over a set $I$ with a maximal $\mathscr{U}$ such that $\mathscr{U}$ is a $\delta$-incomplete ultrafilter. That is, there exists $\{I_n\}_{n\in\mathbb{N}}$, a countable partition of $I$ such that, for all $n$, $I_n \not\in \mathscr{U}$. So, we would have that same property for all $F \in\mathcal{C}$. If some $I_n\in F$ then $I_n\in\mathscr{U}$. that leads to $\mathcal{C} = \{\mathscr{U}\}$.
Comment: Did you try to look up Luxemburg's reference [6]?
Comment: I can't find it, either is like 3 pages of the full paper with no information about filters or there is a physical book in another country.
Answer: You don't need Zorn's lemma for this.  The ultrafilter lemma is sufficient.
Let $X$ be an infinite set and $X=\cup_{n\in\Bbb{N}} U_n$ a partition of $X$ into non-empty mutually disjoint subsets.  Let
$$\mathcal{A} = \{U_n:n\in\Bbb{N}\}\cup\{S\subseteq X: S\text{ is finite}\}$$
and
$$\mathcal{B} = \{X\setminus S: S\in \mathcal{A}\}$$
We show that $\mathcal{B}$ is a filter-subbase.  Therefore $\mathcal{B}$ generates a filter $\mathcal{F}$, and $\mathcal{F}$ is contained in an ultrafilter $\mathcal{U}$ by the ultrafilter lemma.  Then by definition for all $n\in\Bbb{N}$, $X\setminus U_n\in\mathcal{U}$ but $\cap_{n\in\Bbb{N}} (X\setminus U_n) = X\setminus(\cup_{n\in\Bbb{N}}U_n) = \emptyset$.
So let $I\subseteq \Bbb{N}$ be a finite set and $F\subseteq X$ a finite set.  Then
$$\cap_{i\in I}(X\setminus U_i) \cap (X\setminus F) = X\setminus (\cup_{i\in I}U_i \cup F)\tag{1}$$
However, note that $\Bbb{N}\setminus I$ is infinite, and since each $U_i$ is nonempty and they're mutually disjoint, $\cup_{i\in \Bbb{N}\setminus I}U_i$ is an infinite subset of $X$.  Since $F$ is finite, it follows that $\cup_{i\in I}U_i \cup F$ is not all of $X$, so the right hand side of $(1)$ is non-empty.  This shows the collection $\mathcal{B}$ is a filter-subbase as required.$\Box$


Seletor de classe no CSS

Question: Não estou conseguindo fazer referência a uma
, que está no meu arquivo index.html, através do meu arquivo .css.
Tenho a seguinte estrutura no meu arquivo index.html:

Endereço 1

Endereço 1

Estou tentando fazer referência à
, porém, os ajustes que estou fazendo no arquivo .css não estão sendo aplicados a esta div.
A referência no meu arquivo .css é dada por:
.div-address{
  border: 1px solid;
  font-family: 'Boogaloo', cursive;
}

Esta estrutura está implementada logo abaixo da estrutura definida no arquivo .css. Fiz isso pensando que meu estilo poderia sobrescrever algum estilo já existente na estrutura CSS do Bootstrap.
NOTA:

Estou usando o framework Bootstrap
A estrutura de arquivo está correta (index.html, pasta css, pasta js etc.)
Na primeira linha do meu arquivo .css estou importando a font utilizada para o div (@import url("https://fonts.googleapis.com/css?family=Boogaloo|Yesteryear");)

Quando eu coloco o estilo ".div-address" no meu arquivo index.html, o estilo é implementado corretamente na div. Devo estar cometendo algum erro quando à referência de classes no CSS ou algo está sobrescrevendo meu estilo criado no arquivo .css.
Bom, ainda sou novato em desenvolvimento Web e peço a ajuda dos senhores para solucionar este problema.
Obrigado.
Comment: Estás a incluir esse arquivo `.css` na página com `<link rel="stylesheet" type="text/css" href="etc...`?
Comment: Olá @Sergio, estou sim "". Minha estrutura de arquivos está correta. Digo isso porque consegui implementar alguns ajustes através do arquivo .css.
Comment: Ok, então estás a mudar o ficheiro do boostrap diretamente/manualmente? ele é estático ou é compilado? tipo de less para css ou stylus para css?
Comment: Olá @Samir, estou implementando meus estilo após todos os estilos definidos no arquivo .css.
Comment: @SamirBraga , quais referências? Poderia ser mais específico? Eu ainda sou novato nesse assunto.
Comment: Seria minha tag `head`? Se for, segue: `
`
Comment: `
`
Answer: Acho que o melhor seria colocar todos seus estilos que não façam parte do Bootstrap em um arquivo diferente, e lincá-lo após todos os links css. Tal como:
<link href="css/bootstrap.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"

<link href="css/meu-arquivo-de-estilo.css" rel="stylesheet">

Comment: Entendi, não sabia que dava pra fazer isso. Acredito que deva funcionar. Vou tentar aqui e já respondo. Obrigado!
Comment: Funcionou @Samir, muito obrigado! Gostaria de saber apenas se essa é uma boa prática? Perco em desemprenho se eu implementar esta estrutura com mais de um arquivo CSS? Percebi que o meu arquivo pessoal herdou do arquivo css do Bootstrap. Acredito que seja pelo falo de ter sido declarado após o link do css do bootstrap. Mais uma vez obrigado!
Comment: @HudsonRodrigues, isso depende de algumas coisas, do tamanho do arquivo, de como as regras são sobrepostas, etc. Sugiro que pesquise sobre performance front-end, é um assunto muito interessante e útil :).

Seletor de classe no CSS


Multicast between kubernetes pods

Question: I have an app in which there are a few tasks that communicate using publisher/subscriber. The main problem is that the pub/sub discovery works by multicasting information to the other tasks, but when I deploy those tasks in k8s, the pods can't multicast between them as they have private IPs assigned.
I have read about using services, but it didn't convince me because I would lose the peer to peer structure.
Is there a way to enable 2 pods from the same cluster to see each other using multicast?
For additional info, the pub/sub I am using is Zenoh.
Comment: You'll probably want to investigate tools like Multus ( https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/docs/quickstart.md ).
Answer: Thanks to SYN comment I have been able to find a way. If you use microK8s distribution is quite straightforward, this link contains a good guide: https://microk8s.io/docs/addon-multus.
It is also supposed to be possible with K3s by installing flannel and then multus, but I haven't tried it so I can't assure it.
Comment: Would you mind to share multus config that you used? I've got a similar task, but for the loopback interface only - I suspect I will need to go the Multus path as well, and probably there will be similarities between setting up multicast for the whole network and just for loopback. Here are details of my task: https://serverfault.com/q/1114351 Thanks!
Comment: @Mikha For the network attachment definition I've used the one in the microk8s link. For the pod deployment file I've used the net configuration in the example, didn't configure much more than the name of the network.

Multicast between kubernetes pods


Rails 4 custom admin backend

Question: I'm wanting to create an admin backend for a practice app. After reading around I've come to a general idea of what to do but would like some clarification:

Use namespace to route the backend at example.com/admin...
Put any adminifiable resources inside namespace e.g resources :posts
At this point do I duplicate the normal (public facing) controllers and put them into the admin directory? (Along with CRUD views)
In theory the public facing controllers only need index and show actions, right? As new/create/update/destroy will only be accessed in the admin/controller.

Any clarification or advice is greatly appreciated. Just trying to wrap my head around this.
Answer: I would recommend against duplicating your controllers, or any part of your application for that matter. That goes entirely against the DRY principle, which stands for "Don't Repeat Yourself." Duplicate code becomes really hard to maintain and test as your application grows.
Instead, I would recommend limiting access to certain actions using before filters. For example, let's say that you want users to be able to create posts, read posts and see listings of posts. In your PostsController, you can have something like this:
before_action :admin_user?, only: [:edit, :destroy]

Note: before_action is just the new name for before_filters.
So then actions like index would execute normally for all users, but if a user calls the destroy action, the controller would first check to see if the user is an admin, by calling an admin_user? method (typically defined in ApplicationController). This method could be a simple conditional, like "if the user is not an admin, flash an error message and redirect them back to where they were before the request" and then use it to protect any action or resource you want. You could also use it in the views to show delete buttons on posts only if the user is an admin, for instance.
That's for resource-specific actions. Often times it's also a good idea to have a section of the site that consolidates resource views and administrative actions. This would be its own controller/view (I call mine AdminController) and you can protect all actions in it with the above method:
before_action :admin_user?

To make your resources available to AdminController using the methods defined inside the individual resource controllers, you can do this in routes.rb:
namespace :admin do
  resources :users
end

This will make it so that http://yoursite.com/admin/users/index will still call the index action in the Users controller, but it will happen within the context of an admin user (because of the before_action above).
Comment: Right now I use the before_filters to lightly limit the resources, but want to go with the admin area that consolidates resource views like you suggested.

How would I make these actions (posts, users resources etc) available to the admin controller?

Is having a (mostly empty) controller that inherits from the public facing controllers too un-DRY?

I'm just trying to understand how the current controllers actions would be made available to the backend.

Rails 4 custom admin backend


French book translation related to Ménage problem

Question: I was reading about menage problem till I found the following formula:
$$M_n=2(n!)U_n$$
Where $M_n$ denotes the menage numbers and $U_n$ is the number of ways of seating men.
It's known that :
$$(n-2)U_n= n(n − 2)U_{n−1} + nU_{n−2} + 4(−1)^{n+1}\tag{I}$$
The formula $\text($I$)$ is proved in the book Théorie des nombres by Lucas, Edouard (1842-1891).
Unfortunately the book is in French and I could not find any English version of this book,on the other hand it looks that the only source that gives a proof of $\text($I$)$ is this book.
If someone has an English version please let me know,besides here are the pages that I'm going to learn,it would be highly appreciated if someone help me:

To be continued...
Answer: Lucas sets the problem up by situating the wives in numerical order
$$
W_1\ \_\_\ W_2\ \_\_\ W_3\ \_\_\ \ldots\ W_n\ \_\_
$$
with the blanks to be filled by the husbands, $H_1,\ H_2,\ \ldots,\ H_n$. The last blank, of course, is considered to be adjacent to $W_1$.
Lucas defines four quantities:

$\lambda_n$ is the number of ways of placing the husbands so that $H_j$ is not adjacent to $W_j$ for any $j$;
$\mu_n$ is the number of ways of placing the husbands such that $H_1$ is in the last slot (and hence adjacent to $W_1$), but for all $j\ne1$ it is the case that $H_j$ is not adjacent to $W_j$;
$\nu_n$ is the number of ways of placing the husbands so that exactly one husband is adjacent to his wife, but excluding placements where either $H_1$ or $H_n$ is in the last slot or $H_1$ is in the first slot;
$\rho_n$ is the number of ways of placing the husbands so that $H_1$ is in the last slot (and hence adjacent to $W_1$) and exactly one other husband is also placed adjacent to his wife.

Lucas then derives the formula
$$
\lambda_{n+1}=(n-2)\lambda_n+(n-1)\mu_n+\nu_n+\rho_n.
$$
He does this by extending each of the placements counted by $\lambda_n$, $\mu_n$, $\nu_n$, and $\rho_n$ by putting newcomers $W_{n+1}$ and $H_{n+1}$ at the right,
$$
W_1\ \_\_\ W_2\ \_\_\ W_3\ \_\_\ \ldots\ W_n\ \_\_\ W_{n+1}\ H_{n+1}
$$
and then counting the ways of swapping $H_{n+1}$ with some other $H_j$ to produce a valid placement.

The factor $n-2$ in front of $\lambda_n$ comes about by noticing that $H_{n+1}$ may be swapped with any husband except for $H_1$ or the husband to the right of $W_n$.
The factor $n-1$ in front of $\mu_n$ arises because $H_{n+1}$ may be swapped with any husband except $H_1$.
The term $\nu_n$ comes about, with coefficient $1$, because $H_{n+1}$ must be swapped with the husband who is next to his own wife.
The term $\rho_n$ comes about similarly: $H_1$ is no longer adjacent to $W_1$ because $W_{n+1}$ and $H_{n+1}$ have been interposed. There was one other husband next to his own wife, who now gets swapped with $H_{n+1}$.

For this to be a proof one must argue that all valid arrangements are obtained in this way, exactly once. Lucas doesn't go into detail about this, but I think the way to argue it is to start with a valid arrangement of $n+1$ couples and have $W_{n+1}$ and $H_{n+1}$ depart, leaving two empty chairs. The husband in the chair to the right of the chair in which $W_{n+1}$ sat is moved to the chair in which $H_{n+1}$ sat, and the two now-empty chairs to the left of $W_1$ are removed. We must show that we inevitably get one of the arrangements counted by $\lambda_n$, $\mu_n$, $\nu_n$, or $\rho_n$. The insertion process described previously will then be the inverse of the deletion process just described.
I think this is clear, however. The only places in which possible defects might occur are in the chair to the left of $W_1$ and in the chair that previously contained $H_{n+1}$, which accords with the four cases describing $\lambda_n$, $\mu_n$, $\nu_n$, and $\rho_n$. The only thing that can go wrong in the chair to the left of $W_1$ is that $H_1$ might have been sitting there. (He would previously have been adjacent to $W_n$ and $W_{n+1}$ but would now be adjacent to $W_n$ and $W_1$.) The only slightly complicated thing to understand is the conditions placed on $\nu_n$. The condition that $H_1$ not occupy the chair to the left of $W_1$ is there so that the $\nu_n$ cases don't overlap with the $\mu_n$ cases. The condition that $H_n$ not occupy the chair to the left of $W_1$ (and hence to the right of $W_n$) would never arise as the result of removing $W_{n+1}$ and $H_{n+1}$ from a valid configuration in the manner described. Finally, the condition that $H_1$ not occupy the chair to the right of $W_1$ is needed because the defect is assumed to have arisen by moving the husband previously sitting to the left of $W_1$ in a valid arrangement, and this husband could not have been $H_1$.
Lucas then switches to the equivalent problem of placing $n$ non-attacking rooks on an $n\times n$ chessboard subject to the condition that no rook occupy certain excluded squares (marked with an $\times$):
$$
\begin{array}{cccccccc}
\cdot & \cdot & \cdot & \cdot & \cdot & \cdot & \times & \times\\
\cdot & \cdot & \cdot & \cdot & \cdot & \times & \times & \cdot\\
\cdot & \cdot & \cdot & \cdot & \times & \times & \cdot & \cdot\\
\cdot & \cdot & \cdot & \times & \times & \cdot & \cdot & \cdot\\
\cdot & \cdot & \times & \times & \cdot & \cdot & \cdot & \cdot\\
\cdot & \times & \times & \cdot & \cdot & \cdot & \cdot & \cdot\\
\times & \times & \cdot & \cdot & \cdot & \cdot & \cdot & \cdot\\
\times & \cdot & \cdot & \cdot & \cdot & \cdot & \cdot & \times
\end{array}
$$
Placements counted by $\mu_n$, $\nu_n$, and $\rho_n$ correspond to boards in which rooks occupy particular disallowed squares.  By using the two operations of

deleting a row and the corresponding column, and
performing a cyclic permutation of rows and the corresponding cyclic permutation of columns,

Lucas relates certain sets of boards to one another so as to deduce the three relations
\begin{align*}
\mu_n&=\lambda_{n-1}+\mu_{n-1}\\
\nu_n&=(2n-3)\mu_n\\
\rho_n&=(2n-3)\mu_{n-1}+\rho_{n-1}.
\end{align*}
I have not checked this part in detail. The second of these equations may be used to eliminate $v_n$ from the equation for $\lambda_{n+1}$:
$$
\lambda_{n+1}=(n-2)\lambda_n+(3n-4)\mu_n+\rho_n.
$$
Subtracting from this equation the same equation with $n$ replaced by $n-1$ and using the equation for $\rho_n$ gives
$$
\lambda_{n+1}-\lambda_n=(n-2)\lambda_n-(n-3)\lambda_{n-1}+(3n-4)\mu_n-(3n-7)\mu_{n-1}+(2n-3)\mu_{n-1}.
$$
Simplifying, and using the equation for $\mu_n$ to eliminate $\mu_{n-1}$ gives
$$
\lambda_{n+1}=(n-1)\lambda_n-\lambda_{n-1}+2n\mu_n.
$$
Replace $n$ in this equation with $n-1$ and multiply the resulting equation by $n$ to get
$$
n\lambda_n=n(n-2)\lambda{n-1}-n\lambda_{n-2}+2n(n-1)\mu_{n-1}.
$$
Subtract this from the original equation multiplied by $n-1$ to get
$$
(n-1)\lambda_{n+1}-n\lambda_n=(n-1)^2\lambda_n-n(n-2)\lambda_{n-1}-(n-1)\lambda_{n-1}+n\lambda_{n-2}+2n(n-1)(\mu_n-\mu_{n-1}),
$$
which simplifies to
$$
(n-1)\lambda_{n+1}=(n^2-n+1)(\lambda_n+\lambda_{n-1})+n\lambda_{n-2}.
$$
This can be rewritten as
$$
(n-1)\lambda_{n+1}-(n-1)(n+1)\lambda_n-(n+1)\lambda_{n-1}=-[(n-2)\lambda_n-(n-2)n\lambda_{n-1}-n\lambda_{n-2}].
$$
This is a recurrence of the form $A_{n+1}=-A_n$, which has solution $A_{n+1}=K(-1)^n$ for some constant $K$. We obtain
$$
(n-1)\lambda_{n+1}-(n-1)(n+1)\lambda_n-(n+1)\lambda_{n-1}=K(-1)^n.
$$
Using the initial conditions $\lambda_2=0$, $\lambda_3=1$, $\lambda_4=2$, one finds that $K=4$.
Comment: @ Will Orrick,First of all thank you so much for your work (+1),I have some questions,do these couples sit around a circular table? besides does Lucas give a full explanation about how to derive the formula $$
\lambda_{n+1}=(n-2)\lambda_n+(n-1)\mu_n+\nu_n+\rho_n.
$$? I tried to understand,but it looks difficult
Comment: Yes, it's a circular table. (So the last blank is adjacent to both $W_n$ and $W_1$.) I wouldn't say Lucas's explanation is "full", but it is more detailed than what I've included. Did you follow where the $(n-2)\lambda_n$ term comes from on the right? The explanation of the other three terms is similar. I can try to add it if needed.
Comment: Well if you do that then it would be so nice :)


On the equation $s(n^2) = \left(\frac{q-1}{2}\right)\cdot{D(n^2)}$, if $q^k n^2$ is an odd perfect number with special prime $q$

Question: Let $N$ be an odd perfect number given in the so-called Eulerian form
$$N = q^k n^2$$
where $q$ is the special prime satisfying $q \equiv k \equiv 1 \pmod 4$ and $\gcd(q,n)=1$.

In what follows, let us keep in mind the following lemma:

LEMMA: If $q^k n^2$ is an odd perfect number given in Eulerian form, then $k = 1$ holds if and only if
$$s(n^2) = \left(\frac{q-1}{2}\right)\cdot{D(n^2)},$$
where $s(x)=\sigma(x)-x$ is the aliquot sum of the positive integer $x$, $D(x)=2x-\sigma(x)$ is the deficiency of $x$, and $\sigma(x)=\sigma_1(x)$ is the classical sum of divisors of $x$.

Now, we start with
$$\gcd(n^2,\sigma(n^2)) = \left(q^k t - 2(q - 1)\right)n^2 + \left((-\sigma(q^k)/2)\cdot{t} + q\right)\sigma(n^2),$$
like Tony Kuria Kimani did in this recent ResearchGate preprint.
But the equation
$$\gcd(n^2,\sigma(n^2)) = \frac{\sigma(n^2)}{q^k} = \frac{n^2}{\sigma(q^k)/2} = \frac{s(n^2)}{D(q^k)/2} = \frac{D(n^2)}{s(q^k)}$$
holds.  Consequently, we obtain the simultaneous equations
$$s(n^2) = (D(q^k)/2)\cdot\gcd(n^2,\sigma(n^2))$$
$$= \left(q^k (D(q^k)/2) t - 2(q - 1)(D(q^k)/2)\right)n^2 + \left((-\sigma(q^k)/2)(D(q^k)/2)\cdot{t} + q(D(q^k)/2)\right)\sigma(n^2)$$
$$D(n^2) = {s(q^k)}\cdot\gcd(n^2,\sigma(n^2)) = \left(q^k s(q^k) t - 2(q - 1)s(q^k)\right)n^2 + \left((-\sigma(q^k)/2)s(q^k)\cdot{t} + qs(q^k)\right)\sigma(n^2).$$
We now test whether the equation
$$s(n^2) = \left(\frac{q-1}{2}\right)\cdot{D(n^2)}$$
holds; that is, whether the equation
$$\left(q^k (D(q^k)/2) t - 2(q - 1)(D(q^k)/2)\right)n^2 + \left((-\sigma(q^k)/2)(D(q^k)/2)\cdot{t} + q(D(q^k)/2)\right)\sigma(n^2)$$
$$= \left(\frac{q-1}{2}\right)\cdot\Bigg(\left(q^k s(q^k) t - 2(q - 1)s(q^k)\right)n^2 + \left((-\sigma(q^k)/2)s(q^k)\cdot{t} + qs(q^k)\right)\sigma(n^2)\Bigg) \tag{1}$$
is true.
For simpler algebra, let
$$u_1 = q^k (D(q^k)/2) t - 2(q - 1)(D(q^k)/2)$$
$$u_2 = \left(\frac{q-1}{2}\right)\cdot\left(q^k s(q^k) t - 2(q - 1)s(q^k)\right)$$
$$v_1 = (-\sigma(q^k)/2)(D(q^k)/2)\cdot{t} + q(D(q^k)/2)$$
and
$$v_2 = \left(\frac{q-1}{2}\right)\cdot\left((-\sigma(q^k)/2)s(q^k)\cdot{t} + qs(q^k)\right).$$
Then Equation $(1)$ becomes
$$\left(u_1 - u_2\right)\cdot{n^2} = \left(v_2 - v_1\right)\cdot{\sigma(n^2)}. \tag{2}$$
We now attempt to get simplified expressions for $u_1 - u_2$ and $v_2 - v_1$ using WolframAlpha.  We obtain the following:
$$u_1 - u_2 = -\left(\frac{q^k - q}{2(q - 1)}\right)\cdot\left(tq^k - 2q + 2\right)$$
$$v_2 - v_1 = -\left(\frac{q^k - q}{2(q - 1)}\right)\cdot\left(\frac{q(tq^k - 2q + 2) - t}{2(q - 1)}\right). \tag{3}$$
Dividing both sides of Equation $(2)$ by $d = \gcd(n^2,\sigma(n^2))$, we obtain
$$\left(u_1 - u_2\right)\cdot\Bigg({\frac{n^2}{d}}\Bigg) = \left(v_2 - v_1\right)\cdot\Bigg(\frac{\sigma(n^2)}{d}\Bigg).$$
Recall that
$$d = \frac{\sigma(n^2)}{q^k} = \frac{n^2}{\sigma(q^k)/2}.$$
Consequently, we have
$$\left(u_1 - u_2\right)\cdot\Bigg(\frac{\sigma(q^k)}{2}\Bigg) = \left(v_2 - v_1\right)\cdot{q^k}. \tag{4}$$
Since $\gcd(q^k,\sigma(q^k)/2)=1$, then there exists an integer $G$ such that
$$v_2 - v_1 = G\cdot\left(\sigma(q^k)/2\right).$$
Substituting into Equation $(4)$, we get
$$\left(u_1 - u_2\right)\cdot\Bigg(\frac{\sigma(q^k)}{2}\Bigg) = G\cdot\left(\sigma(q^k)/2\right)\cdot{q^k},$$
from which we finally obtain
$$u_1 - u_2 = G\cdot{q^k}.$$
We therefore finally get
$$\gcd(u_1 - u_2, v_2 - v_1) = \gcd\Bigg(G\cdot{q^k}, G\cdot\left(\sigma(q^k)/2\right)\Bigg) = G\cdot\gcd(q^k, \sigma(q^k)/2) = G. \tag{5}$$

To recap, we have obtained
$$G = \gcd(u_1 - u_2, v_2 - v_1).$$
However, from the equations in $(3)$, we also get
$$\gcd(u_1 - u_2, v_2 - v_1) = -\left(\frac{q^k - q}{2(q - 1)}\right).$$
Hence, we finally have
$$G = \gcd(u_1 - u_2, v_2 - v_1) = -\left(\frac{q^k - q}{2(q - 1)}\right).$$
Since GCDs are always nonnegative, then $G \geq 0$, which means that we have
$$q^k - q \leq 0.$$
This implies that $k \leq 1$.  Since $k \geq 1$ ought to hold (because $k$ is a positive integer satisfying $k \equiv 1 \pmod 4$), then we now know that $k=1$.
Quite apparently, this implies that $G = 0$, whereupon we obtain $u_1 = u_2$ and $v_1 = v_2$.

Here is my question:

Can I define GCDs to be always positive (so that $G > 0$ in the previous section) and thereby get a proof for $k \neq 1$?
Comment: You may assume that $G>0$, but then this should be taken into account, and in the last expression for $G$, the minus sign should be removed.
Comment: By the usual definition, $\gcd(a.b)$ is positive if at least one of $a$ and $b$ is nonzero. If you take the convention that $\gcd(0,0)=0$, then, of course, GCD can be $0$.
Comment: The method for obtaining $G$ here is patterned after those in [answer link 1](https://math.stackexchange.com/a/4559480/28816) and [answer link 2](https://math.stackexchange.com/a/4565473/28816).
Comment: Thank you for your time and attention, Professor Dujella @duje!   So when $G > 0$, then $G \geq 1$, so that I get
$$G = \frac{q^k - q}{2(q - 1)} \geq 1,$$
from which we obtain
$$q^k \geq 3q - 2,$$
which **does not force** a contradiction.  =(
Comment: It does prove, however, that $q = 5$ and $k = 1$ is **untenable**.
Comment: Blimey!  How could I have missed it, Professor Dujella, @duje?

$$q^k \geq 3q - 2 \implies q^k - 1 \geq 3q - 3 = 3(q - 1) \implies s(q^k) = \frac{q^k - 1}{q - 1} \geq 3,$$

which contradicts $k = 1$, since this latter assumption implies $s(q^k) = 1$.

Hence, $k \neq 1$ holds!
Comment: If you want to conclude something for $k=1$, then you should insert it in your computations from the beginning. Otherwise, you might multiply and divide by $0$ (i.e. $q^1-q$).
Comment: Okay, Professor Dujella, @duje!  So here I go:  Assume to the contrary that $k=1$.  Then
$$G = \frac{q^k - q}{2(q - 1)} = \frac{q^1 - q}{2(q - 1)} = 0,$$
which contradicts $G \geq 1$.
Comment: Basically, my approach here (as well as in my two newest answers) has been to use GCD theory to derive conclusions about the truth or falsity of $k=1$.  (Note that nowhere did I use division by $G$ in the original post, and that I know that $d = \gcd(n^2,\sigma(n^2)) \geq 3$.) @duje
Comment: It seems that for $k=1$, you have $G=\gcd(0,0)$, and I do not see how you can conclude anything from here.
Comment: Yes, $k = 1$ implies $G = \gcd(0,0) = 0$, Professor Dujella, @duje.  Which is why I wanted to see if I could assume that GCDs are **always positive**, in general, in order to conclude $k \neq 1$.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/140378/discussion-between-duje-and-arnie-bebita-dris).
Answer: Posting this self-answer, thanks to hints from Professor Dujella in the chat room.

First, we show that the assumption $G > 0$ leads to a contradiction.
It is clear that, under the assumption $G > 0$, $k \neq 1$ holds.  (This is because $k = 1$ implies that $G = 0$.)
Then I obtain (from Equation $(4)$ in the original post) that
$$I(q^k) = \frac{\sigma(q^k)}{q^k} = \frac{2(v_2 - v_1)}{u_1 - u_2} = \frac{q(tq^k - 2q + 2) - t}{(q - 1)(tq^k - 2q + 2)} = \frac{q}{q - 1} - \frac{t}{(q - 1)(tq^k - 2q + 2)}. \tag{1}$$
(Note that from Equation $(1)$ in this answer, we have $t \neq 0$.)
We obtain
$$\frac{1}{q^k (q - 1)} = \frac{t}{(q - 1)(tq^k - 2q + 2)}$$
which is equivalent to
$$0 = \left(\frac{1}{q - 1}\right)\cdot\left(\frac{1}{q^k} - \frac{t}{tq^k - 2q + 2}\right) = \left(\frac{1}{q - 1}\right)\cdot\left(\frac{tq^k - 2q + 2 - tq^k}{tq^k - 2q + 2}\right) = -\frac{2(q - 1)}{(q - 1)(tq^k - 2q + 2)}.$$
Now, since a priori we know that $q \geq 5$ holds, then we may cancel $q - 1$ from both numerator and denominator of the last fraction, to get
$$0 = -\frac{2}{tq^k - 2q + 2},$$
resulting in the contradiction
$$0 = -2.$$
(Note that $tq^k - 2q + 2 \neq 0$, because otherwise we would get
$$t = \frac{2(q - 1)}{q^k},$$
which implies that $q^k \mid 2(q - 1)$ (since $t$ must be an integer), contradicting $\gcd(2,q)=\gcd(q-1,q)=1$.)
Hence, we conclude that $G = 0$ must hold.

Now, we claim that:

CLAIM: $G = 0$ if and only if $k = 1$.

Proof: The implication $k = 1 \implies G = 0$ is obvious.
For the converse, assume that $G = 0$.
Then we obtain the system of equations
$$0 = u_1 - u_2 = - \left(\frac{q^k - q}{2(q - 1)}\right)\cdot(tq^k - 2q + 2) \tag{2}$$
$$0 = v_2 - v_1 = - \left(\frac{q^k - q}{2(q - 1)}\right)\cdot\left(\frac{q(tq^k - 2q + 2) - t}{2(q - 1)}\right). \tag{3}$$
Now, note that (referencing Equations $(2)$ and $(3)$ in this answer), we have
$$(2) \iff \left((q^k - q = 0) \lor (tq^k - 2q + 2 = 0)\right) \land (q \neq 1) \iff k = 1,$$
since $tq^k - 2q + 2 = 0$ contradicts the requirement that $t$ must be an integer.
$$(3) \iff \left((q^k - q = 0) \lor (q(tq^k - 2q + 2) - t = 0)\right) \land (q \neq 1) \iff \left((k = 1) \lor (t(q^{k+1} - 1) = 2q(q - 1))\right) \land (q \neq 1) \iff \Bigg((k = 1) \lor \left(1 < t = \frac{2q}{\sigma(q^k)} = \frac{2q}{q + 1} < 2\right)\Bigg) \land (q \neq 1) \iff k = 1,$$
which completes the proof.


What is the most appropriate way to cluster respondents based on their rankings of some items?

Question: I have ~30 observations of individuals ranking 20 different products from top to bottom (1-20). I would like to have a way to "cluster" these individuals based on their rankings of the different products.
For example, I would like to cluster respondents with similar high rankings of the same products. This can be done looking at only the top 3 products ranked by each respondent, if that's simpler.
What would be an appropriate way to perform this analysis?
Answer: You can simply use k-means or hierarchical clustering.
However I'd assume the top products are much more carefully ranked and important, so I'd apply the square root to the entire matrix first, or the logarithm. But that is not "guaranteed" to be better.
Answer: Clustering of respondents based on their rankings of some items - I like to do hierarchical cluster analysis (for example, average or complete linkage) based on Canberra distance or Clark distance. These measures weigh the difference 1-2 higher than 2-3, higher than 3-4, etc. in a exponentially fading manner. It is like podium positions in sports: the advantage of gold (1 place) over silver (2 place) is greater than of silver (2) over bronze (3); while advantage of some 10th place over 11th one is already negligible.
To see the formulas of these two and of many other popular distance measures used for quantitative data - open Word doc. describing my macro !PROXQNT - find it in collection "Various proximities", on my web-page (the link to the page is on my profile page here).
Answer: Prepare metric to measure distance between rankings (maybe Levenshtein https://en.wikipedia.org/wiki/Levenshtein_distance or Kendall? https://en.wikipedia.org/wiki/Kendall_tau_distance), then use k-centroid.
If you use it for analyzing or visualization the data you can also use HAC.


Promise node js

Question: Faço 3 requisições HTTPS nodejs para uma API também em node, cada promise executa uma tarefa e essas promises estou passando várias informações no body delas, uma dessas informações precisa ser um ID. Executando uma promise all, com as 3 promises, a promise example_2 me retorna um ID e quero passar esse ID para a promise example_3, me retornando o resultado que preciso. Então o resultado do promise all tem que ser da promise example_3. E não faço ideia de como fazer isso!
let example_3 = () =>{
   return new Promise( ( resolve, reject ) =>{
     try{
        request({
            method:'post',
            body:'AQUI PRECISO DO ID DO EXAMPLE_2'
       },error(.....

//Executo todas promises
let exect = async () => {
   let responses    = await Promise.all([example_1,example_2,example_3])
   let responseJson = JSON.parse(responses[1]);
   //o id da promise example_2
   let idExample2   = JSON.parse(responseJson.data.filter_value);
}

O id que eu quero passar para a promise EXAMPLE_2 esta na variavel idResp. Alguém poderia me orientar?
Comment: tenta melhorar o corpo da sua pergunta, qual tecnologia você utiliza, é um banco? um documento JSON? isso não está claro deixe toda informação possível.
qual tipo de banco de for um banco e o que exatamente tem nesse modelo de banco, tudo isso tem que ser passado.
Comment: obrigado @Teuuz1994, vou melhorar a pergunta
Answer: Ja que está usando async / await você não pode fazer dessa maneira ?
let example_3 = (id) =>{
   return new Promise( ( resolve, reject ) =>{
     try{
        request({
            method:'post',
            body: id
       },error(.....

//Executo todas promises
let exect = async () => {
   let promise1 = await example_1()
   let promise2 = await example_2()

   let promise3 = await example_3(promise2.data.filter_value)
}

Você também pode paralelizar as chamadas para melhorar a performance.
let exect = async () => {
       let promise2 = await example_2()

       let promise1 = example_1()
       let promise3 = example_3(promise2.data.filter_value)

       let responsePromise1 = await promise1
       let responsePromise3 = await promise3

    }

Comment: obrigado, com seu exemplo me deu uma luz, declarei uma variavel global e joguei o id dentro dela. ficou assim:
state.myId = JSON.parse(responseJson.data.filter_value);
let examp = await example_3();

Promise node js


Recent log messages

Question: Is there a way to view more than just the "recent" log messages in Drupal 7?
I need to look further back for a customer, but the "recent" is only showing messages for today.
Is it possible to search a date range or something?
Any help with this would be greatly appreciated!
Thank You!!
Nicole
Answer: If you're referring to the logs at /admin/reports/dblog - what you see is all that is available.
Depending on your server configuration, you can likely find some more info in your php error logs, the location and the amount of data the error log stores varies based on the server configuration.
Answer: Drupal only stores a limited number of log entries, determined by the "Database log messages to keep" setting located at Administration > Configuration > Development.
However, most web servers keep a so called "access log", a file containing an entry for each URL that was requested.
In some cases and configurations the information (e.g. who created a user) can be inferred from the access log.
Answer: To view more than the Recent log messages at admin/reports/dblog you need to use the error log or/and the access log of the webserver.
I'm not sure if in your case is Apache, NGINX or if you are using a webhosting service, some of them have an option to check this logs.
In the future, if you want to keep more messages at admin/reports/dblog, you can adjust that at admin/config/development/logging and increase the amount on the "Database log messages to keep" option. Careful with this option, a value like "1000000" could have a negative impact on the website performance.
If you don't have a shared hosting environment and you have ssh access to the webserver, I think the best option is to enable the syslog module. This module logs events by sending messages to the logging facility of your web server's operating system (syslog).

Recent log messages


From almost surely to expectation

Question: Suppose you have two sequences of positive random variables, $(X_n)$ and $(Y_n)$, such that a.s. $Y_n = o(X_n)$. Do you see any sufficient condition to obtain $\mathbb E(Y_n)=o(\mathbb E(X_n))$?
Comment: $X_n$ being independent from $Y_n$ for all $n ∈ \mathbb N$ might work... Would you be interested in that?
Comment: Yes, i would be interested! Thank you
Answer: Let $(X_n)$ a sequence of strictly positive integrable random variables and $(Y_n)$ a sequence of nonnegative integrable random variables such that

$X_n $ is independent from $Y_n$ for all $n ∈ \mathbb N $,
$Y_n = o(X_n)$ almost surely,
the sequence $( Y_n/X_n )$ is dominated by an integrable random variable.

Then $ \mathbb E[Y_n] = o(\mathbb E[X_n])$. To see this, we observe first that assumption (2) can be rewritten as $ \lim \frac {Y_n}{X_n} = 0  $ almost surely. Then (3) gives that $ \lim  \mathbb E[\frac {Y_n}{X_n} ] = 0$. Now by independence and Jensen's inequality, $$ \mathbb E[Y_n / X_n] = \mathrm{Cov}(Y_n,1/X_n) + \mathbb E[Y_n] \mathbb E[1/X_n] = \mathbb E[Y_n]\mathbb E[1/X_n] \geq \mathbb E[Y_n]/\mathbb E[X_n]. $$
Hence $ \mathbb E[Y_n] = o(\mathbb E[X_n])$. From the last display we also see that we can replace "independent from" in (1) by $1/X_n$ and $Y_n$ being positively correlated for all $n$.

Without the assumption (3) of a dominating integrable RV, we can find a counterexample, e.g. $ Ω = (0,1]$ with the Borel-σ-algebra and Lebesgue measure,
$$ X_n =n, \qquad Y_n = n^3 1_{(0,1/n]}, \qquad \frac{Y_n}{X_n} = n^2 1_{(0,1/n]},$$
so $Y_n = o(X_n)$, but $\mathbb E[Y_n] = n^2 ∉ o(\mathbb E[X_n]) = o(n)$.

The interesting question that remains is what happens when we do have (3) but drop the independence resp. positive correlation requirement. It does feel like $\mathbb E[Y_n/X_n] → 0 $ is incompatible with $ \mathbb E[Y_n] / \mathbb E[X_n] $ being bounded below by some positive constant if we also have the integrable bound, but I don't have a proof or counterexample.

From almost surely to expectation


Enviar e-Mail com STARTTLS porta 587

Question: Preciso enviar um e-mail usando as configurações do cliente. O acesso ao host utiliza segurança STARTTLS usando porta 587.
Para testes montei o seguinte código (alterei os dados do cliente por segurança):
try {
        String host = "188.8.131.52";
        String port = "587";
        String address = "firstname.lastname@example.com";
        String pass = "xxxx";

        Properties props = new Properties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.quitwait", "false");
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.user", address);
        props.put("mail.smtp.password", pass);
        props.put("mail.smtp.port", port);

        Session session = Session.getDefaultInstance(props, null);

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(address));

        Multipart multiPart=new MimeMultipart();

        InternetAddress toAddress = new InternetAddress("firstname.lastname@example.com");
        message.addRecipient(Message.RecipientType.TO, toAddress);

        message.setSubject("Send Auto-Mail");
        message.setContent(multiPart);
        message.setText("Demo For Sending Mail in Android Automatically");

        Transport transport = session.getTransport("smtp");
        transport.connect(host, address, pass);

        transport.sendMessage(message, message.getAllRecipients());
        transport.close();

        return true;
    } catch (Exception e) {
        Log.e(this.getClass().toString(), e.getMessage());
        return false;
    }

Porém ao tentar conectar no host (transport.connect()) ocorre o seguinte erro:

javax.mail.MessagingException: Could not convert socket to TLS;
    nested exception is:
      javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.

Creio que seja alguma propriedade que falte setar (ou não), porém não sei ao certo como tratar esse erro. O que fazer nesse caso?
Fiz o mesmo teste usando a lib javamail porém obtive o mesmo erro:
https://code.google.com/p/javamail-android/
Answer: Comparando aqui com um meu, configurado com JavaMail que está funcionando perfeitamente a algum tempo, para TLS, as propriedades que tem de diferentes são:
No meu tem:
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.smtp.quitwait", "false");

e não tem:
props.put("mail.smtp.ssl.trust", "smtpserver");

Acredito que esse mail.smtp.ssl.trust não seja uma propriedade utilizado para TLS, já que parece explicitamente ser uma configuração para servidores SSL.
Na Documentação do JavaMail diz o seguinte sobre o uso da propriedade mail.smtp.ssl.trust:

If set, and a socket factory hasn't been specified, enables use of a MailSSLSocketFactory. If set to "*", all hosts are trusted. If set to a whitespace separated list of hosts, those hosts are trusted. Otherwise, trust depends on the certificate the server presents.

Que resumidamente informa que essa propriedade define o smtp especificado com "confiável", dispensando o uso do certificado de segurança com especificado.

Não tenho certeza, mas parece trazer vulnerabilidade a implementação, já que você esta usando um smtp com certificados de segurança e ignorando isso (é necessário também observar se essa propriedade não vai ocasionar o aumento na probabilidade de seu email ser marcado com span por alguns servidores de email).

Tente as alterações que sugeri e veja se funciona.
Recomendo observar esse post sobre a diferença entre SSL e TLS.
Comment: Grande Fernando, ótima resposta. Fiz a alteração nas propriedades, e fazendo um teste com meu email da kinghost, o qual usa TLS também, funcionou. A ÚNICA DIFERENÇA é que o meu host é "smtp.dominio" e o do cliente é "mail.dominio". Por ser "mail" preciso declarar isso na propridade? Como?
Comment: @felipearon, qual propriedade você quer declarar esse "mail.dominio" ou "smtp.dominio"? não entendi sua duvida? No "mail.transport.protocol"? Se for acredito que não faça diferença, pode permanecer `smtp`.
Comment: foi uma dúvida mesmo se precisa ou não declarar "mail" ou "smtp". Pelo que vi basta permanecer "smtp". Modo de inicialização HELO faz alguma diferença na conexão?
Comment: @felipearon, o que vem a ser HELO?
Comment: as coisas estão clareando mais. Pelo que estou entendendo, o servidor do cliente é local na empresa. Esse usa criptografia TLS com um **certificado** que não é padrão, por conta disso não estou conseguindo a conexão, diferente do certificado da kinghost (o qual fiz o teste de envio e está funcionando).
Answer: Tente trocar isso
 props.put("mail.smtp.ssl.trust", "smtpserver");

pelo smtp do seu cliente, pois o smtp do seu cliente não deve ser smtpserver certo?
Ex:
     props.put("mail.smtp.ssl.trust", "smtp.meucliente.com.br");

Comment: Refiz a classe de envio de e-Mail, e setando a propriedade acima funcionou perfeitamente!
Answer: A primeira resposta do @user2227682 funciona perfeitamente, porém como você está utilizando Start TLS existe uma propriedade mais específica para isso, confome o @Fernando Leal disse, não é a regra ideal, embora funcione.
Se você quiser utilizar a propriedade abaixo também, irá funcionar perfeitamente:
session.getProperties().put("mail.smtp.starttls.enable", "true");

Portanto, as duas regras isoladas ou juntas resolvem esse tipo de problema.

Referência (em inglês):

https://stackoverflow.com/a/48096615/5626568

Enviar e-Mail com STARTTLS porta 587


Solaris logical domain disappears after hard restart (power loss)

Question: We've set up a logical domain (LDOM) on Solaris 11, it persists after a reboot. However, when doing a cold boot (power on), the logical domain isn't found.
Note: We've executed
<code>ldm add-spconfig <my_config_name>
</code>
Thanks!
Comment: What's the domain's `auto-boot?` setting?  See https://blogs.oracle.com/cmt/entry/what_s_up_with_ldoms1
Comment: Any issues with the SP itself? Have you checked the SP logs for issues, battery problems etc? You're not doing anything wrong afaik.
Comment: Auto-boot is true and the boot device is set to the 'virtual machines' only vdisk
Answer: You need to use the lastest server firmware. Update it.
This is the main problem.


Can I multiply two correlation coefficients?

Question: I have the following information:
Measure A had a Pearson correlation of 0.60 with measure B in one sample.
The two-week test-retest reliability of measure A in the same sample was 0.64. The two-week test-retest reliability for measure B was 0.76 (Pearson correlation of the sum scores for both).
Say I now have a third measure administered to this sample, measure C. Measures C and B are both depression symptom scores. Given the two-week test-retest reliability for B, we can be confident that depressive symptoms are reasonably stable over two weeks. Measures B and C have been psychometrically validated in other literature (proved concurrent validity against structured clinician interviews, analyzed factor structure, etc).
Measure C was administered within 2 weeks of measure A. Its correlation with measure A is only 0.30. So, measure C was administered at a different time to A, and it is similar to B in nature. However, I don't have the correlation between B and C in this sample (still searching for papers that reported correlations between these measures in other samples).
Is there a way to guesstimate the expected correlation between A and C, e.g. by multiplying the concurrent correlation of A and B and the two-week test-retest correlation of B?
(Yes, I know this would involve a lot of assumptions, but I emphasize I am looking for a guesstimate of the correlation I can expect between A and C; 0.30 is low, but I want to account for the fact that the test differs and the administration time differs.)
Answer: In path model analysis, the correlation between two variables connected via a third variable is calculated in this fashion. For example, if $A \rightarrow B$ has a standardized coefficient of 0.6 and $A$ and $C$ are correlated 0.5, then the (standardized) indirect relationship between $C$ and $B$ (thru $A$) is $0.6 \times 0.5= 0.3$. The total correlation would be this value added to the values from any other valid paths in the model.  Assuming none (mainly, assuming no direct path from $C$ to $B$), this would be the correlation between those two variables.
Comment: That sounds good. I was not familiar with path model analysis. Thanks!


AngularFireAuth emulator login is lost on page reload

Question: My Angular project successfully uses the AngularFireAuth injectable from @angular/fire to connect to a local Firebase authentication emulator. I used these sources as references for my implementation:

Firebase Docs: Instrument your app to talk to the Authentication emulator

StackOverflow: How to configure AngularFireAuthModule and/or AngularFireAuth to point to auth emulator

However, as soon as I reload the page the login state is lost and I have to log in again.
First I tried setting the persistence like this, in an Angular component constructor:
constructor( private _fireauth: AngularFireAuth) {
    this._fireAuth.useEmulator(`http://${location.hostname}:9099/`);
    this._fireauth.setPersistence(firebase.auth.Auth.Persistence.LOCAL);
}

which made no difference. Then I noticed in the browser network console that apparently the firebase library does find the locally stored session after pageload but initially attempts to contact google servers to verify it, which of course fails, because it's a local emulator session:

This seemed to make sense because _fireAuth.useEmulator() is only called in the component constructor. Other parts of the app such as the AngularFireAuthGuard probably try accessing the authentication status way earlier than that. A few attempts to call useEmulator() before any other part of the app might attempt to access the authentication status failed:

Attempt1: Calling useEmulator() in an @Injectable({providedIn: 'root'}) aka service constructor
Attempt2: Providing an APP_INITIALIZER which executes code before the application is even bootstrapped:

export function initializeApp1(afa: AngularFireAuth): any {
  return () => {
    return new Promise(resolve => {
      afa.useEmulator(`http://${location.hostname}:9099/`);
      setTimeout(() => resolve(), 5000);
    });
  };
}

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    ...,
    AngularFireModule.initializeApp(environment.firebase),
    AngularFireAuthModule,
    ...
  ],
  providers: [
     AngularFireAuth,
     {
       provide: APP_INITIALIZER,
       useFactory: initializeApp1,
       deps: [AngularFireAuth],
       multi: true
     }
  ],
  bootstrap: [AppComponent]
})

Attempt3: Providing the USE_EMULATOR Injectable which seems to be implemented in the AngularFireAuth constructor:

  providers: [
     {
       provide: USE_EMULATOR,
       useValue: [location.hostname, 9099]
     },
  ]

I thought especially Attempt3 would set the emulator mode as early as possible because how much earlier could it be set than in the constructor? The Injectable seem to work, as the browser console prints the usual warning message on pageload: auth.esm.js:133 WARNING: You are using the Auth Emulator, which is intended for local testing only.  Do not use with production credentials.. However, the request to googleapis.com is still fired every time a stored session in the local indexedDB is detected on pageload and I'm logged out afterwards. Also worth noting: In Attempt2 I use a 5 second timeout to slow down the app initialization noticeably and the request to googleapis.com is fired instantly after pageload, way before Angular has finished initializing.
At this point I don't know what to try anymore. @angular/fire is obviously build upon the basic Firebase JavaScript library, so I might have to set emulator mode even earlier, but maybe I'm walking in the completely wrong direction here?
================================================================
[EDIT:] It seems that combining Attempt 2 with Attempt 3 works, as long as the initializeApp1() method uses a setTimout() of at least approx. 100ms. When I remove the timeout or set it to something as low as 10ms the login ist lost. Any timeout longer than 100ms works too. At this point it looks very much like a race condition?
Working example:
export function initializeApp1(afa: AngularFireAuth): any {
  return () => {
    return new Promise(resolve => {
      afa.useEmulator(`http://${location.hostname}:9099/`);
      setTimeout(() => resolve(), 100); // delay Angular initialization by 100ms
    });
  };
}

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    ...,
    AngularFireModule.initializeApp(environment.firebase),
    AngularFireAuthModule,
    ...
  ],
  providers: [
     // Provide the AngularFireAuth constructor with the emulator parameters
     {
       provide: USE_EMULATOR,
       useValue: [location.hostname, 9099]
     },
     // Delay the app initialization process by 100ms
     {
       provide: APP_INITIALIZER,
       useFactory: initializeApp1,
       // for some reason this dependency is necessary for this solution to work.
       // Maybe in order to trigger the constructor *before* waiting 100ms?
       deps: [AngularFireAuth],
       multi: true
     }
  ],
  bootstrap: [AppComponent]
})

I also noticed this comment in the AngularFireAuth source code. So far I don't really understand what's happening, but maybe the issue is related:

// HACK, as we're exporting auth.Auth, rather than auth, developers importing firebase.auth (e.g, import { auth } from 'firebase/app') are getting an undefined auth object unexpectedly as we're completely lazy. Let's eagerly load the Auth SDK here. There could potentially be race conditions still... but this greatly decreases the odds while we reevaluate the API.
Comment: It is actually a bug https://github.com/firebase/firebase-js-sdk/issues/4110
Comment: I managed to get around it by cleaning up my dependencies so that firestore was initialized after auth. I found I had a dependency to firestore in my custom auth service.
Comment: Struggling with the same issue. The auth emulator is fairly new, and it may be a bug/missing feature that needs to be corrected in one of the libs.
Comment: I just added a few new insights. It looks like a race condition in the constructor of the `AngularFireAuth` injectable.
Comment: I also found that comment, but after debugging a little more I'm more uncertain.
Comment: For the time being I'll use the combined solution of `Attempt 2` and `Attempt 3` with a 100ms timeout. I also added an `!environment.production` condition. As long as the race condition has to be dealt with only in a development environment and as long as I have this workaround I won't put any more time into this.
Comment: I don't use Emulator, but I have had a similar problem, I have solved it in Google API Console - Restrict and rename API key, adding in API Restriction section among other Token Service APIs, and it works for me.
Comment: This no longer seems to work.  I'm using Angular 12.2.4, Firebase 8.9.1 and ngx-auth-firebaseui. Using attempt 2 & 3 still causes the login to be lost. For me I was also losing the login anytime I recompiled my app, which does not happen when turning of the emulators.

Using ng serve --hmr worked for me to retain the login when recompiling, but the refresh issue still exists.  Not sure if this has something to do wth ngx-auth-firebaseui but there are no mention of any issues with the emulators on their github site.
Answer: I've tweaked the initialize app function in my code, to use rxjs instead of promises.
export const initializeApp = (angularFireAuth: AngularFireAuth): (() => Observable<boolean>) => {
    if (!environment.firebaseConfig.useEmulator) {
        return () => of(true);
    } else {
        return () => of(true).pipe(
            delay(100),
            tap(_ => {
                angularFireAuth.useEmulator('http://localhost:9099/');
            })
        );
    }
};

Answer: The following solution worked for me -
Add this to the top of app.module.ts (before @NgModule) -
const firebaseConfig = {
  ...
};

import firebase from 'firebase/app';
import 'firebase/firestore';
import 'firebase/auth';
import 'firebase/functions';

const app = firebase.initializeApp(firebaseConfig, 'myApp');
if (environment.useEmulators) {
  app.auth().useEmulator('http://localhost:9099');
  app.firestore().useEmulator('localhost', 8080);
  app.functions().useEmulator('localhost', 5001);
}

And then further down in your imports section:
  imports: [
    ...
    AngularFireModule.initializeApp(firebaseConfig, 'myApp'),
    ...
  ],

I'm guessing this method "grabs" the Auth service earlier than AngularFire. But as you mentioned, the authentication emulator is quite new, hopefully in one of the next releases it will be fixed. Based on this github post.
Comment: I followed your steps, which seems to be similar to https://github.com/firebase/firebase-js-sdk/issues/4110. However, my auth still seems to be hitting the cloud.  I am using Angular 9.1.13, Firebase 8.9.1 and AngularFire 6.1.5.


Prove this inequality $ \sqrt{5} > \frac {13 + 4\pi}{24 - 4\pi} $

Question: $$ \sqrt{5} > \frac {13 + 4\pi}{24 -  4\pi} $$
Comment: @Simon S: I've tried [The one by (published by Nilakantha in the 15th century)](http://en.wikipedia.org/wiki/Pi#Infinite_series). Other than calculators, all techniques are permitted. I'm looking for the best / shortest solution.
Comment: Nice almost integer!
From the observation by @JackDAurizio,
$$\frac{\left(133-37\sqrt{5}\right)}{\pi}\approx 16.0000007560086$$

Maybe this interesting question could be reopened by adding as a context two other approximations to $\pi$ that use $\sqrt{5}$, such as
http://math.stackexchange.com/questions/1092215/how-was-this-approximation-of-pi-involving-sqrt5-arrived-at and http://math.stackexchange.com/questions/146831/approximation-for-pi
Comment: The rational multiple of $\frac{1}{\pi}$ can be related to two convergents to $\pi$:
$$\frac{133}{\pi}=\frac{111}{\pi}+\frac{22}{\pi}\approx \frac{106}{3}+7=\frac{127}{3}=\frac{2^7-1}{3}$$
Answer: This is the same as proving that
$$\frac{1}{16}(133-37\sqrt{5})>\pi$$
and it follows from the fact that the continued fraction of the LHS is:
$$ [3;7,15,1,660,\ldots] $$
while the continued fraction of $\pi$ is:
$$ [3;7,15,1,292,\ldots].$$


Dimension of two finite-dimensional subspaces

Question:
Suppose $V$ is a vector space over a field $F$, and $S$, $T$ are two finite-dimensional subspaces of $V$.
Prove that $S \subset T \Rightarrow $ dim($S$) $\leq$ dim($T$)

My solution)
Let $\{s_1,...,s_n\}$ be a basis of $S$.
Take $t \in T \setminus S$.
If $t$ is a linear combination of $\{s_1,...,s_n\}$, then $t \in S$, which is a contradiction.
Thus $t$ is not a linear combination of $\{s_1,...,s_n\}$.
Now $\{s_1,...,s_n,t \}$ is a basis of $S \cup \{{t}\} $.
Therefore, dim($S$) $\leq$ dim($S \cup \{{t}\} $) holds.
Since $t \in T \setminus S$ is arbitrary, dim($S$) $\leq$ dim($S \cup [T  \setminus S ] $) = dim($T$) holds.
Is it correct?
Answer: The last line is not necessary.   Note:  $$dimT \ge dim (S\cup span\{t\})= dimS+1\gt dimS $$.  The first inequality because there are $dimS+1$ independent vectors in  $T $...
So, if $\exists t \notin S $ then $dimS\lt dim T $, otherwise  $S=T $ so $dimS=dimT $...
Comment: $S\cup\{t\}$ is not a subspace, so it doesn't have a dimension.
Comment: If you mean the span of $S\cup\{t\}$, then why should its dimension be $\le\dim T$?
Answer: Note that $\dim(S\cup\{t\})$ doesn't make sense, because $S\cup\{t\}$ is generally not a subspace (it definitely isn't if $t\in T\setminus S$, by the way).
You could try and salvage it by using $S+\operatorname{span}\{t\}$, but you cannot claim $\dim(S+\operatorname{span}\{t\})\le\dim T$, because this uses what you're trying to prove.

Proposition. The dimension of a (finitely generated) vector space is the maximal size of a linearly independent set.

Proof. Suppose $\{v_1,\dots,v_m\}$ is a linearly independent set with maximal size in the vector space $V$. If it is not a basis, then there exists $v$ which is not a linear combination of $\{v_1,\dots,v_m\}$. In this case, $\{v_1,\dots,v_m,v\}$ is a linearly independent set, contradicting maximality. QED
With this proposition, you have the proof for your statement: assuming $\dim S>\dim T$ would provide a linearly independent set in $S$ with size larger than the dimension of $T$: contradiction.
Comment: I see the problem on my answer! I used what I want to prove..thanks for your comment! I delete my answer ;)
Answer: Let $\{v_1, \ldots, v_k\}$ be a basis for $S$.
$S$ is a subspace of $T$, so the linearly independent set $\{v_1, \ldots, v_k\}$ can be extended to a basis $\{v_1, \ldots, v_k, v_{k+1}, \ldots, v_n\}$ for $T$. Obviously $k \le n$.
By definition of dimension (which is the cardinality of any basis), we have $\dim S = k$ and $\dim T = n$. Therefore, $\dim S \le \dim T$.


Convert Hindustani Bansuri Notes to Carnatic Venu Notes

Question: I plan to use this video to further learn "Tum Hi Ho" on Bansuri
However, the notes sequences are entirely different
Ascending is
Sa Re2 Ga2 Ma1 Pa Da1 Ni2 Sa
Descending is
Sa' Ni2 Da1 Pa Ma1 Ga2 Re2 Sa
Where do I even find information on how to convert these notes?
And what is 1 or 2 after the note? What does it signify?
Please help. The svara sounds so beautiful, I wish to replicate on Bansuri (as well as play "Tum Hi Ho" properly)
Comment: Why do I have a feeling you are overly complicating this. The ascending and descending pitches you described is the major scale (or Raga Shankarabharanam if you really want to be pedantic, but this song is simple enough that you can interpret it as purely major scale). And since humans do not differentiate octave intervals as different : https://en.wikipedia.org/wiki/Octave#Octave_equivalence, its functionally same to play a note in one octave compared to the other. Also what exactly are you trying to convert here? Your question is ambiguous.
Comment: I want to know how to play this on regular 6-hole bansuri
Answer: The other answer by @SoulEater asserts that the numbers refer to the octave of the note. This is incorrect, so I am adding my own answer here to address the OP's question.

The sapta swarās, namely Sa, Ri (or Re), Ga, Ma, Pa, Dha and Ni, are employed in a 12-note system in Hindustani music and in a 16-note system in Carnatic system.
In Hindustani music, what this means is the following: Sa and Pa are "fixed" notes, and there are two positions for each of Re, Ga, Ma, Dha and Ni. These give rise to the 2 + 2x5 = 12 notes in the Hindustani system.
In Carnatic music, what this means is the following: Sa and Pa are "fixed" notes, and there are three positions for each of Ri, Ga, Dha and Ni, and two positions for Ma. These give rise to the 2 + 3x4 + 2 = 16 notes in the Carnatic system.
Now, the 12 notes in the Hindustani system are given the following names (listed in increasing order of the pitch):

Sa
Komal Re
Shuddha Re
Komal Ga
Shuddha Ga
Shuddha Ma
Tivra Ma
Pa
Komal Dha
Shuddha Dha
Komal Ni
Shuddha Ni

(It might help to "visualise" the positions of these swarās if you note that they correspond to the movable Do Re Mi in Western music, as mentioned in @AlbrechtHügli's answer to this question of yours: Equivalency between Indian Classical Saptak and Western Notes.)
An alternative way to notate these 12 positions is to simply number the different positions of Re, Ga, Ma, Dha and Ni, as follows:

S
R1
R2
G1
G2
M1
M2
P
D1
D2
N1
N2

So, for example, Bilawal Thaat (corresponding to the rāgam Sankarābharanam in Carnatic music, or to the major scale in Western classical music), uses the swarās

S, R2, G2, M1, P, D2 and N2

Similarly, in Carnatic music, we give names to each of the 16 notes, and we also refer to them in short by adding numbers to the swarās as before. In increasing order of pitch, they are as follows (I am not mentioning their names here):

S
R1
R2 = G1
R3 = G2
G3
M1
M2
P
D1
D2 = N1
D3 = N2
N3

As you can see, the 16 notes do not have distinct positions. In terms of their pitch, R2 is the same as G1, D2 is the same as N1, etc.

Aside: note that some restrictions clearly have to be placed. Since a ragam must not have a rishabham and a gāndharam both of the same pitch, if R2 occurs in the rāgam, then G1 will not occur, and vice-versa. Similarly for the other overlaps. Moreover, the gāndharam cannot have a lower pitch than the rishabham, so if R3 occurs in a rāgam, then G1 cannot occur. Again, similar restrictions apply to the dhaivatam and nishādam.

Now, to answer the main question, the equivalence between the two systems of notation shows that the notes

S, R2, G2, M1, P, D1 and N2

correspond to

Sa, Shuddha Re, Komal Ga, Shuddha Ma, Pa, Komal Dha and Komal Ni

Warning: if you see someone notating the swarās using subscripts, as in the linked video, then know that a priori they could be using either the 12-note system or the 16-note system. So, things can get confusing because, for instance, G2 means two different things in the two systems! Also know that the 12-note system is sometimes used in Carnatic music as well, so just knowing that a piece in Carnatic music is being notated is not enough to be sure which of the two notation systems is being used.

A good place to start if you want to know more about the notations used for swarās in Indian classical music is the Wikipedia article on swarās.
Comment: Very nice answer! There is a bounty coming your way.
Answer: Hindustani musicians name pitches using a system called Sargam, the equivalent of the Western movable do solfege:

Sa (ṣaḍja षड्ज) = Do
Re (Rishabh ऋषभ) = Re
Ga (Gandhār गान्धार) = Mi
Ma (Madhyam मध्यम) = Fa
Pa (Pancham पञ्चम) = So
Dha (Dhaivat धैवत) = La
Ni (Nishād निषाद) = Ti
Sa (ṣaḍja षड्ज) = Do

Both systems repeat at the octave. The difference between sargam and solfege is that re, ga, ma, dha, and ni can refer to either "Natural" (shuddha) or altered "Flat" (komal) or "Sharp" (teevra) versions of their respective scale degrees.
Source, info: Hindustani classical music - Wikipedia.
About the numbers: There are three main octaves: low (mandra), medium (madhya) and high (tāra). It is about the pitch notation of the flute, as the flute can be in any of these voices, see about pitch here. Also see  this fingering chart, where you can better see the pitches.
Hope this helps you, because indeed is a beautiful sound the one this instrument makes.

Here's a video explaining difference between Bansuri and Venu:
Comment: This is beautiful and your information is helpful, but I was asking for conversion between Carnatic system and Hindustani System. Carnatic Venu has 7 to 8 holes whereas Hindustani Bansuri has 6 holes.
Comment: I think once knowing the notes you can translate them to any instrument regardless the number of holes. Check again my answer I added a youtube video which explains more about these two types of flute


Probability that the p-value is less than 0.05 if H0 is true?

Question: Suppose that under $H_0$, a measurement $X$ is $N(0,\sigma^2 )$, and that under $H_1$, $X$
is $N(1,\sigma^2 )$ and that the prior probability $P(H_0) = P(H_1)$.
With $\sigma$ = 1, what is the probability that the p-value is
less than 0.05 if $H_0$ is true? What is the probability if $H_1$ is true?
Here are my calclations:
Because we have the prior probability $P(H_0) = P(H_1)$,than our likelihood ratio will be:$$\frac{\dfrac{1}{\sqrt{2\pi}}e^\dfrac{-x^2}{2}}{\dfrac{1}{\sqrt{2\pi}}e^\dfrac{-(x-1)^2}{2}}$$
terms with $\pi$ canceled out and we got the following inequality:
$$\frac{e^\dfrac{-x^2}{2}}{e^\dfrac{-(x-1)^2}{2}} >1$$
Solving for x we got:
$$\frac{1-2x}{2} >ln(1)  => x<1/2$$
Are my calculations and the way of solving the problem right?
If yes, what should i do next? Because i don't understand how can i find the probability that the p-value is
less than 0.05
Comment: This is a strange post.  Why are you involving a prior probability distribution in your calculations when the two parts of the question stipulate that $H_0$ is true or $H_1$ is true?  It makes one suspect that you haven't successfully communicated the problem you wish to solve.
Comment: Do it in three steps.  First decide what test statistic you will use.  (Your question doesn't say anything about this.)  Then you can find the critical region for the test. Finally, for each hypothesis, compute the chance that the test statistic lies in the critical region.
Comment: There is a *lot* of detail missing from this post. Frequentists can speak of a probability that $p$ is less than 0.05 because it is calculated from a hypothetical distribution of a test statistic. $p$ is not a parameter. It looks like you're basing your test on the likelihood ratio statistic (in your first display). You can do a MUCH better job reducing the equation. Take its log, it *will* be a known distribution.
Comment: @whuber can you give me a hint how to solve this problem correctly?
Comment: @whuber i think, that in this case i should use likelihood-ratio test and from this test we got, that `exp[(1-x^2)/2] <c` ,where c is some constant.

Then we ca find the value `c` from this equation - this will be our critical region.
Am i right?
Comment: For a continuous statistic and a point null, it really doesn't matter what the statistic is, we can calculate the probability that the p-value is less than 0.05 under the null by elementary arguments.
Comment: @Glen_b as whuber said, i chose L-R statistic and found critical region(we will reject H0 for x<0.5).

But how can we find, the probability? that p-value is less that 0.05 under the null ? My calculation was P(x<0.5 |Ho) = 0.30. But that is an alpha.
Comment: Your rejection rule doesn't matter here, we're discussing p-values. Let's assume you can correctly (exactly) calculate your p-values. What is the distribution of the p-value if the null is true?
Comment: @Glen_b standard normal distribution.
Comment: P-values are necessarily between 0 and 1. How would they have a standard normal distribution?
Comment: @Glen_b of course the p-value distribution is uniform.
I am sorry for the first answer:)
Comment: If a p-value is U(0,1), what is the probability that it is less than 0.05?
Comment: @Glen_b 0.05...omg that is so easy. Thank you!
Answer: We know in frequentist testing that the likelihood ratio test is UMP, and because it is a monotone, continuous likelihood ratio statistic, the test should be of the right size. Asymptotic theory tells us that 2 times the log likelihood ratio has an asymptotic $\chi^2_1$ distribution. A good "hunch" might be to realize that normal random variables should be ideal sailing conditions and this would be a finite sample property.
You've presented the likelihood ratio statistic in the first display. But reduce it using exponent rules and take it's log. Formally describe which test you will apply.


ImagePickerController crashes my app saying "Received Memory Warning" when there are other apps running on my device (2 or more apps)

Question: My App crashes saying "Received Memory Warning" when i take a picture from camera (UIImagePickerController).
Scenario when i get the crash: If I have other apps running on my device(2 or more), I am getting the crash and if there is only one other app running or no other apps running before I launch my app then there are no crashes at all.
This crash happens only when i take the picture from my camera but when i choose the picture from photo library there is no crash at all.
I am using Xcode 4.3.2 and I am using ARC.
Can any one help me on this?
This is the code i am using
-(void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex: (NSInteger)buttonIndex
{

    if (buttonIndex < 2)
    {
        if([UIImagePickerController isSourceTypeAvailable:buttonIndex==0?UIImagePickerControllerSourceTypeCamera:UIImagePickerControllerSourceTypePhotoLibrary])
        {
            UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
            [ipc setDelegate:(id<UIImagePickerControllerDelegate,UINavigationControllerDelegate>) self];
            [ipc setSourceType:buttonIndex==0?UIImagePickerControllerSourceTypeCamera:UIImagePickerControllerSourceTypePhotoLibrary];
            if (buttonIndex == 0)
            {
                [ipc setAllowsEditing:NO];
            }
            [ipc setMediaTypes:[NSArray arrayWithObjects:(NSString *)kUTTypeImage, nil]];
            [self presentModalViewController:ipc animated:YES];
        }
        else
        {
            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Action Alert" message:@"Camera is not available in this device." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alert show];
        }
    }
}

    -(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
    {

        [self dismissModalViewControllerAnimated:YES];
        UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
        if (!image) image = [info objectForKey:UIImagePickerControllerOriginalImage];
        [NSThread detachNewThreadSelector:@selector(scallImage:) toTarget:self withObject:image];
}

 -(void) scallImage:(UIImage *) image
    {
    CGSize newSize = CGSizeMake(320, 480);
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    image=nil;
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSString *cImage = [UIImageJPEGRepresentation(newImage, 0.5) base64EncodedString];
    [ImageButton setBackgroundImage:newImage forState:UIControlStateNormal];
    [ImageButton setHidden:NO];
    //[profileImageButton setBackgroundImage:newImage forState:UIControlStateNormal];
    newImage=nil;
}

Is there any thing wrong in my code?
Comment: does this happen after the first picture is displayed or do you have a number of UIImage objects loaded & resident & displayed (e.g. like in a table view)?
Comment: It happens in either ways
Answer: Try avoiding to allocate UIImagePickerController in that method. Instead allocate it in viewDidLoad. Put this line of code in viewDidLoad:
 ipc = [[UIImagePickerController alloc] init];

And have it declared first in .h file.
Hope this helps.
Comment: How ever at the end of the method 'ipc' will get released right because I am on ARC
Comment: It will get released after viewDidUnload.
Comment: so if i do "ipc = nil" in the block after my work done then will it release? because i am removing the reference !
Answer: I finally realized that by removing some of the unwanted images/resources from the project I am able to run my app without crashes ...!!! Thanks everyone who helped me !


Show that the sequence $x_{n+1}=1+\sqrt {x_n}$ is convergent

Question:
Let, $x_1=1$ and for all $n\in \Bbb N$, $x_{n+1}=1+\sqrt {x_n}$. Prove that the sequence is convergent.

I'm unable to how the sequence is monotonic increasing !
We have, $x_{n+1}-x_n=1+\sqrt{x_n}-x_n$. How can I say this is $\ge 0$ ?n Or any other way to prove this ?
Comment: More general question: https://math.stackexchange.com/q/2010693/290189
Answer: This is easier than you think. Note that all terms are positive, so
$$x_n \le x_{n+1} \implies \sqrt{x_n} \le \sqrt{x_{n+1}} \implies 1+ \sqrt{x_n} \le 1 + \sqrt{x_{n+1}}.$$


Como converter px em vh e vw no JavaScript?

Question: Eu quero converter px em vh e vw no JavaScript, como posso fazer isso?
exemplo
23px = resutado vh ou vw
Answer: É apenas uma questão de porcentagem:
var convertPx2 = {
  vh: function(px){
    px = parseFloat(px);
    var wh = $(window).height(); // captura a altura da viewport

    // faz a relação de  porcentagem dos pixels informados
    // com a altura da viewport
    return (px*100)/wh;
  },
  vw: function(px){
    px = parseFloat(px);
    var ww = $(window).width();  // captura a largura da viewport

    // faz a relação de  porcentagem dos pixels informados
    // com a largura da viewport
    return (px*100)/ww;
  }
}

var convertPx2 = {
 vh: function(px){
   px = parseFloat(px);
   var wh = $(window).height();

    return (px*100)/wh;
  },
 vw: function(px){
   px = parseFloat(px);
   var ww = $(window).width();

    return (px*100)/ww;
  }
}

console.log('400px em vw: ', convertPx2.vw(400));
console.log('400px em vh: ', convertPx2.vh(400));

Comment: Exelente soluçao, funcionou muito bem


How do I use dpm() or kint() to debug a block plugin I created?

Question: I created a custom module which implements a block plugin. The code was generated with Drupal Console. When I try to debug the code within the build function, I get a function not found error.
Why doesn't my code print the value of $build?
namespace Drupal\my_module\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides a 'DefaultBlock' block.
 *
 * @Block(
 *  id = "default_block",
 *  admin_label = @Translation("test block"),
 * )
 */
class DefaultBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $build = [];

    $build['default_block']['#markup'] = '1:Implement DefaultBlock.';
    dpm($build);
    //kint($build);
    return $build;
  }

}

Answer: dpm() definitely works within a custom block; I just tested. Since it calls a service, you may need to clear your cache before it shows up, for example with the command line with drupal cache:rebuild all or drush cr.
To test if the service is available, you could use this code.
dump( \Drupal::service('devel.dumper')); die();

Another thing to consider is that blocks are cached in Drupal 8 by default.  Make sure your build() is actually executing. You may want to turn off the rendering cache while developing, in settings.php or settings.local.php.
$settings['cache']['bins']['render'] = 'cache.backend.null';

Comment: the function definitely works... *if* devel.module is actually enabled, which I guess is the problem here.


How to get a collection of input elements by name attribute

Question: I've got a form which looks like that:
<form method="post" enctype="multipart/form-data" onsubmit="return new_post_form_submit();">
<input type="hidden" name="task" value="addPost">
<input type="hidden" name="post_photo_edit[]" value="0">
<input type="hidden" name="post_photo_edit[]" value="0">
<input type="hidden" name="post_photo_edit[]" value="0">
 ...
</form>

Inside new_post_form_submit function, I would like to select all the elements named post_photo_edit as a collection. As You can see it name actually is post_photo_edit[], because I want to have it as an array inside my PHP code.
I'm using MooTools, but probably jQuery will have exactly the same solution for this.
I've tried to call
$$("input[name='post_photo_edit[]']")

but it gave me an exception. And calling it this way:
$$("input[name='post_photo_edit']")

returns empty collection.
I know I can call this instead
document.getElementsByName("post_photo_edit[]")

and it will work perfect, but I'm wondering how this expression should look like in MooTools to work like this above.
any ideas?
Answer: Function: $$
Selects and extends DOM elements. Return an Elements instance. The Element instance returned is an array-like object, supporting every Array method and every Element method.
Syntax:
var myElements = $$(argument);
Arguments:

selector - (string) A CSS selector
elements - (elements), (collection) or (array) An enumerable list of elements
element, element - (element) any number of elements as arguments

Returns:

(elements) - An array-like Elements collection of all the DOM elements matched, extended with document:id.

So you should use: $$(document.getElementsByName("post_photo_edit[]"));
CSS3 supports character escaping, so you can use backslashes to escape characters:
But you can also escape the array operator like this: $$("input[name=post_photo_edit\[\]]")
Comment: this `$$("input[name=post_photo_edit\[\]]")` would be perfect, but it doesn't work
Comment: i tried in jsfiddle under google chrome and it was good.
http://jsfiddle.net/WSkQs/
Comment: Your're right, it's working but... I'm using some old MooTools version, under 1.1 on jsfiddle it also do not work, under 1.25 it return 0 and under 1.3 it works as it should. Thank You!
Comment: If you're trying to use Mootools/do this to get around IE8's DOM traversal limitations, this doesn't work in IE8.
Answer: Not sure about MooTools, but to select every elemnt that has an attribute which BEGINS with something, you do this:
$('input[name^="post_photo_edit"]')

You can check it out here: jQuery starts With Selector
Comment: Thank You for Your tip, it's `$$('input[name^="post_photo_edit"]')` actually. MooTools is using [W3C CSS3 selectors](http://www.w3.org/TR/css3-selectors/#selectors).
Comment: Under IE, a least 8, only this works: `[name~='post_photo_edit']`
Answer: you should use attribute starts with selector. It's same on MooTools


Margin: 0 auto positioning not working on divs

Question: For some strange reason, centering divs using margin: 0 auto is not working. My code:
HTML:
<!DOCTYPE html>

<meta charset="utf-8">
<title>Picture Gallery</title>

<link rel="stylesheet" href="css/week7.css">

The Mighty Avengers

and CSS:
html {
background-color: gray;
}

h1 {
text-align: center;
}

img {

height: 250px;
margin-left: -20px;
width: 250px;
}

.slide1, .slide2 {
display: block;
margin: 0 auto;
width: 85%;
}

None of the other instances of this type of centering talked about on Stack have been any help. I've tried this with and without a display type set on the classes, to no avail. Any insight into this would be appreciated.
Answer: That's because your image is 150px.. and your div is 80% of the document
You can fix it doing a text-align: center; on .slide1, .slide2.
Answer: Firstly margin: 0 auto; is working in your case but the problem is another - The images width is not enough to full fill the container, so if you want to center the images here is a code for it:
img:first-child {
    margin-left: 0;
}

.slide1, .slide2 {
    display: block;
    margin: 0 auto;
    width: 85%;
    text-align: center;
}

Comment: That did not occur to me, and that is indeed the issue. Thanks!
Answer: I guess this is what you looking for:
Working : Demo
HTML: No Change
CSS
html {
background-color: gray;
}

h1 {
text-align: center;
}

img {

height: 250px;
margin-left: -2px; /* So that it resides side by side*/
width: 250px;
}

.slide1, .slide2 {
display: block;
margin: 0 auto;
width: 500px; /* As you are having 250px for each image */
}

Comment: @Michael Sean Caveney, is this what you want?
Answer: What is it you are trying to achieve? Your slide divs are centered. I've applied a yellow border to them so that you can see.
.slide1, .slide2 {
  display: block;
  margin: 0 auto;
  width: 85%;
  border:1px solid yellow;
}

I've also updated your img css to make it more responsive so that the images dont wrap onto a second row.
img {
  height: auto;
  width: 25%;
  max-width:250px;
}

https://jsfiddle.net/Lmmb03ck/4/
Hope that helps.
Comment: Thanks for reminding me of the "colored border to see that your containers are where they need to be" trick. I'm kicking myself for forgetting that, it's been a while since i had to write CSS.


What is the maximum possible value of determinant of a matrix whose entries either 0 or 1?

Question: My question is simply the title:

What is the maximum possible value of determinant of a matrix whose entries either 0 or 1 ?
Comment: $n!$ is impossible.
Comment: An upper bound that is smaller than $n!$ is $n^{n/2}$. Google Hadamard's inequality.
Comment: Since the determinant is the sum of $\,n!\,$ products of elements of the matrix chosen in a particular way, I'd say the maximum value is $\,n!\,$ ...but I've no example to offer.
Comment: There can't be any example for that
Comment: I can offer an example for $n-1.$ Taking $a_{ii}=0$ and $a_{ij}=1$ if $i\neq j.$
Comment: But for your energetic claims, @MherSafaryan, I see no proof or even hint...
Comment: @DonAntonio, proof of what?
Comment: Of any of your claims below my first comment, @MherSafaryan
Comment: Do you need some help to understand that, @DonAntonio?
Comment: Oh, dear: not at all,  @MherSafaryan...hehe. It's just that it was **you** who asked, I offered a first, rather gross bound, and you claim that that is impossible...just like that.
Comment: And no: it was **not** obvious, or better: as obvious as your question could have been.
Answer: Quoting my question in another thread:

In fact, I don't even know how large the determinant of a 0-1 matrix can be. The Hadamard's bound for the absolute determinant of an $n\times n$ 0-1 matrix is $\frac{(n+1)^{(n+1)/2}}{2^n}$ (online ref. 1 and ref. 2), and the bound is sharp if and only if there exists a Hadamard matrix of order $n+1$. Yet, to my knowledge, there is no known sharp upper bound for the absolute determinant of a general $n\times n$ 0-1 matrix.
Comment: Hm, can someone explain (or direct me to someplace) to understand why this answer is a community wiki? I've not dealt with community wikis before, so just curious.
Comment: @CalvinLin See an explanation [here](http://math.stackexchange.com/privileges/community-wiki). In the present case I turned my answer into a community wiki one on purpose, because I didn't think simply *quoting my own question verbatim* deserves any reputation points.
Answer: A few examples of $\{0,1\}$-matrices (with the largest determinants $-$ according to OEIS-A003432):
$n=2$:
$\quad\det\left(
\begin{array}{cc}
\bf{1} & 0 \\
\bf{1} & \bf{1} \\
\end{array}
\right)
=1;$
$n=3$:
$\quad\det\left(
\begin{array}{ccc}
\bf{1} & 0 & \bf{1} \\
\bf{1} & \bf{1} & 0 \\
0 & \bf{1} & \bf{1} \\
\end{array}
\right)
=2;$
$n=4$:
$\quad\det\left(
\begin{array}{cccc}
\bf{1} & 0 & \bf{1} & 0 \\
\bf{1} & \bf{1} & 0 & \bf{1} \\
0 & \bf{1} & \bf{1} & 0 \\
0 & 0& \bf{1} & \bf{1} \\
\end{array}
\right)
=3;$
$n=5$:
$\quad\det\left(
\begin{array}{ccccc}
\bf{1} & 0 & \bf{1} & 0 & 0\\
\bf{1} & \bf{1} & 0 & \bf{1} & 0 \\
0 & \bf{1} & \bf{1} & 0 &\bf{1}\\
0 & 0 & \bf{1} & \bf{1} & 0 \\
\bf{1} & 0 & 0 & \bf{1} & \bf{1} \\
\end{array}
\right)
=5;$
$n=6$:
$\quad\det\left(
\begin{array}{ccccc}
\bf{1} & 0 & \bf{1} & 0 & 0 & 0\\
\bf{1} & \bf{1} & 0 & \bf{1} & 0 & 0 \\
0 & \bf{1} & \bf{1} & 0 &\bf{1} & 0\\
0 & 0 & \bf{1} & \bf{1} & 0 & \bf{1}\\
\bf{1} & 0 & 0 & \bf{1} & \bf{1} & 0\\
\bf{1} & \bf{1} & 0 & 0 & \bf{1} & \bf{1} \\
\end{array}
\right)
=9;$
$n=7$:
$\quad\det\left(
\begin{array}{ccccc}
\bf1 &    0 & \bf1 &    0 &    0 & \bf1 & \bf1 \\
\bf1 & \bf1 &    0 & \bf1 &    0 &    0 & \bf1 \\
\bf1 & \bf1 & \bf1 &    0 & \bf1 &    0 &    0 \\
   0 & \bf1 & \bf1 & \bf1 &    0 & \bf1 &    0 \\
   0 &    0 & \bf1 & \bf1 & \bf1 &    0 & \bf1 \\
\bf1 &    0 &    0 & \bf1 & \bf1 & \bf1 &    0 \\
   0 & \bf1 &    0 &    0 & \bf1 & \bf1 & \bf1 \\
\end{array}
\right)
=32;$
$n=8$:
$\quad\det\left(
\begin{array}
\bf1 &    0 & \bf1 &    0 &    0 & \bf1 & \bf1 &    0 \\
\bf1 & \bf1 &    0 & \bf1 &    0 &    0 & \bf1 & \bf1 \\
\bf1 & \bf1 & \bf1 &    0 & \bf1 &    0 &    0 & \bf1 \\
   0 & \bf1 & \bf1 & \bf1 &    0 & \bf1 &    0 &    0 \\
   0 &    0 & \bf1 & \bf1 & \bf1 &    0 & \bf1 &    0 \\
\bf1 &    0 &    0 & \bf1 & \bf1 & \bf1 &    0 & \bf1 \\
   0 & \bf1 &    0 &    0 & \bf1 & \bf1 & \bf1 &    0 \\
   0 &    0 & \bf1 &    0 &    0 & \bf1 & \bf1 & \bf1 \\
\end{array}
\right)
=56;$
Comment: Very nice! I was also looking for patterns of symmetry but didn't search too long... (I stopped after having brute-forced $n=4$ with $2^{16}$ variants of the matrix ... ;-))
Comment: @orangeskid: I looked among the striped shapes just to reduce the search area. The striped matrices provide maximum value for determinant only for small $n$ ($n\le 8$): $$n=9: \qquad det_{max}(striped) =125 \textrm{ vs } det_{max}=144; $$ $$n=10: \qquad det_{max}(striped)=312 \textrm{ vs } det_{max} = 320;$$ $$n=11: \qquad det_{max}(striped)=1215 \textrm{ vs } det_{max}=1458;$$
Comment: @Oleg567: So interesting! Btw, just found [this](https://codegolf.stackexchange.com/questions/52851/find-the-maximum-determinant-for-each-size-toeplitz-matrix).
Comment: Yes, we can find first 8 matrices among striped matrices ($\searrow \searrow \searrow$). What about others $n$ ???
Comment: Impressive!  Were you looking only among the striped ones? For $n=9$ you might need $17$ stripes, so you did not reach the largest value from the list?
Comment: Interesting!  A question: given a striped determinant with $0$, $1$, is it largest among striped determinants with entries in $[0,1]$? Since it is not linear in the entries anymore...
Comment: @orangeskid:

small update:
$n=10$ has $det_{max}(striped) = 315$;
and $n=11$ admits striped (cyclic) solution:
$$
n=11:\qquad det\left(
\begin{array}{lllllllllll}
1&0&1&0&0&0&1&1&1&0&1\\
1&1&0&1&0&0&0&1&1&1&0\\
0&1&1&0&1&0&0&0&1&1&1\\
1&0&1&1&0&1&0&0&0&1&1\\
1&1&0&1&1&0&1&0&0&0&1\\
1&1&1&0&1&1&0&1&0&0&0\\
0&1&1&1&0&1&1&0&1&0&0\\
0&0&1&1&1&0&1&1&0&1&0\\
0&0&0&1&1&1&0&1&1&0&1\\
1&0&0&0&1&1&1&0&1&1&0\\
0&1&0&0&0&1&1&1&0&1&1
\end{array}
\right) = 1458
$$

Regarding striped determinant with entries in $[0,1]$: it looks so, but I have no proof.


check if radio is selected doesn't do anything

Question: I have two radio buttons and I want that when I select an option to continue with the code but I can not because nothing appears. Here is the whole code

$(function() {
  $("#tratamientos").click(function() {
    let valorSelect = $("#tratSelect").val();
    let valor = $('input:radio:checked').val();
    if (valor == 'rojo') {
      if (valorSelect == 2) {
        alert('Extracción indicada es una prestación requerida.')
        $('#tratSelect').val('none')

      }
    }
  });

});

if ($("#prestRequerida").is(':checked')) {
  alert('ha seleccionado prestacion requerida')
}

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">

<form id="tratamientos">

    Seleccione el tipo de Prest. requerida

      <input type="radio" id="prestExistente" name="colorPrestacion" value='rojo'>

       Prestaciones existentes

        <input type="radio" id="prestRequerida" name="colorPrestacion" value='azul'>
         Prestaciones requeridas

  <select class="col-md-4" name="" id="tratSelect">
    <option value='none' selected disabled>Seleccione referencia</option>
    <option value="2">Extracción requerida</option>

  </select>
</form>

I have tried differents ways and I don't understand why the other one works and this not
This is the one who works
$(function () {
    $("#tratamientos").click(function () {
        let valorSelect = $("#tratSelect").val();
        let valor = $("input:radio:checked").val();
        if (valor == "rojo") {
            if (valorSelect == 2) {
                alert("Extracción indicada es una prestación requerida.");
                $("#tratSelect").val("none");
            }
        }
    });
});

and these are the others
if ($("#prestExistente").is(':checked')) {
    console.log('ha seleccionado prestacion existente')
}

       let val= $('input:radio[name=colorPrestacion]:checked').val()
   if (val=="rojo") {
       alert(' seleccion prestacion existente')
   }

also the if condition to the radio buttons dont have to be inside a function that's why I didn't put it inside the other
Comment: Is your jQuery selector `#prestExistente` an input element? Only input elements in this case utilize the :checked property.
Comment: The second if isn't inside the click callback.
Comment: yes it is an input element and also how can I make it work without insert it inside the click function?
Comment: i wrapped it inside a $(document).ready(function() {})
Comment: @LuzBritez If you don't put it in an event handler, it only runs when the page first loads, before the user selects one of the buttons.
Answer: Your last if statement should be within the click event handler as well:
$(function () {
    $("#tratamientos").click(function () {
        let valorSelect = $("#tratSelect").val();
        let valor = $('input:radio:checked').val();
        if (valor == 'rojo') {
            if (valorSelect == 2) {
                alert('Extracción indicada es una prestación requerida.')
                $('#tratSelect').val('none')

            }
        }
        //Right here VVV
        if ($("#prestRequerida").is(':checked')) {
            alert('ha seleccionado prestacion requerida')
        }
        //Right here ...
    });

});


Does music have a relative interval notation?

Question: A melody can be written in a type of relative notation, where we don't think in notes but rather in relative intervals.
X - means choose any note
0 - means hit note again where you are
positive - means to raise current note by this many semitones
negative - means to lower current note by this many semitones
So the first few measures of the melody of happy birthday could be written as:
X 0 2 -2 5 -1 -4 0 2 -2 7 -2
Is there an official name for this type of notation?
Comment: A tiny bit similar to NNS, as it's not key dependent.
Comment: This is like Parsons Code, except that Parsons Code just indicates Repeat, Up or Down so it doesn't care about the size of the interval, just its direction.
Answer: In the theory and analysis of twentieth-century music, we have the notion of ordered pitch intervals. These intervals are measured in semitones (as in the system you gave) and, because they are "ordered," they specify ascending or descending.
As such, your "Happy Birthday" notation becomes:
 0 +2 -2 +5 -1 -4 0 +2 -2 +7 -2
Similar concepts are used when programming music, or determine trends across a corpus; for instance, IMSLP's Search by Melody feature uses something like it. (In their case, they give middle C the value of 60.)
Comment: it's interesting. A harmony could be notated in a similar way underneath it. Like a one note harmony. The harmony would just be relative to the current melody note played.
Comment: No worries! Also: https://music.stackexchange.com/questions/1480/what-is-the-the-nashville-numbers-system


How to build Qhull into Javascript with Emscripten?

Question: I've been trying to build Qhull for use on the net, and to be honest. I'm completely lost. I've already installed the Emscripten SDK, and I've tried reading through the guides. From what I can gather, it seems that there are two ways to compile a large project like this one: I can either pass the files as arguments to emcc, or I can make my own custom Makefile that somehow does that for me. But I can neither figure out how to pass multiple files as arguments, nor how Makefiles work.
After scouring the web, I managed to find this port of an old Qhull version, which comes with its own Makefile:
QHULL_PATH = ./src/libqhull
TARGET = qhull.js
EMCC = ../emscripten/emcc
PREJS = ./src/pre.js
POSTJS = ./src/post.js
MAIN = ./src/main.c
EXPORTJS = "['_run_qhull']"
CFLAGS = -O1

SOURCES := $(shell find $(QHULL_PATH) -type f -name '*.c')

all: $(TARGET)
    @echo  "Done"

$(TARGET): $(SOURCES) $(PREJS) $(POSTJS) $(MAIN)
    $(EMCC) $(CFLAGS) $(SOURCES) $(MAIN) -s EXPORTED_FUNCTIONS=$(EXPORTJS) --pre-js $(PREJS) --post-js $(POSTJS) -o $(TARGET)

clean:
    rm -rf $(TARGET)

Unfortunately, the Makefile is in the Unix format, which I only figured out after about two hours of frustration. I don't know how to make it work on Windows.
So, what can I do to get the latest version of Qhull running in Javascript?
I'm using Windows, and my current IDE is Dev-C++.
Answer: So if you're new to compiling, using emscripten to compile a large library is going to be a big challenge. I suggest reading through the emscripten docs on compiling.
It looks like Qhull has both a MakeFile and a CMakeLists.txt. I suggest trying CMake.
The typical way to use CMake with emscripten on linux is something like this:
mkdir embuild
cd embuild
emcmake cmake ..
emmake make

I've never compiled on Windows (I use linux), but I believe that (at least when using Cmake) it is similar.
That probably won't work on the first try.
If (after many tries) you can't get it working, you could try compiling qhull manually with emcc. It looks harder at first, but in the long run I usually get fewer errors.


Solving a Quadratic Equation

Question: $f(x) = 9x^2 - 48x + 14$
I need help in solving this equation.
I cannot simply factorise it, so do I need to use the 'quadratic' formula  to solve it?
Comment: Well, then go on with the quadratic formula. What's the problem?
Comment: http://www.sosmath.com/algebra/quadraticeq/complsquare/complsquare.html
Answer: $$\Delta:=b^2-4ac=48^2-4\cdot 9\cdot 14=1800=2\cdot 900\implies$$
$$x_{1,2}=\frac{48\pm\sqrt\Delta}{2\cdot 9}=\frac{48\pm 30\sqrt2}{18}=\frac{8\pm5\sqrt2}3$$
Comment: Thanks everyone for getting back to me so soon.
Answer: You can factorise it like this:
$9x^2-48x+14=(9x^2-48x+64)-50=(3x-8)^2-50=(3x-8)^2-(5\sqrt{2})^2=$
$=(3x-8+5\sqrt{2})\cdot(3x-8-5\sqrt{2})$
Answer: The first thing to do in this situation, is to check for the discriminant i.e. $$D = b^2-4ac$$
This will tell us, if the your question has a solution or not. If the number is less than zero, then it has no roots. If it is greater than zero then it has two roots and if it equal to zero then it is has one root.
So we have the following:
\begin{align}
&D = b^2-4ac \\
&D = (-48)^2 - 4(9)(14) \\
&D = 1800
\end{align}
Great! This equation has  two roots. Now that we already have the discriminant, we can just use the quadratic formula
$$\begin{align}
&x = \frac{-b \pm \sqrt{b^2-4ac}}{2a} \\
&x = \frac{-9 \pm \sqrt{1800}}{18} \quad \text{*}\\
\end{align}$$
(*) Remember that $b^2-4ac$ is really just $D$ which we calculated before hand and so we can just sub that in.
Now if you work that last bit out, you should get the following roots:
$$x = \frac{1}{3} (8-5\sqrt{2}) \text{ or } \frac{1}{3} (8+5\sqrt{2}) $$
Answer: $$9x^2-48x+14=0,$$ $$x_1=\frac{8+5\sqrt 2}{3}; x_2=\frac{8-5\sqrt 2}{3}$$
The factorise it:
$$9x^2-48x+14=9\left(x-\frac{8+5\sqrt 2}{3}\right)\left(x+\frac{8-5\sqrt 2}{3}\right)$$
Answer: $$f(x) = 9x^2 - 48x + 14=(3x)^2-2\cdot3x\cdot8+8^2-8^2+14=$$
$$=(3x-8)^2-50=(3x-8)^2-(\sqrt50)2=$$
$$=(3x-3\frac{8}{3}-3\frac{\sqrt50}{3})(3x-3\frac{8}{3}+3\frac{\sqrt50}{3})=$$
$$=9(x-\frac{8}{3}-\frac{\sqrt50}{3})(x-\frac{8}{3}+\frac{\sqrt50}{3})=$$
$$=9\left(x-\frac{8+5\sqrt2}{3}\right)\left(x-\frac{8-5\sqrt2}{3}\right)$$

Solving a Quadratic Equation