Java CombinationLock Program

Question: I'm really new to Java and I'm having issues with a program required for my Java class. I need to simulate a lock and implement methods that change combination, check the number on top etc.
Well, I think there's an issue with my openLock() method or alterLockCombination() method. My program will correctly open the lock with default combination (0,0,0) but when I try and change the combination it won't work properly and only the default combination will unlock the lock.
Where are my errors here?
import java.util.Scanner;

public class Lock {

public static final int CLOCKWISE = 0;
public static final int COUNTER_CLOCKWISE = 1;

Scanner in = new Scanner(System.in);

private int x;
private int y;
private int z;
private boolean isLockOpen;
private int noOnTopOfKnob;

public Lock() {
    x = 0;
    y = 0;
    z = 0;
    this.isLockOpen = false;
    this.noOnTopOfKnob = 0;
}

public void alterLockCombinaiton(int x, int y, int z) {
    this.x = x;
    this.y = y;
    this.z = z;
}

public void turnKnob(int direction, int noToStop){
    int i = noOnTopOfKnob;
    int numbersPassed = 0;
    System.out.println("Simulating......");

    do{
        if(direction == CLOCKWISE)
            i++;
        else if(direction == COUNTER_CLOCKWISE)
            i--;
        if(i > 39)
            i = 0;
        if (i < 0)
            i=39;
        this.noOnTopOfKnob = i;

        System.out.print(noOnTopOfKnob + " ");
        numbersPassed++;

        if(numbersPassed>40 && noOnTopOfKnob==noToStop)
            break;
    }
    while(true);
    System.out.println();
}

public void closeLock() {
    System.out.println("Locked!");
    this.isLockOpen = false;
}

public boolean openLock() {
    // initializing with arbitrary values
    int firstStop = -1;
    int secondStop = -1;
    int thirdStop = -1;
    int firstRotation = -1;
    int secondRotation = -1;
    int thirdRotation = -1;

    for(int i = 1; i <= 3; i++){
        System.out.print("Enter a number (0-39) " + i + ": ");
        int noToStop = in.nextInt();
        System.out.print("Enter 0 for clockwise and 1 for counter-clockwise) " + i + ": ");
        int direction = in.nextInt();
        turnKnob(direction, noToStop);

        if(i == 1) {
            firstStop = noToStop;
            firstRotation = direction;

        }
        else if(i == 2) {
            secondStop = noToStop;
            secondRotation = direction;
        }
        else if(i == 3) {
            thirdStop = noToStop;
            thirdRotation = direction;
        }

        if(firstStop == this.x && firstRotation == CLOCKWISE
                && secondStop == this.y && secondRotation == COUNTER_CLOCKWISE
                && thirdStop == this.z && thirdRotation == CLOCKWISE) {

            this.isLockOpen = true;
        }

    }
    return isLockOpen;
}

public boolean isLockOpen() {
    return this.isLockOpen;
}

public int getNoAtTop() {
    return noOnTopOfKnob;
}

}

END of Lock.java
import java.util.Scanner;

public class LockInput {
    public static void main(String[] args) {
            System.out.println("\nWelcome to lock simulator");
            System.out.println("-------------------------------------------------");

            menu();
 }

    public static void menu() {
            Scanner scnr = new Scanner(System.in);
            Lock newLock = new Lock();
            int xInput, yInput, zInput;

            System.out.println("\nSelect an option for the lock.\n");
            System.out.println("    A : Set a new lock combination. ");
            System.out.println("    B : Close the lock.");
            System.out.println("    C : Attempt to open the lock.");
            System.out.println("    D : Check lock status.");
            System.out.println("    E : Check current top number.");
            System.out.println("    Q : Quit program.");

            char menuOption = scnr.next().charAt(0);
            menuOption = Character.toUpperCase(menuOption);

            switch(menuOption) {
                    case 'A':
                            System.out.println("Set a new combination for the lock.\n");
                            System.out.println("Enter the first number of the combination.");
                            xInput = scnr.nextInt();
                            System.out.println("Enter the second number of the combination.");
                            yInput = scnr.nextInt();
                            System.out.println("Enter the third number of the combination.");
                            zInput = scnr.nextInt();

                            newLock.alterLockCombinaiton(xInput,yInput,zInput);
                            menu();
                            break;
                    case 'B':
                            newLock.closeLock();
                            menu();
                            break;
                    case 'C':
                            newLock.openLock();
                            System.out.println("-------------------------------------------------");
                            System.out.println("After lock open attemp....");
                            System.out.println("No on top: " + newLock.getNoAtTop());
                            System.out.println("Lock is open: " + newLock.isLockOpen());
                            menu();
                            break;
                    case 'D':
                            System.out.println("Lock is open: " + newLock.isLockOpen());
                            menu();
                            break;
                    }

    }
}

LockInput class is unfinished since I'm trying to figure out my input issue first.
Comment: Just for the record: dont use an "int" to define CLOCK/COUNTERCLOCK. It would be more appropriate to use an enum instead...
Comment: Beyond that: be more disciplined about vertical spacing: A) follow java coding standards regarding where you put braces/newlines B) be consistent: dont put new lines randomly: use them to really group things that belong together ... together. Dont just use new lines because you can!
Answer: The problem is that you are creating a new Lock() each time menu() is called.
So, the modified combination will be immediately replaced by the default one since menu() gets called just after that, and the lock replaced by a new Lock instance :
newLock.alterLockCombinaiton(xInput,yInput,zInput);
menu();

You may want to remove Lock newLock = new Lock(); from menu(), and declare it as a static variable at the class level instead :
static Lock newLock = new Lock();

Better yet, as suggested by @GhostCat to avoid the static variable :
Create the object in the main method
Lock newLock = new Lock();

Change the menu() method to menu(Lock newLock)
Then call it from main : menu(newLock);
The same goes for the Scanner variable, you'll probably figure that part out .
Comment: I would rather suggest that main() creates Scanner/Lock and **passes** those to the menu() as parameters.
Comment: Thanks so much! I created the object and scanner in main and passed them to menu() as parameters and that worked.

Java CombinationLock Program


Python/MySQL - Exportando arquivos CSV

Question: Olá, estou desenvolvendo uma aplicação para extrair arquivos do meu banco de dados, em csv. O arquivo é gerado normalmente com os dados que estão no banco, mas se eu inserir mais dados dentro do banco, ele gera o mesmo arquivo, somente com oq tinha antes.
Segue o código abaixo:
import pymysql
from pymysql import InternalError
from pathlib import Path
from tkinter import *

tess = Tk()
tess.title("tess")

def exp_rel_emp():

    conn = pymysql.connect(host="localhost", port=3306, user="root", password="", db="omnia")
    print("connect sucessfull!")

    try:
        with conn:
            conn.commit()
            statm = "SELECT * FROM omniacademp INTO OUTFILE '/TEMP/CadastroEmpresas.CSV' FIELDS TERMINATED BY ';' ENCLOSED BY ''"
            cursor = conn.cursor()
            with cursor:
                cursor.execute(statm)
                results = cursor.fetchall()
                print(results)
    except InternalError:
        Path('/TEMP/CadastroEmpresas.CSV').touch()
    finally:
        conn.close()
        print("MySQL connection is closed")

bt = Button(tess, text="tess", command=exp_rel_emp)
bt.place(x=10, y=10)

tess.mainloop()

Comment: E se excluir o arquivo manualmente e executar o SQL, o que acontece?
Comment: Ele gera um novo atualizado, mas gostaria que ele sobrescrevesse o anterior, atualizado.
Comment: Basta excluir o arquivo antes. Conforme a própria [documentação do MySQL](https://dev.mysql.com/doc/refman/8.0/en/select-into.html), a instrução `SELECT ... INTO OUTFILE` não sobrescreverá o arquivo por questões de segurança.
Comment: A causa  pode ser que o código que gera o arquivo não está sendo executado outra vez depois da inserção de novos dados no banco
ou está sendo executado  mas está programado para ler apenas os dados existentes no momento em que foi criado não atualizando
Comment: Tem a questão que tem que ter permissão para escrever arquivos no diretório **"/TEMP/"**
Answer: Vide a documentação do MySQL:

The SELECT ... INTO OUTFILE 'file_name' form of SELECT writes the selected rows to a file. The file is created on the server host, so you must have the FILE privilege to use this syntax. file_name cannot be an existing file, which among other things prevents files such as /etc/passwd and database tables from being modified.

O arquivo que será gerado não pode existir devido, entre outros motivos, questões de segurança, para não correr o risco de sobrescrever arquivos fundamentais do sistema.
Ou seja, se o arquivo existir, basta removê-lo antes de executar a consulta. Utilizando a biblioteca pathlib você pode utilizar o método pathlib.Path.unlink.

Python/MySQL - Exportando arquivos CSV


Rearranging a power series centered in $z_0$ to a power series centered in 0: is that possible?

Question: Suppose we have this power series $S(z) = \sum_{n=0}^{\infty}a_n(z-z_0)^n$ that converges $\forall z \in D(z_0,r)$, $r$ being the radius of convergence. Is that possible to transform $S(z)$ to $T(z) = \sum_{n=0}^{\infty}b_nz^n$? Under which conditions the previous question makes sense (absolute convergence of terms - made of their own power series)? What can we say about "$S(z)=T(z)$"? How does the radius of convergence change? The center of the power really changes?
EDIT: I mean something like this:
$$
S(z) = \sum_{n \geq 0} a_n (z-z_0)^n = \sum_{n \geq 0} a_n \sum_{k=0}^n \binom{n}{k} z^k (-z_0)^{n-k} = \sum_{n \geq 0} \sum_{k=0}^n a_n \binom{n}{k} z^k (-z_0)^{n-k} = \\
\sum_{n \geq 0} \left[ \sum_{k \geq n} a_k \binom{k}{n} (-z_0)^{k-n} \right]z^n = \sum_{n \geq 0} b_n z^n = T(z)
$$
Then we get:
$$
\sigma(S)^{-1} = \overline{lim} \sqrt[n]{|a_n|} = \overline{lim} \sqrt[n]{|b_n|} = \overline{lim} \sqrt[n]{\left| \sum_{k \geq n} a_k \binom{k}{n} (-z_0)^{k-n} \right|} = \sigma(T)^{-1}
$$
EDIT2: I decided to look the power series as a limit for the polynomial series then I realize the first idea makes no sense. We can't define $b_n$ by the way I thought in EDIT1. Here an example:
$$
|z| < 1:\frac{1}{1-z} = \sum_{n \geq 0}z^n = S(z)
\\ \\
|z-1|<1:\frac{1}{z} = \frac{1}{1-(1-z)} =
\lim_{m \to \infty} \sum_{n = 0}^m(1-z)^n =
\lim_{m \to \infty} \sum_{n = 0}^m \sum_{k=0}^n \binom{n}{k}1^{n-k}(-z)^k = \\ =
\lim_{m \to \infty} \sum_{n = 0}^m \sum_{k=0}^n \binom{n}{k}(-1)^kz^k =  \lim_{m \to \infty} \sum_{n = 0}^m \left[ \sum_{k = n}^m \binom{k}{n}(-1)^n \right]z^n =^{wrong} \sum_{n \geq 0} b_nz^n = T(z)
$$
Comment: What is your thought?
Comment: I've just added my 'thought'. Check it out.
Comment: You need to know, in order to have a related series representation, at least that $S(z)$ extends analytically to $z=0$. In your expression all the coefficients could perfectly be divergent series, even if the analytic extension exists. With the condition of having an analytic extension to $z=0$ you get some series extensions, but uniqueness is not guaranteed. If $0\in D(z_0,r)$, then you get uniqueness as well, but this condition is only sufficient.
Comment: The radius of convergence $T$ is guaranteed to be $\sigma(T)\geqslant\sigma(S)-|z_0|$ if $\sigma(S)>|z_0|$. No idea how you think you would have proved that $\sigma(T)=\sigma(S)$.
Comment: @xbh Patting users in the back by assuring them their reasonings are "fine" when they are not, is not a service to give them.
Comment: @Did Sorry, i was irresponsible. I myself should not leave this kind of comment when I did not totally understand the question. I will delete it.
Comment: "In your expression all the coefficients could perfectly be divergent series, even if the analytic extension exists. " @user583185 that is exactly what I wanted to hear
Comment: I added an example I studied here by myself. Did I get the right conclusion?
Answer: You know that $S(z)$ is holomorphic in the region $D(z_0,r) = \{ z \in \mathbb{C} \mid \lvert z - z_0 \rvert < r \}$. Therefore $S(z)$ can be expanded as a convergent power series at any $w \in D(z_0,r)$. If $\lvert z_0 \rvert < r$, this applies for $w = 0$. Write $T(z) = \Sigma_{n=0}^\infty b_n z^n$. Then you have $b_n = \frac{1}{n!}S^{(n)}(0)$ which gives the same result as in your question. For the radius $r_T$ of convergence of $T(z)$ we get $r_T \ge r - \lvert z_0 \rvert$. Note that $r_T > r - \lvert z_0 \rvert$ is possible. Clearly $S(z) = T(z)$ for $z \in D(z_0,r) \cap D(0,r_T)$.
But this is not the complete story. If $f : U \to \mathbb{C}$ is holomorphic (where $U \subset \mathbb{C}$ is open), then $f$ can be expanded as a convergent power series at any $w \in U$. For the radius $r(f,w)$ of convergence we get
$$r(f,w) \ge sup \{R \mid D(w,R) \subset U \} .$$
See e.g. Radius of convergence of Taylor series of holomorphic function.
This means that if $0, z_0 \in U$ and $r(f,0) + r(f,z_0) > \lvert z_0 \rvert$, and if $S(z)$ is the power series for $f$ at $z_0$ and $T(z)$ the power series for $f$ at $0$, then $S(z) = T(z)$ for $z \in D(z_0,r(f,z_0)) \cap D(0,r(f,0)) \ne \emptyset$. However, the coefficients $b_n$ of $T(z)$ cannot be expressed via the coefficients $a_n$ of $S(z)$ if $r(f,z_0) \le \lvert z_0 \rvert$.
Comment: @The Invertible Hog Dog If the answer is okay, you should officially accept it. See https://math.stackexchange.com/help/someone-answers .


Controller won't load data from database

Question: I am currently making a controller to gather myself the data i need from a database. I am not allowed to use Entity Framework and i can't seem to find the reason my controller won't load the data from my SQL server... It is locally hosted on my computer and the connecntion string i am using is in the controller file itself.
Thanks in advance!
I have removed the data context from my controller because i can't share them
namespace ControllerFile.Controller
{
    internal class ControllerFile
    {
        private static string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings[""].ConnectionString;

        public GroupModel GetModel(int Id)
        {
            string sqlQuery = " Query ";

            using (SqlConnection con = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = new SqlCommand(sqlQuery, con))
                {
                    cmd.Parameters.AddWithValue("", );

                    con.Open();

                    SqlDataReader reader = cmd.ExecuteReader();

                    while (reader.Read())
                    {
                        try
                        {
                            Model user = new Model();

                            return user;
                        }
                        catch
                        {
                            MessageBox.Show("Error");
                        }
                    }
                }
            }
            return new Model();
        }

        public void AddNewItem(Model, model)
        {
            string sqlQuery = " QUERY ";

            using (SqlConnection con = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = new SqlCommand(sqlQuery, con))
                {
                    cmd.Parameters.AddWithValue("", model.id);

                    con.Open();

                    try
                    {
                        cmd.ExecuteNonQuery();
                    }
                    catch
                    {
                        MessageBox.Show("Error");
                    }

                }
            }
            return;
        }
    }
}

The result should be a proper connection to my database where my listview loads the correct data. I have added a hardcoded variable with a filled model and that one did load into the listview. So we can rule that code out. It has to be in the controller.
Answer: You're not using the data you get from the database anywhere in that code. You do this:
while (reader.Read())

but then you never actually get any data from the data reader. You just do this:
Model user = new Model();

return user;

so you're just returning a new, empty model, no matter what you get from the database. You need to actually get the appropriate data from the data reader and put it in the model, e.g.
Model user = new Model {SomeProperty = reader.GetString(reader.GetOrdinal("SomeColumn"))};

return user;

Comment: I feel really dumb right now.... I had removed the data context for this post but i never thought about the fact i forgot to add the Model data in the first place. :facepalm:


Bounding growth of generalised mean $M_p(a)$ as $p$ increases

Question: This is a follow-up question to the one previously asked here. on the geometric growth rate of generalized mean. For some $p$ and positive numbers $a=(a_1,\dots,a_n)\in\mathbb{R}^{+}$, let $M_p(a)$ denote the generalised or Hölder mean, defined as
\begin{align}
M_p(a) = \left(\frac1n\sum_{i=1}^n a_i^p \right)^{1/p}, && a_1,\dots,a_n\ge 0, p\in\mathbb{R}^+
\end{align}
It well-known property of generalised means that for any given $a$, the value of $M_p(a)$ increases monotonically in $p$, and strictly so if $a_i$'s are not all equal. The following question attempts to quantify the growth when they are not necessarily equal:

Question: For some fixed $a$, consider the sequence $m_k := M_{2^k}(a)$ corresponding to generalised means with power series $p=1,2,4,\dots$. Is there some constant $c_n$ such that
$$ c_n \left(\frac{m_{k+2}}{m_{k+1}}\right)^2\le \frac{m_{k+1}}{m_k}$$
where $0 < c_n < 1$ crucially does not depend on $a$.

Possible approach
Observations:

If the bound holds universally for $c_n$ and $k=0$, the rest of the inequalities are automatically implied by the base case on the scaled vector $a_i\mapsto 2^k a_i$.

Define $f(x) = \log M_{1/x}(a)$ we can restate the inequality in terms of $f$:
\begin{align}
\log c_n + 2 (f(1/4)-f(1/2)) \le f(1/2) - f(1)
\end{align}
We can also state this result in terms of slope:
\begin{align}
1/2\log(c_n) +\rho(1/4,1/2) \le \rho(1/2,1), && \rho(a,b):=\frac{f(a)-f(b)}{b-a}
\end{align}
Since $f(x)$ is convex (as proven here), a sufficient condition can be obtained by using derivatives:
$$
f'(1)-f'(1/4) \le O(1)
$$
which can be resulted from a bound on second derivative
$$
 f''(x) = O(1)\qquad x\in[1/4,1]
$$
From the second derivative derivation,
$$
 f''(x) = \frac{1}{x^3}\left[ \frac{\sum a_i^{1/x} (\log(a_i))^2}{\sum a_i^{1/x}} - \left(\frac{\sum a_i^{1/x} \log(a_i)}{\sum a_i^{1/x}} \right)^2 \right]
$$
This can be re-arranged to
$$
f''(x) = \frac{1}{x^3}\left[\frac{\sum_{i,j\le n} a_i^{1/x}a_j^{1/x} (\log(a_i/a_j))^2}{\sum_{i,j\le n} a_i^{1/x}a_j^{1/x}}\right]
$$
we can think of the latter formula for $f''(x)$ as weighted average of $\log(a_i/a_j)^2$ terms with weights $a_i^{1/x} a_j^{1/x}$, which allows us to conclude it's not greater than log of maximum ratio between $a_i$'s:
$$
f''(x)\le \max_{i,j}\log(a_i/a_j)^2
$$
However, this introduces a dependency on $a$, and hence is a weaker result, most likely because bounding average with min is a crude approximation.
Possible value $c_n$
As it is common with inequalities involving means, it is best to check the all-equal and all-except-one-zero cases:

If $a_1=\dots=a_n$, both sides being $1$ and inequality holds trivially with $c_n=1$
If only one value is non-zero $a_1>0,a_2=\dots=a_n=0,$ we have $M_4(a)/M_2(a) = n^{1/4},$ and $M_2(a)/M_1(a)=n^{1/2}$, and the inequality again holds with $c_n=1$.

At this point, I took a guess that $c_n=1$ will uniformly hold for all possible $a_i$'s. Thanks to the comment by @Vincenzo in the original post, this turned out to be false. Based on this counter-example, I'll try to investigate the ratios with a special case of a geometric sequence for $a_i$'s.
Consider $a_i=\alpha^{i-1}$ for $i=1,\dots,n$ and some $\alpha\in (0,1]$ to be determined later. Since the ratios are scale-invariant, starting with $a_1=1$ suffices. Note that $\alpha=1$ corresponds to the all-equal case, and $\alpha\to 0^+$ converges to the all-but-one-zero case. Thus, it is interesting if the optimal $\alpha$ (one leading to smallest $c_n$) is in between the two extremes.
We have
\begin{align}
M_p(a) = \left(\frac1n\sum_{i=0}^{n-1} a_i^p\right)^{1/n}
= \left(\frac1n\sum_{i=0}^{n-1} (\alpha^p)^n\right)^{1/p}
= (n)^{-1/p}\left(\frac{1-\alpha^{np}}{1-\alpha^p}\right)^{1/p}
\end{align}
We can conclude:
\begin{align}
\frac{M_{2p}(a)}{M_p(a)}=n^{1/2p} \left(\frac{1+\alpha^{pn}}{1+\alpha^{p}}\right)^{1/2p}
\implies c_n=\frac{M_2(a)}{M_1(a)}\left(\frac{M_4(a)}{M_2(a)}\right)^{-2}=\left(\frac{(1+\alpha^{2n})^2(1+\alpha)}{(1+\alpha^{n})(1+\alpha^2)^2}\right)^{1/4}
\end{align}
If $n$ is sufficiently large and $\alpha<1$, by approximating $1+\alpha^{2n}$ and $1+\alpha^n$ by $1$, $c_n$ can be approximated by
\begin{align}\tag{*}
c_n&\approx \left(\frac{1+\alpha}{(1+\alpha^2)^2}\right)^{1/4},
\end{align}
Finally, we can lower-bound the RHS by finding the arg-min $\alpha$, which turns out to be $\alpha=2/3$, and the corresponding minimum value is $RHS(*)\ge 0.94539...$ Because this value is not close to $1$, this suggests a somewhat surprising inequality
\begin{align}
\min_{\alpha\in(0,1)} \left(\frac{1+\alpha}{(1+\alpha^2)^2}\right)^{1/4} = 0.9453... \text{ for $\alpha=2/3$} \implies \min_{0<\alpha<1} c_n = 0.9453... - o(n)
\end{align}
where $o(n)$ presumably goes down exponentially in $n$ (using negative sign $-o(n)$ to emphasis that it's possibly slightly lower for finite $n$)
Clearly, all these were drawn for a very special case of a a geometric series. But th fact that an "optimal" $\alpha$ exists for a geometric sequence, suggests that anything significantly slower than or faster than exponential dependency of $a_i$ on $i$, eg. $a_i = i\alpha + \beta $ or $a_i= \alpha^{i^2} $, is unlikely to lead to a lower $c_n$.
Answer: Clearly for any positive random variable $X$we have  $E(X^2)\leq E(X)^{2/3}E(X^4)^{1/3}$ by Holder inequality, so your attempts with $c_n=1$ are futile.
Comment: Yes, that was indeed $c_n=1$ was the erroneous guess in the earlier post, but the main question here is for $c_n = .94$ or some constant slightly smaller than $1$.


qual a utilidade de classes aninhadas em python?para que eu usaria algo do tipo?

Question: não consigo encontrar muita coisa do tipo para python, eu sei que dá para fazer isso e sei como fazer, mas não sei porque alguém iria querer fazer isso, visto que a classe interna é incapaz de acessar os atributos e métodos da classe externa, coisa que eu normalmente usaria uma herança para resolver, mas tirando a herança de jogo, usar isso tem alguma utlilidade? vi meu professor fazendo num curso de Django que estou fazendo atualmente.
Comment: Essa pergunta se bem trabalhada tem o potencial de se tornar uma pergunta muito boa e gerar boas repostas. Perguntar a esmo sobre a utilidade de classes aninhadas é escopo indefinido, talvez se associar quais as vantagens  do uso de classes aninhadas a um design pattern especifico, por exemplo Builder, junto de um exemplo de uso.
Answer: Nâo sei exatamente em Python, mas isso é um problema geral de computação.
Normalmente se faz classe aninhadas para se organizar o código.
imagine que você tem uma classe GoogleAPIClient, e digamos que as respostas você deseja guardar em um objeto Response
Este objeto Response não é um objeto Response qualquer, mas dedicado, e se você nomear esta classe com um nome comum, pode colidir com outro Response de outra coisa.
Você pode nomear esse response como GoogleAPIClientResponse, mas o que se faz normalmente é aninhar, assim, dentro do seu GoogleAPIClient você referencia isso apenas como Response.
Algumas linguagens ainda permitem que classes aninhadas sejam privadas, ou seja, você nâo pode gerar uma instância desse response fora de GoogleAPIClient.


Auxiliary variable Gibbs sampler

Question: Suppose we want to sample from a pdf $f(x_1,x_2)$. It's easy to sample from $x_1 \vert x_2$, but not $x_2 \vert x_1$, so we introduce an auxiliary variable $u$ such that $\int f(x_1,x_2,u) du = f(x_1,x_2)$, and it's easier to sample $x_2 \vert x_1, u$. Then, given $(x_1^{(t)}, x_2^{(t)}, u^{(t)})$, we do:

Sample $x_1^{(t+1)} \sim f(x_1 \vert x_2^{(t)})$
Sample $x_2^{(t+1)} \sim f(x_2 \vert x_1^{(t+1)}, u^{(t)})$
Sample $u^{(t+1)} \sim f(u \vert x_1^{(t+1)}, x_2^{(t+1)})$

Does this Gibbs sampling procedure give us valid samples from $f(x_1,x_2)$? If so, why is this true?
Comment: Then your first sample (for $x_1$) needs to be conditional on $u$ as well as $x_2$.
Comment: Is it in fact the case that $f(x_1|x_2,u) = f(x_1|x_2)$?
Comment: In general, no, they're not the same.
Comment: I agree that if we use $f(x_1 \vert x_2, u)$ in step 1 the algorithm would definitely produce valid samples from $f(x_1,x_2)$. My question is about whether the samples are still valid if we use $f(x_1 \vert x_2)$ in step 1 instead. Why or why not?
Answer: Assuming $(x_1^{(t)}, x_2^{(t)},u^{(t)})$ is distributed from the joint distribution $f(x_1^{(t)}, x_2^{(t)},u^{(t)})$, $(x_1^{(t+1)}, x_2^{(t)},u^{(t)})$ is distributed from$$f(x_1^{(t)} \mid x_2^{(t)}) \times f(x_2^{(t)},u^{(t)})$$which differs from$$f(x_1^{(t)} \mid x_2^{(t)},u^{(t)}) \times f(x_2^{(t)},u^{(t)})$$in general. Hence Step 1 does not keep the target as the stationary distribution in general.

Auxiliary variable Gibbs sampler


MySQL output with line breaks in php

Question: I have the following output from my database. How can I output the existing line breaks of the text??
while($row = mysql_fetch_array( $result )) {

    // echo out the contents of each row into a table
    echo "
" ;
    echo '' . $row['id'] . '	';
    echo '' . $row['kategorie'] . '	';
    echo '' . $row['titel'] . '	';
    echo '' . $row['betroffen'] . '	';
    echo '' . $row['beschreibung'] .  '	';
    echo '' . $row['prioritaet'] . '	';
    echo '' . $row['status'] . '	';
    echo '' . $row['eingereicht'] . '	';
    echo '' . $row['umsetzung'] . '	';
    echo '' . $row['kommentar'] . '	';
    echo '' . $row['entwickler'] . '	';
    echo 'bearbeiten	';
    echo 'löschen	';
    echo "
";
}

// close table>
echo "
";

Comment: It has outputed properly. Look at your HTML source.
Comment: [**`nl2br()`**](http://www.php.net/manual/en/function.nl2br.php) ?
Comment: How to use nl2br in my code?
Comment: Which column holds the new line...?
Answer: There are a few ways to do this.
One is with str_replace  another (more common way) is to use nl2br.
For both you have 2 Options in how you use them.
1.) You use single echo Statements as you currently do. In this case you use the commands on the values themselves.
For using str_replace (be Aware that you Need here to differentate between the OS you are using the code on...some use \n some \n\r ,.....
echo '' . str_replace("\n", "
", $row['umsetzung']) . '	';

For completeness sake I'll also put in nl2br (although dinesh already has posted that)
echo '' . nl2br($row['umsetzung']) . '	';

2.) You gather the Output into a variable and then echo that variable (while using the commands on it).
$myOutput = ""
$myOutput = $myOutput . "
" ;
$myOutput = $myOutput . '' . $row['id'] . '	';
$myOutput = $myOutput . '' . $row['kategorie'] . '	';
......
$myOutput = $myOutput . 'löschen	';
$myOutput = $myOutput . "
";
echo nl2br($myOutput);

This method is also possible with str_replace instead of nl2br.
Answer: nl2br($string)

Suppose you want line breaks in title, that is a string. You can do this as follows:-
$trs = '';
while($row = mysql_fetch_array( $result )) {
  extract($rows);
  $trs .= "
$id	"
  $trs .= "
$kategorie	"
  $trs .= "
nl2br($titel)	"
}

echo $trs;

MySQL output with line breaks in php


wdk ddk compiler problems with std::string and std::wstring

Question: I've started playing around with the WDK / DDK (I'm assuming they're the same thing) samples and in particular the printer port monitor example. I've got this compiling using their build tool and I can attach to the spooler process and debug through... good stuff!
.. Problem comes when I simply want to write some debug out. I really thought this would be simple (haven't doing c++ in a while!) but it appears not!
The current problem I'm having is simply trying to create an instance of std::wchar, as in below:
std::wstring test("Blah");

Problem is, when I compile with the wdk build tool I get these errors:
1>c:\winddk\7600.16385.1\src\print\monitors\localmon\localmon.c(361) :
 error C2143: syntax error : missing ';' before ':'
1>c:\winddk\7600.16385.1\src\print\monitors\localmon\localmon.c(363) :
 error C2143: syntax error : missing ';' before 'type'

I'm guessing that this is because the compiler doesn't understand the std:: bit maybe? The line number points to the wstring declaration above.
I've added include <string.h> but that didn't help and my sources file is below:
!IFNDEF MSC_WARNING_LEVEL
MSC_WARNING_LEVEL=/W3
!ENDIF
MSC_WARNING_LEVEL=$(MSC_WARNING_LEVEL) /WX

C_DEFINES=-DUNICODE -D_UNICODE -D_SPL_CLUST

TARGETNAME=ddklocalmon
TARGETTYPE=DYNLINK
DLLENTRY=_DllMainCRTStartup
DLLDEF=localmon.def
DLLORDER=localmon.prf
TARGETLIBS=$(SDK_LIB_PATH)\kernel32.lib     \
           $(SDK_LIB_PATH)\advapi32.lib     \
           $(SDK_LIB_PATH)\user32.lib       \
           $(SDK_LIB_PATH)\ws2_32.lib       \
           $(SDK_LIB_PATH)\spoolss.lib

INCLUDES=$(INCLUDES);     \
         $(DDK_INC_PATH); \

USE_MSVCRT=1

SOURCES=localmon.rc  \
        localmon.c   \
        winspool.c   \
        util.c       \
        config.c     \
        xcv.c        \
        irda.c       \
        mem.c        \

PRECOMPILED_INCLUDE=precomp.h

Also, if I ever got wstring working I was going to use this with OutputDebugString() to process my debug to the visual studio output console, but I think I've read somewhere that this may not work as the port monitor runs in kernel mode?
If anyone could shed any light on this I'd really appreciate it! :)
Andy.
Comment: As others have pointed out, you need to include ``, not ``. In addition to that, a wide string literal has an `L` prefix, `std::wstring test(L"Blah");`.
Comment: Cool, can anyone answer the remaining question of the best way to debug in c / port monitors?
Comment: The standard infrastructure for logging/tracing is [Event Tracing for Windows](https://msdn.microsoft.com/en-us/library/windows/desktop/bb968803.aspx). It is built into the system, can be enabled and disabled at run-time, and can be used from both userland as well as kernel-mode code.
Answer: std::string and std::wstring are C++ classes (actually typedefs for C++ classes), and you are compiling .c files.
Using the C++ runtime libraries in drivers feels a bit strange, I don't know if it works.
If you where to compile as C++ the include is <string> and not <string.h>.
Comment: The example above is compiling user-mode DLL - not a driver (user-mode code - both EXE and DLL is also supported by DDK/WDK).
Comment: C++ in drivers is reasonble, if you understand what the compiler is doing. I.e. you have to understand when you can't call code that's paged out. That restriction continues to apply in the presence of virtual functions, and of course the vtable can't be paged out either.
Answer: Almost all, if not all, of the DDK uses C, not C++.
Comment: Ah, fair enough, thanks! Do you know what I should be using for debugging and logging etc? Take it there isn't anything simple I could use?
Comment: Debug prints (similar to printf) via an attached Windows Kernel Debugger.
Answer: std::string and std::wstring is a part of C++ standard library (included in header file  - NOT  that is part of C standard library as @dalle already posted).
And as @dalle already posted you compile C source code (samples are written in C) - the right format for C++ source file name is *.cpp
Full C++ support is available in user-mode. So since you have user-mode DLL using C++ is OK it you rename files to *.cpp (but looks ugly because you embed C++ chunks into pure-C code samples).
In kernel-mode code however the C++ support is very limited.
If you really need full C++ language support in kernel-mode you may use some tricks to enable it but it is very complicated thing to do by yourself that requires lots of knowledge and experience (though there are some incomplete solutions available to the public).


How can I keep verification on github commits after moving to subkeys?

Question: I recently did a restructure of GPG subkeys so that I have separate keys for signing, auth and encryption:
<code>sec   rsa2048/1B6B7842BBDF4ECE 2016-12-03 [SC]
      74CB4B430ABAB52DEFDECA481B6B7842BBDF4ECE
uid                 [ultimate] Viktor Hedefalk <firstname.lastname@example.com>
ssb   rsa2048/011A8AF0BDCADC7E 2016-12-03 [E]
ssb   rsa2048/67AD5595B594FB0F 2021-02-08 [S]
ssb   rsa2048/F62F31B2894C0560 2021-02-09 [A]
</code>
Problem arose because Github didn't consider my commits to be verified anymore. My options:

Add another entry with the new modified public key - couldn't do that without first deleting since it's actually the same key.
So I deleted the old public key armor and added a new entry from current gpg state. Now my old commits aren't verified but the new one is. This in contrast to https://stackoverflow.com/a/64591620/312873

How can I have both my historical and future commits verified? I'm confused by the output that github gives me here - both the unverified and verified are signed with 67AD5595B594FB0F if I understand this:
Answer: Turns out I just had to wait a few seconds/minutes for something to trigger at github. Just hit refresh now and all was dandy. Happy I took a screenshot or I would have thought I was imagining:


"Zend Optimizer not installed" after I updated to Ubuntu 10.04

Question: I've just updated from 9.10 to 10.04. Everything seems to run fine except for zend optimizer which is throwing "Zend Optimizer not installed" error. I went to php.ini and the following line is still there
Code:
<code>zend_extension=/etc/php5/ZendOptimizer.so
</code>
Also I checked that the file does exist and that the php.ini I am looking at is in fact the php.ini file that is being used by the server. Please let me know if you have any ideas about how to fix or debug this.
Thanks,
Eugene
Answer: Unfortunately Zend Optimizer isn't available for PHP 5.3 yet. You can read about it at the Zend forums: http://forums.zend.com/viewtopic.php?f=57&t=1365. If you really need Zend Optimizer because of Zend Guarded PHP applications you will have to downgrade to PHP 5.2. Or if the application you need is available as an ionCube package you can try ionCube.

Original answer (this still applies for other versions or when a PHP 5.3 compatible version is released):
The PHP version in Ubuntu 10.04 is updated from 5.2.x (Ubuntu 9.10) to 5.3.x. Your Zend Optimizer extension is probably not working because it is outdated and not compatible anymore (if you haven't updated it in the meanwhile). Try to update your Zend Optimizer extension and check if it makes any difference.
If the config really is used by the server and the problem still exists after upgrading Zend Optimizer, check your Apache error_log for any problems loading the Zend Optimizer extension.
Comment: Thanks for help! I enabled debug level of error logging and finally managed to see something. Here is the error

"Zend Optimizer requires Zend Engine API version 220060519.
The Zend Engine API version 220090626 which is installed, is newer.
Contact Zend Technologies at http://www.zend.com/ for a later version of Zend Optimizer."

I am not sure what to do with it though...should I downgrade zend engine? If yes, do you by chance have some manuals at hand?

PS. I've double-checked and my ZendOptimizer.so is indeed the newest one
Comment: I was wrong in my original answer, unfortunately Zend Optimizer isn't available for PHP 5.3 yet.
Comment: Yeah, you are right, I googled zend forums and found the same info. I'll be looking for a way to downgrade php now. Thanks for the help!
Answer: Eugene, you should download Zend Guard for PHP 5.3 from the following page:
http://www.zend.com/en/products/guard/downloads
Pay attention to download the Linux version ;-)
Take the file ZendGuardLoader.so and put it in:
/etc/php5/
Then, update your line in php.ini to look as follows:
zend_extension=/etc/php5/ZendGuardLoader.so
Good luck!
Answer: beta loader files available now for php 5.3 - http://forums.zend.com/viewtopic.php?f=57&t=6595


Old iOS application crashes after launch screen

Question: I'm working on an objective-c iOS application that was first created in 2011 some updates and changes where done in 2013. Now I'm supposed to make this work since it's crashing with an error:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Application windows are expected to have a root view controller at the end of application launch'

in AppDelegate i have checked :
<code>[self.window setRootViewController:viewAfterLaunchScreen];
</code>
according to this answer "Application windows are expected to have a root view controller at the end of application launch" error when running a project with Xcode 7, iOS 9
after debugging i have noticed that the application crashes after running the rootViewController at viewWillAppear.
<code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
if ([[DAL GetPreferences:@"FIRST"] isEqualToString:@"1"])
{
    LoginViewController *lvc3 = [[LoginViewController alloc] initWithNibName:@"LoginViewController" bundle:nil];
    [self.window setRootViewController:lvc3];
    [lvc3 release];
}
else if(_window.rootViewController == nil){

    PagingViewController *lvc2 = [[PagingViewController alloc] initWithNibName:@"PagingViewController" bundle:nil];
    [self.window setRootViewController:lvc2];
    [lvc2 release];
}
[DAL SavePreference:@"FIRST" :@"1"];
[self.window makeKeyAndVisible];
return YES; }
</code>
Comment: Possible duplicate of ["Application windows are expected to have a root view controller at the end of application launch" error when running a project with Xcode 7, iOS 9](http://stackoverflow.com/questions/30884896/application-windows-are-expected-to-have-a-root-view-controller-at-the-end-of-a)
Comment: @Mahesh i have checked this answer before posting my question and i have already mentioned that i have checked setRootViewController.
Comment: Show your `didFinishLaunchingWithOptions` method.
Comment: @Mahesh please check the edited post
Comment: try `LoginViewController *lvc3 = [[LoginViewController alloc] initWithNibName:@"LoginViewController" bundle:nil];
    [self.window setRootViewController:lvc3];` before return YES. if problem is still there then check that your viewcontroller is not nil.
Comment: the problem is still not solved @Mahesh thank you for your time
Answer: How old is this "old" project? If it's more than a few years, do you still have:
<code>[window addSubview:viewController.view];
</code>
You should instead replace it with:
<code>[window setRootViewController:viewController];
</code>


Anonymous user's can't views/download files uploaded via file field

Question: I have a node with a File field and i am using public file system. I have uploaded a file via File field and checked the mark "display" in the list of attached files to node, but still, anonymous user's can't even view it (also they can't download it), till i check this permission:

But i think it's security vulnerability. Is drupal 7 file access system broken? Or am i missing something?
Manage display page
Comment: You should not give anonymouos to bypass file access control. Could you post a screenshot of the "manage display" page for the content type?
Comment: Yeah, sure check the updated post.
Comment: Permissions on sites/default/files are ok? Link to download file appear on node view?
Comment: Permission on folder files is 775, no, link doesn't appear. When i try to open the file directly it throws me - access denied.
Comment: And if you view the node using admin? Are you sure that the file is a "public" and not "private" file?
Comment: Yes, i'm sure it's public. When i view node as user (with id 1) i see the file and able to download it, but anonymous doesn't even see it.
Answer: Figured out! I have uploaded a .rar file, so drupal wouldn't recognize this as existed file types e.g. audio, image, document. I had to go in admin/structure/file-types/manage/document
And add mimetypes for .rar and .zip extension:
application/rar
application/zip

Then just reuploaded file and gave anonymous user's permission:
Document: Download any files


What is the distinction between "relationships" and "differences" (particularly in the context of group differences on a numeric attribute)?

Question: What is the distinction between a relationship and a difference in the context of statistics - if you have a nominal variable and an interval variable, when should you use a correlation to measure the relationship, rather than a t-test or an ANOVA?
I'm not after the usual 'what is your question about - relationships or differences' (although I obviously appreciate the importance), but rather what is it about the data or the constructs that I should know to make this decision.
If for example you have males and females and their intelligence scores. Is there a statistical/conceptual reason why a t-test is better here than a point-biserial correlation?
This is probably going to be an obvious question. To be honest though, I don't feel like I've ever really understood the distinction, so perhaps some of you can articulate it for me?
Answer: Association (or "correlation") and difference are two sides of the same coin. Difference between groups by some quantitative characteristic can be reasoned as the association between variables "group" and "characteristic". Eta coefficient, also called correlation ratio, is the proper association measure between a nominal variable and a scale variable, and is therefore the other side of the coin for ANOVA or t-test. In fact, Eta is used as the effect-size measure (i.e. standardized measure of the size of the difference) in ANOVA. Association measures which vary from 0 to 1 or -1 to 1 are often used as effect size measures. Point-biserial correlation is equal to Eta when there are 2 groups. Point-biserial correlation is just Pearson r.


Complex Shipping Rule: €3 Flat Rate for order's first 2kilos + extra €1.2/extra kilo charge

Question: Well, the title is quite descriptive about what I'm trying to do with Rules for my e-shop.
I have a flat rate for shippable products and I want to charge extra shipping costs to customers according to order's total weight. I'm already using physical fields for weight so I could use the field's value for this rule. Note that some products won't have anything in the weight field and in this case I don't want to take them into consideration for the shipping cost calculation.
So, I want to charge €3 (flat rate's base charge) if the order is 0-2 kilos.
In case the total order's weight is more than 2 kilos, I want to add €1.2 to shipping cost for every additional kilo.
e.g. order has 3 products.
Product 1 - 2 kilos
Product 2 - 0 kilos (or no value in weight field)
Product 3 - 2.5 kilos
Total order's weight: 2+0+2.5 = 4.5 kilos (ie 2.5 kilos to be charged extra)
So the shipping charge should be €3 (flat rate's base) + €1.2*2.5 = €6.
I really need some guidance here on how I'm going to make this happen using Rules.
Answer: One of the problems with Commerce (and Ubercart for that matter) is that it takes awhile for someone to come around with weight based calculations. I have done something similar but it might not work for you.
1) I made each increment I wanted to allow a single product (i.e. 1lb of Product X is 1 QTY, if they want 2lbs of Product X, it's the same as saying Product X with 2 QTY.)
2) Then I created bundles for what I wanted to allow.
3) In shipping, you can set up a rule that allows extra for each extra QTY ($6 for 1 QTY and $2 for each additional QTY.)
For you, it might be possible to set your rule to multiply but you would have to create a module that would allow you to set percentages on QTY if you wanted someone to be able to add 1.2 QTY to their cart. For me, it was easier to do by whole increments and much cleaner on the rules. You can also set your shipping rule to line items so that the first line item is the base and the remaining are the additional.


How to keep case-sensitive in Restful response?

Question: How to keep case-sensitive in Restful response?
My friend complain about case-sensitive in RESTful response

file *.csproj
<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net5.0</TargetFramework>
    <UserSecretsId>4942e08e-0489-4b66-ab36-7c1376ecb8a8</UserSecretsId>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="AWSSDK" Version="126.96.36.199" />
    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="5.0.0-preview.8.20414.8" />
    <PackageReference Include="Microsoft.AspNetCore.Cors" Version="2.2.0" />
    <PackageReference Include="Microsoft.AspNetCore.Identity" Version="2.2.0" />
    <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="5.0.0-preview.8.20414.8" />
    <PackageReference Include="Microsoft.AspNetCore.Identity.UI" Version="5.0.0-preview.8.20414.8" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.0-preview.8.20407.4" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.0-preview.8.20407.4" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="5.0.0-preview.8.20407.4">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.Extensions.Identity.Core" Version="5.0.0-preview.8.20414.8" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="5.0.0-preview.8.20419.1" />
    <PackageReference Include="MimeKit" Version="2.9.1" />
    <PackageReference Include="NAudio" Version="1.10.0" />
    <PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
    <PackageReference Include="NUnit" Version="3.12.0" />
    <PackageReference Include="RestSharp" Version="106.11.5-alpha.0.18" />
    <PackageReference Include="SendGrid" Version="9.21.0" />
    <PackageReference Include="Serilog" Version="2.10.0-dev-01240" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="5.5.1" />
    <PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="5.5.1" />
    <PackageReference Include="Swashbuckle.AspNetCore.Swagger" Version="5.5.1" />
    <PackageReference Include="Swashbuckle.AspNetCore.SwaggerGen" Version="5.5.1" />
    <PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="5.5.1" />

    <PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.10.9" />

    <PackageReference Include="System.ServiceModel.Syndication" Version="5.0.0-preview.8.20407.11" />
    <PackageReference Include="System.Text.Encoding.CodePages" Version="5.0.0-preview.8.20407.11" />
    <PackageReference Include="Twilio" Version="5.46.2" />
    <PackageReference Include="Twilio.AspNet.Core" Version="5.33.1" />
  </ItemGroup>

</Project>

        ///
        /// GET: http://localhost:5002/TrustedPerson/5
        ///
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<ActionResult<TrustedPerson>> ViewTrustedPerson(int id)
        {
            var item = await _db.TrustedPeople.FindAsync(id);
            if (item == null)
            {
                return NotFound();
            }
            return item;
        }

and
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;
using shadow.Data;
using shadow.Services;
using System.Text;
using Microsoft.Extensions.FileProviders;
using System.IO;
using shadow.Models;
using Microsoft.AspNetCore.Authorization;

namespace shadow
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            services.AddHttpContextAccessor();
            //services.AddCors();

            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                    builder => builder.AllowAnyOrigin()
                        .AllowAnyMethod()
                        .AllowAnyHeader());
            });

            services.AddSingleton<IUriService>(o =>
            {
                var accessor = o.GetRequiredService<IHttpContextAccessor>();
                var request = accessor.HttpContext.Request;
                var uri = string.Concat(request.Scheme, "://", request.Host.ToUriComponent());
                return new UriService(uri);
            });
            services.AddIdentity<ApplicationUser, IdentityRole>(options =>
            {
                //options.Password.RequireDigit = true;
                //options.Password.RequireLowercase = true;
                options.Password.RequiredLength = 6;
            }).AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultTokenProviders();
            services
                .AddAuthentication(auth =>
                {
                    auth.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                    auth.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                })
                .AddJwtBearer(options =>
                {
                    options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                    {
                        ValidateIssuer = true,
                        ValidateAudience = true,
                        ValidAudience = Configuration["AuthSettings:Audience"],
                        ValidIssuer = Configuration["AuthSettings:Issuer"],
                        RequireExpirationTime = true,
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["AuthSettings:Key"])),
                        ValidateIssuerSigningKey = true
                    };
                });

            services.AddAuthorization(options =>
            {
                options.FallbackPolicy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .Build();
            });

            services.AddScoped<IUserService, UserService>();
            services.AddTransient<IMailService, SendGridMailService>();
            services.AddControllers();
            services.AddRazorPages();
            services.AddControllers(options => options.SuppressAsyncSuffixInActionNames = false);
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            //app.UseHttpsRedirection();
            app.UseRouting();
            // app.UseCors(options => options.WithOrigins("http://localhost:4200")
            //.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());

            app.UseCors("CorsPolicy");

            app.UseAuthentication();
            app.UseAuthorization();

            // Server: https://shorten.news/static-file/content/10992.mp3
            // Local: http://localhost:5000/static-file/content/10992.mp3
            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(
                // Path.Combine(env.ContentRootPath, @"c:\audio\")),
                Path.Combine(@"c:\audio\")),
                RequestPath = "/static-file"
            });
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }

}

Model
using System;

#nullable disable

namespace shadow.Models
{
    public partial class TrustedPerson
    {
        public int Id { get; set; }
        public string Fullname { get; set; }
        public string AliasName { get; set; }
        public string Email { get; set; }
        public string PhoneNumber1 { get; set; }
        public string PhoneNumber2 { get; set; }
        public string PhoneNumber3 { get; set; }
        public int? RelationshipId { get; set; }
        public string About { get; set; }
        public int? AvatarId { get; set; }
        public DateTime? Created { get; set; }
        public DateTime? Modified { get; set; }
    }
}

The response like
{
    "id": 1,
    "fullname": "Do Xxx Xx",
    "aliasName": "Xx ham",
    "email": "firstname.lastname@example.com",
    "phoneNumber1": "0989878776",
    "phoneNumber2": "0989878777",
    "phoneNumber3": "0989878778",
    "relationshipId": 3,
    "about": "Dep trai",
    "avatarId": 42,
    "created": "2020-09-05T10:34:39.427",
    "modified": null
}

my friend want
{
    "Id": 1,
    "Fullname": "Do Xxx Xx",
    "AliasName": "Xx ham",
    "Email": "email@example.com",
    "PhoneNumber1": "0989878776",
    "PhoneNumber2": "0989878777",
    "PhoneNumber3": "0989878778",
    "RelationshipId": 3,
    "About": "Dep trai",
    "AvatarId": 42,
    "Created": "2020-09-05T10:34:39.427",
    "Modified": null
}

(2)
Is (2) best practice?
How to keep case-sensitive in key of RESTful response like C# model?
Comment: The terminology here is,  camelCase in the first example and PascalCase in the second. Personally i think your friend should have bigger things to worry about
Comment: I am pretty sure you just use `null` for the models default casing `options.JsonSerializerOptions.PropertyNamingPolicy= null;`
Comment: You'll need to show the your code for setting up JSON serialization.
Comment: Where I can find it?
Comment: Your Startup class' `ConfigureServices` method.
Comment: I just added it in question.
Comment: It looks like you don't have anything, so it will be using the default. Are you using .NET Core 2.x?
Comment: I use .NET 5, I will add more information in question
Comment: You'll probably need something like `services.AddJsonOptions(o => o.JsonSerializerOptions.PropertyNamingPolicy = YOURNEWPOLICYSETTING);` but I'm not 100% sure what to put here for your use case because I'm still using JSON.NET in my APIs.
Comment: It works, @MichaelRandall let's post your answer.
Comment: @DoNhuVy all good, the answer that is there is good enough :) as sneaky as it was :P
Answer: Add this line
services.AddJsonOptions(options => { options.JsonSerializerOptions.PropertyNamingPolicy = null; });

Answer: For .NET Core 6 with minimal startup, the code for the accepted answer is:
builder.Services.AddControllers().AddJsonOptions(options =>
{
    options.JsonSerializerOptions.PropertyNamingPolicy = null;
});


A Summability methods which sum the harmonic series

Question: Studying summability theory I've come across many summation methods however by now I know only two not very interesting method which re-sums the harmonic series $\sum_{n=0}^\infty \frac 1{n+1}$ : the null method (most trivial of all, sums every series to $0$) and a generalization of Ramanujan summation (more interesting but not regular so not a summation method in the standard sense) for which
$$\sum_{n=0}^\infty \frac 1{n+1}=0\:\:\:(N)$$
$$\sum_{n=0}^\infty \frac 1{n+1}=\gamma \:\:\:(R')$$
Where $\gamma$ is the Euler constant.
Basically what I'm asking is: are there any other more or less known or useful method which can re-sum the harmonic series to a finite value? And more deeply why is it so difficult to regularize such series?
Any example or link to a paper would be very useful to me!
Comment: see the similar question https://mathoverflow.net/q/3204/7710
Comment: @SimplyBeautifulArt thanks! I've rad similar questions on this and other sites however what I'm specifically looking for is some other more well behaved (regular, maybe stable) method which assigns a finite sum to the harmonic series and maybe it would be great to understand why more a series diverges slowly more it is hard to resum it (this may sound general but knowing a bit of summability it should be clear enough)
Comment: Does this answer your question? [Is it possible to use regularization methods on the Harmonic Series?](https://math.stackexchange.com/questions/20005/is-it-possible-to-use-regularization-methods-on-the-harmonic-series)
Comment: @HandeBruijn interesting sure but I don't see much summability theory in it
Comment: @GottfriedHelms I'm always amazed by how summability has developed in over a century! The Devil's invention is so fascinating.
Comment: Renato - I like like you that "divergent series" subject. I've played around with a self-made matrix summation procedure based on the eulerian-numbers. That summation employs basically the same series-transformation as the Borel-summation does. Unfortunately I don't arrive at something else than infinity. If you like to read explorative articles then you can look at http://go.helms-net.de/math/index.htm for the two links at the entry *"A matrix-method for divergent summation using the matrix of Eulerian numbers"*
Comment: Hmm, perhaps I should take some effort to formulate some of my heuristical approaches as answerable questions - I've experimented with some matrix-methods, generalizations mainly of the Euler-summation ; but it is a couple of years ago and I don't remember whether/how I could possibly focus the unproven heuristics such that I could ask it here... perhaps I can come back to this next days.
Comment: It seems misleading to call this a "sum," in particular, why should the sum of an infinite number of positive terms be less than the sum over a finite number of them?  Why not just call this a map from the set of real-valued sequences to the set of real numbers, i.e., $h:\mathbb{R}^{\mathbb{N}} \rightarrow \mathbb{R}$ with $h(\{1/n\}_{n=1}^{\infty}) = \gamma$?  And then of course you should define the map $h$ precisely.
Comment: @RenatoFaraone : I'm not sure what you mean by "it is pretty clear."  Once you start reusing standard $\sum$ notation, then it is not clear when you mean the usual definition and when you mean some other definition. Kind of like using the symbol $\sqrt{2}$ to mean $100$.
Comment: @RenatoFaraone : In that case I encourage you to define your sum at the start.  I googled "A generalization of Ramanujan summation" but could not find a precise definition (and of course there can be many different generalizations...).
Comment: Related: [Can we assign a value to the sum of the reciprocals of the natural numbers?](https://math.stackexchange.com/q/1627069/272831)
Comment: The null method is always lame =P
Comment: @SimplyBeautifulArt yeah never surprising but incredibly strong and also linear! Not that bad ;)
Comment: X'D True. ${~}$
Comment: Related? Both the Harmonic series and the Euler constant pop up in : [What exactly are the curves that are a best fit to the Harmonic Cantilever?](https://math.stackexchange.com/questions/897387/what-exactly-are-the-curves-that-are-a-best-fit-to-the-harmonic-cantilever) .
Comment: @GottfriedHelms I've read it and found very interesting the answer by Steven but I don't have the background to understand it, what should I study in order to fully understand those concept?
Comment: Urrrxxx - that answer of Steven is also way over my head...
Comment: @GottfriedHelms I'm far from graduating but my thesis will surely be on divergent series so everything you send me is greatly appreciated!
Comment: @Michael I prefer to use the term "resummation" instead of "sum" but in the context of summability it is pretty clear what we mean by "sum" and well... it is shorter to write
Comment: @Michael well imagine you are doing modular aritmethic, the standard notation is due to Gauss (if I remember correctly) but in a 10 page long where I am doing calculations mod 11 if I use the '=' sign and nothing else I think no one will say "I don't understand this notation" . The same is for summability, when we talk about generalized sum/resummation and we only use the term sum I don't see much a big ambiguity
Comment: @Michael you can find an entire book by the Springer about Ramanujan summation and its different definitions
Answer: As an exercise in learning about "divergent series" and their classical summation-procedures I played with a method which is based on a matrix-transformation using the "Eulerian numbers". It is often "stronger" than Euler-summation (of any order), can sum not only the geometric series with $q<1$ but also the alternating series of factorials (it is similar to Borel-summation) - but cannot sum the nonalternating versions of that series when they are classically divergent, and thus cannot sum not the harmonic series.
The pure series transformation using the matrix $E$ from a series $a_1+a_2+a_3+...$ into a vector $T$ containing the transforms looks like
$$  [a_1,a_2,a_3,...] \cdot E = [t_1, t_2,t_3,...] = T  $$
and for convergent and summable cases the partial sums of the $t_k$ approximate the sum of the series-terms on the lhs and we have then a usable series-summation method (it gives also convergence acceleration for the summable cases). For reference, I call this provisorically the "Eulerian transform" or "Eulerian summation".
For the given case of the harmonic series the method gives for the partial sums of the $t_k$ infinity and thus the harmonic series is not summable by the "Eulerian summation".
But besides this that partial sums give the following remarkable approximation (writing the $N$'th harmonic number as $H_N$)
$$ \sum_{k=1}^N t_k - H_N = \log 2 +\varepsilon_N
\qquad \qquad \lim_{N \to \infty} \varepsilon_N=0$$
which reminds of the formula for the Euler-Mascheroni-constant, but has a different constant term.

Remark: the method has not yet a sufficient theoretical framework but because the entries in $E$ have a tractable composition one can do relatively simple partial analyses for the self-study.
See initial exploration of E and the basic idea of summation method and for the current problem the investigation of the transform for some non-summable cases


HP ProLiant Smart Array "lock up" code 0x11

Question: I've a ProLiant DL580 G7 server that experienced a storage subsystem failure during production. The system appeared available and responded to pings, but all I/O access stalled (the system load must have been 100+). The ASR did not trigger at the specified watchdog timeout. I had to force a reboot from the ILO. During POST, I received the following error:
A controller failure event occurred prior to this power-up. (Previous lock up code = 0x11)
I haven't pulled the ADU report yet, but I'm curious as to what this error actually means. I was not responsible for the the installation, but can see that the firmware is very old. But if there's anything else I should know about the error, I'd like to know for the post-mortem report.
Edit - I should add that the server had 95 days of uptime prior to the lock up.
Answer: HP doesn't publish what the lock up codes mean. In my experience they always result in some hardware needing to be replaced. You'll have to pull the ADU and submit it to HP support.
Comment: Couldn't agree more Chris, this looks like either a suspect controller or possibly an issue with the FBWC, either way get HP to replace BOTH the controller and the cache.
Comment: Definitely a bad sign, time to get support involved.
Comment: Given that the uptime was 90+ days from initial installation, does this just seem like a premature failure of the component? I'm the thousands of HP servers I've deployed, I've only seen something like this twice. I was hoping we could get specifics on the meaning of the error code.
Comment: Definitely premature failure. If you can get the meaning of the code out of HP I'd be really impressed. For whatever reason they've been tight lipped on those lock-up codes.
Answer: I found this advisory which suggests that such an error requires a firmware upgrade for the SmartArray controller in question.
(Disclaimer: I'm a HP employee but not in storage, sales or support, I just have some hardware displaying the same error).
Comment: This led me to a better solution. I still think that something at the OS level is aggravating the controller, but firmware is a potential issue.


Do some tasks after a simplenews newsletter has been sent

Question: I need to unsubscribe users from a specific simplenews newsletter category after a newsletter of that category has been sent. The best way is to do this action after updating sent status of newsletter. but there are not a hook or event to do this. What is your opinion to implement this task?
Comment: Did you try using rules. I hope `simplenews` integrates with rules.
Comment: Simplenews only provides two events in rules: when a single user subscribes or unsubscribes.
Comment: Currently, I remove subscriptions in hook_simplenews_spooled. But it is not a good way to do this task.
Answer: The best way would be patch simplenews to offer more events.
Second best would be to override simplenews via a custom module to offer more events.
There are other options but those are the best following the Drupal way.


Trying to seed to mongoDB with an array of string, not sure what I am supposed to declare the model as

Question: So I am trying to test some seed data, with mongoDB, it is an ecommerce store and I am trying to parse in an array of categories but it gives an error. This is the products model
const { Schema, model } = require('mongoose');
const dateFormat = require('../utils/dateFormat');

const productSchema = new Schema({
  title: {
    type: String,
    required: 'The Product title is required',
    minlength: 1,
    maxlength: 280,
    trim: true,
  },
  description: {
    type: String,
    required: true,
    trim: true,
  },
  categories: [{
    type: Schema.Types.ObjectId,
    ref: 'Category',
  }],
  brand: {
    type: Schema.Types.ObjectId,
    ref: 'Brand',
    required: false
},
  image: {
    type: String,
    required: true,
    trim: true,
  },
  price: {
    type: Number,
    required: true,
    trim: true,
  },
  createdAt: {
    type: Date,
    default: Date.now,
    get: (timestamp) => dateFormat(timestamp),
  }
});

const Product = model('Product', productSchema);

module.exports = Product;

Brand model:
const { Schema, model } = require('mongoose');
const dateFormat = require('../utils/dateFormat');

const brandSchema = new Schema({
  name: {
    type: String,
    required: 'The Brand name is required',
    minlength: 1,
    maxlength: 280,
    trim: true,
  },
  products: [{
    type: Schema.Types.ObjectId,
    ref: 'Product',
  }],
  createdAt: {
    type: Date,
    default: Date.now,
    get: (timestamp) => dateFormat(timestamp),
  }
});

const Brand = model('Brand', brandSchema);

module.exports = Brand;

Category model
const { Schema, model } = require('mongoose');
const dateFormat = require('../utils/dateFormat');

const categorySchema = new Schema({
  name: {
    type: String,
    required: 'The Category name is required',
    minlength: 1,
    maxlength: 280,
    trim: true,
  },
  products: [{
    type: Schema.Types.ObjectId,
    ref: 'Product',
  }],
  createdAt: {
    type: Date,
    default: Date.now,
    get: (timestamp) => dateFormat(timestamp),
  }
});

const Category = model('Category', categorySchema);

module.exports = Category;

and this is a snippet of the seed data
    {
      "title": "Ansie Boots",
      "description": "2",
      "image": "http://via.placeholder.com/640x360",
      "price": 145,
      "categories": ["Boots", "For Her"],
      "brand":"Vagabond"
    }

I was reading the MongoDB docs and came across this $facet doc but I was a bit puzzled about what it was trying to do, as I am still a beginner.
 errors: {
    'categories.0': CastError: Cast to [ObjectId] failed for value "[ 'Trainers', 'For Him' ]" (type string) at path "categories.0" because of "CastError"

The error codes show me that the brands also
  stringValue: '"Nike"',
      messageFormat: undefined,
      kind: 'ObjectId',
      value: 'Nike',
      path: 'brand',
      reason: BSONTypeError: Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer

Comment: Could you also show us the `Category` and `Brand` models? The problem seems to lie there.
Comment: I've edited the post to add the `Category` and `Brand` models
Answer: In the Product model brand and categories are defined as ObjectIds that reference other models.
The the seed data these fields contain strings.
You will need to create instances of the Brand and Category models for each of those before you can refer to them.
If the seed process will be single-threaded, you might use something like this to get a brand document:
let branddoc = Brand.findOne({name: seedItem.name});
if (branddoc == null) {
   branddoc = new Brand({name:seedItem.name})
   branddoc.save()
}

Then replace the brand string in the seed item with the generated document, do the same process with each entry in the array of categories before creating the product document.


How to judge a mix, on e.g. muddiness and balance?

Question: I have been producing music for 7 years: And I have yet to understand how artists are able to tell what a proper mix sounds like. They often tell me that my mix sounds weird and "muddy", but I myself really can't tell what is wrong with it. I understand that to make a proper mix: You need to "reserve" frequencies on the band to make that instrument sound clean. But what If I have two instruments that lay on the same frequencies (And that happens a lot in my mixes since I produce Hardstyle)? How do I go about that?
Can anybody recommend any good source to really learn this? I have several books on this, and I've read them throughout. But I still can't differentiate between a bad mix and a professional mix with my ears.
Comment: Are you A/B listening to your mixes and others? One of the important things is to get a reference point, which might be knowing your equipment really well, or to listen to reference recordings which you are aware of how they sound, through the equipment you are using. If your mixes are considered muddy compared to other material, they probably have less treble than what they are compared too. This should be easy to hear. Ask for specific recordings, and compare them to your mixes.
Answer: It's all about practice and experience. You have to train your ears, you have to know your tools. Producing is not the same as mixing or mastering, some skills overlap but they need mostly different skill sets.
There are tools and techniques that will help you judge the frequency balance of a mix. You might eventually not need them at all, though some of the best mixing engineers keep them in their daily arsenal.

Listen to reference songs. Pick a set of professionally produced songs that are similar to whatever you are mixing. Look for songs that have a mix that you really like. Play your mix and the reference song separately and compare. If you are too high on lows, mids, highs, some instrument is too loud or too soft or whatever, do adjustments.
Use visual aids. This is specially useful if you don't trust your listening environment (ears, speakers, room, etc). This is most likely the case if you are not an experienced mixer with expensive monitors and acoustically treated room. You can use an spectrum analyzer to see what's going on in your mix. If you don't know what shapes and proportions to look for, use the spectrum analyzer in reference tracks to check roughly which forms you should aim for. Logic and Live have built-in spectrum analyzers in their native equalizers, if your DAW doesn't have one you can get FabFilter Pro-Q 2. There are many other visualizing plugins out there, so you might want to try many before making a choice.
Listen your mix through many different systems. Every part of your listening environment (room, speakers, equipment, etc) will color the sound (accentuate the mids, attenuate the highs, or whatever), so you want to listen your mix in different rooms, with different speakers. Try stereo, car, earbuds, etc. Find a good middle ground where your mix sounds good everywhere (at the same time understand the limitations of each system, lows will be lacking in small speakers and that's perfectly normal and fine). Reference tracks are again useful here, to give you an idea how each system should sound like.

These can be of great help, even to experienced mixing engineers, but are specially useful if you are just starting.

They often tell me that my mix sounds weird and "muddy", but I myself really can't tell what is wrong with it.

If you can't tell what's wrong with it, maybe it's because different tastes, or maybe you are not very sensible to the low frequencies (ear damage of some kind), or maybe you don't have a subwoofer and the other person does so you can't even hear muddiness he is referring to, maybe his room accentuates the lows. Who knows?
Again, your problem here is lack of experience. The solution is getting experience, so you are on the right track.
Mixing is both a science and an art. If you want to get philosophical about it, there's no such thing as a weird, bad, or good mix. The ideal balance is subjective. But if you are mixing for the masses, you want to take their tastes into consideration too.

I understand that to make a proper mix: You need to "reserve" frequencies on the band to make that instrument sound clean. But what If I have two instruments that lay on the same frequencies (And that happens a lot in my mixes since I produce Hardstyle)? How do I go about that?

There's nothing inherently wrong with having two elements in the same place and time (violin ensembles can sound beautiful), but if they are not working as a unity you usually want to separate them, otherwise it can turn into something similar to many people talking at the same time.
This has little to do with mixing and more to do with production, composition, and instrumentation. The art of when, where, what, and how to put stuff doesn't have a blanket answer for "how do I get about that?". Maybe you want to consider separating elements in time (so they don't sound at the same time) or in frequency (they use different octaves) or tonally (use another instrument, or tweak the timbre of the current one).
There's little you can do in the mix with instruments that clash in time and frequency. You can try some separation with panning or eq and filters, but the results are limited. If you think two elements clash too hard, you want to take your mixing hat off and put your composer hat on. Maybe that idea doesn't work as well as it did in your head, and needs a change in the composition level, not at the mixing level.

Can anybody recommend any good source to really learn this? I have several books on this, and I've read them throughout. But I still can't differentiate between a bad mix and a professional mix with my ears.

Reading is invaluable, but will do nothing for you if you don't practice using your ears.

First of all, pick an ear training program. I recommend you the Golden Ears program. Train daily.
Mix, mix, and mix. Mix at the very least one song daily.
Don't stop studying! There are great resources out there.

In short
There are many subtleness in sound dynamics, and training your ears to recognize them takes time and practice. Accurately judging the scenario takes knowledge. Practice, practice, and practice.
If you want to get serious about mixing, you want to get an audiometry. Test your ears and see if everything is ok so you can be sure any misinterpretation is because of lack of practice and not because something like ear damage.
Comment: No worries, looks like other people are picking up the slack. I really appreciate this response, I goof off with production occasionally and this sort of info really helps. I'll just add that you don't need to limit yourself too much with reference work- anything with comparable instrumentation, volume, even something that just sounds good can be of great use. With hardstyle, for example, you might like the way some jazz tracks handle the bass (clearly audible but not too domineering).
Answer: After listening to the example mix, I have a few specific comments:

there's a very strong likelihood that the monitoring is deficient. It is likely very hyped in the high end, and probably has a big hole in the low mids.
It's likely that you mix very loud.
Your mixes have a preponderance of very broad-band "large" synths, stacked on top of each other.

The result of mixing on monitors with a hyped high-end is that you'll roll off the highs to make them sound correct at your listening position, but they'll be "muddy" everywhere else.  The mix example you provided is significantly missing high end.
The result of mixing very loud, particularly in a small room, (or worse: on headphones) is that you'll tend to miss the stacking up of low mids, which contributes to muddiness.
The result of lots of full-range synths is that everything is competing for the same space.  I've heard it said over and over again by all the mixing greats that "the mute button is the most useful and least often used" tool in the mixer's kit.  You create impact by giving instruments a bit of room, you eliminate impact (i.e. make it "muddy") by over-layering them...especially when they're all broad-range "large" synths.
Your drums are absolutely buried in the mix and highly over-compressed.  This eliminates any possibility that they'll add impact, they instead add clutter.
The mix itself is highly compressed.  I know that this is the style these days, especially using a compressor hit hard to create pumping/breathing, but try dialing that back a bit, or at least increase the attack time, and see if you don't get more impact.
Doing "frequency carving" on instruments to make them sit together better is not nearly as useful as it seems it would be on paper.
Reverb is a contributor to muddyness. Try pulling back the decay time.
A "good" mix isn't just a function of making everything equal, at the same level.  A "good" mix allows the listener to "reach deep" into the mix and hear detail.  A common attribute of a "good" mix is that some particular instrument or sound is presented to the listener as the "primary" focus, and the instrument that gets primary focus is not necessarily the same one for the duration of the mix...focus gets tossed around between the instruments, adding to listener engagement.
Comment: You indeed hit perfectly in all your conclution steps.
1. I do have cheap 5' monitors from Tannoy. But I only use them when im arranging the track, so I use headphones for mixing (Though that was better for "cleaner" sound) 2. I do mix with quite loud volume (Again, thought it was better to hear smaller details). 3. I do indeed run very wide synths, and try to make them as fat as possible, especially the main parts such as Leads, Plucks, etc... You thought me a lot today, and I thank you for it :)
Comment: @AlexanderJohansen Interesting ! I mix rock and want it to sound as powerful and smacky as possible. (Don't google "smacky". . I just made it up lol). I've found the best way is to mix very quietly and make it so that I can hear the parts I want to poke through, then a bit louder for general tweaking - but not 'loud'. Ears get tired quickly and "studio tan" sets in more quickly (I start listening too hard and can't -er- hear the woods for the trees, as it were)
Comment: My experience of mixing though earphones is that it sounds awful through speakers afterwards - in my phones mixes, drums are generally very low and mushy, bass up too high. Some kind of phycho-acousting thing going on as it's not about frequency, more the closeness to the ear makinf punchy things like drums sound more punchy through phones than they are through a speaker. I don't know the physics behind that, just the effect.
Comment: some mixers do work loud.  I know a couple A-list guys that do, and it works for them.   They tend to work in nice rooms though...and I'm sure they would modify their habits if they were in the typical home studio.  Mixing in headphones is extremely problematic:  you have no way of knowing how the mix will work out in the open, the information just isn't there.
Answer: Just a bit bout "Muddiness":
Listening to your mixes (through good earphones), I can hear a bit of muddiness.. kind of..
"muddiness"  .. obviously it's not a technical term but if I take it to mean indistinct and lacking in sharpness, almost like slightly blurred image ..
Things that contribute to muddiness :

Lack of very high end frequencies. Sometimes this area brings out the detail and makes the mix come to life, especially on things like acoustic guitars. There aren't any in your mix but the same applies to vocals and other natural things, or percussion.
Too much lower middle range. If you consider that your ears hear as though they have comperssors built in, then too much lower middle will be where the mumbling non-detailed sounds are and too much can make the mix sound like it's being played in the next room. Not sure I'd say that's the case in your mixes though.
Lack of separation of frequencies for instruments : You're already aware of this.
Something "big" (long/dominant notes) too loud in the mix: My opinion is that the synth in your mix is bleeding over everything else. It seems like if you took it down just a little, other thigns would be able to poke through a bit more. This could be anythign in theory thouhg - a favourite mistake of mine is to have the bass guitar up too much, bleeding all over the bottom end of the guitar and making vocals sound thin and weedy. We live and learn.
Lack of dynamic range: Often caused by too much compression. Everything's squashed to fit into the same volume range - often a good thing - but sometimes the sound can suffer and lose definition. Eg at the point where a bass drum might strike, if someone starts singing at the same time, the vocal note drops to let the bass through and the overall effect is that the vocals sound indistinct. This can happen with percussion too.
Compressor has attack turned down: If this is the case then things like ride cymbals, shakers, P S and T sounds on vocals, anything with a sharp attack, will lose its defined "start" so will sound a bit mushy. It's hard to pinpoint this because such sounds are still there, just with less punch.
Answer: In my experience, when the artist complains that the mix sounds "muddy" it usually means that either it lacks brightness (for example: alot of mixing producers are afraid to add more treble to hihats and cymbals on drum track for fear that the mix will get all hissy, but in fact when you don't add treble to hihats and cymbals they can get "lost" in the mix due to electric guitars distortion, for example).
In other words, when all the instruments are "aligned", heard, and sound overall good, then the artist won't complain about the mix.
One good way to achieve this is to use sidechain ducking, and if you can and have the gear to it, even preffered is sidechain EQing.   For example: If you have electric guitars in your mix, they usually "catch" the frequency range of 400-4000 hz.  In this range you also have the singer, the drum's snare and toms, and sometimes even keyboard.   So what you do, is you use a sidechain EQ on the 500-1000hz range to "duck" the guitars when the singer joins the mix, and you add sidechain "ducking" on the 1000-1200hz range whenever the "snare" drum hits.
This way, you get to maintain a good sounding mix in which all the instruments are heard and nothing gets lost in the mix.
Of course, setting this up properly requires some planning, and learning what each instrument's dominant frequency range is.


O que é controle de concorrência?

Question: Sobre os estudos que eu estava fazendo  no momento em que eu perguntei O que é um semáforo?, me informaram que, pra eu entender melhor sobre esse termo, eu deveria estudar sobre Controle de Concorrência.
Alguém poderia me explicar do que se trata?
Comment: Só achei referente a banco de dados, [Técnicas de controle de
concorrência (CC)](http://www.ic.unicamp.br/~thelma/gradu/MC526/turma-2009/Slides-526/Aula17-Controle-Concorr.pdf)
Comment: Será o controle de concorrência trata problemas do tipo [deadlock](https://pt.stackoverflow.com/questions/64484/o-que-%C3%A9-deadlock-no-sql-server)?
Comment: A [página em inglês da wikipedia sobre o assunto é excelente](https://en.wikipedia.org/wiki/Concurrency_control).
Answer: De uma maneira bem simples, o controle de concorrência visa gerenciar o acesso a recursos compartilhados. O objetivo é controlar como múltiplos acessos podem utilizar um recurso sem conflitos, porque o acesso concorrente sou simultâneo pode gerar inconsistência dos dados.
Isso não se restringe a bancos de dados, mas podem ser variáveis de memória, arquivos físicos, threads, etc.
Existem diferentes formas de de gerenciar a concorrência (semáforo é uma delas):

Monitor é uma técnica utilizada para sincronizar tarefas que compartilham um recurso. ou seja, o monitor oferece uma interface para permitir a manipulação de um recurso compartilhado. Para tanto utiliza uma trava de exclusão mútua, que consiste de variáveis de controle e regras para liberar ou travar o recurso.
De maneira prática, o monitor basicamente é uma classe que controla o recurso, assim quando for preciso requisitá-lo devemos enviar o pedido para ela.
Lock é um mecanismo que isola o acesso a um recurso, limitando a um acesso de escrita por vez. Com isso, ele gerencia uma fila de acessos, ou seja, o primeiro a solicitar o lock ganha acesso ao recurso, e os acessos seguintes entram numa fila aguardando até que o lock seja liberado para ser concedido acesso ao próximo da fila. É bastante usado em bancos de dados para controlar o acesso a tabelas e registros.
Semáforo é um mecanismo de concorrência que controla a quantidade de acessos simultâneos a um recurso compartilhado. Seria semelhante a um semáforo de trânsito, mas não por tempo, e sim por quantidade de veículos que podem acessar uma via. Quando o número máximo de recursos disponíveis é atingido, as solicitações devem aguardar alguma tarefa ser concluída para ter acesso ao recurso compartilhado.

Alguns links interessantes sobre concorrência e semáforos:
https://www.revista-programar.info/artigos/threads-semaforos-e-deadlocks-o-jantar-dos-filosofos/
https://brizeno.wordpress.com/tag/semaforos/
http://www.inf.ufsc.br/~frank.siqueira/INE5645/3.%20Controle%20de%20Concorrencia.pdf
Answer: Complementando a resposta anterior, com outras palavras e exemplificando, é o que acontece em seu computador: Há vários programas e threads "querendo" ser executados pelo processador, usar a dados da cache, da memoria RAM, acessar dispositivos I/O, entre outros. O sistema precisa gerenciar isso de forma que não gere confusão entre informações, endereços de memoria, ou ate mesmo quando um programa/thread entra em região critica.
Impedir ou liberar acesso dos dispositivos quando puderem ser usados.

O que é controle de concorrência?


Generate random matrix with elements having spatial co-relation

Question: I want to generate an $N\times N$ matrix where in each element is a processor parameter.
Each cell has a value (process parameter) associated with it which can be modeled as a Gaussian random variable with fixed mean and standard deviation.
Also there is a spatial co-relation coefficient between each of the cells based on distance given by :
$$\rho = e^{-\alpha\sqrt{(i-k)^2 + (j-l)^2}} \forall i,j,k,l  \in [1,N]$$
How do I write a program to generate  a random matrix with the following properties ?
Answer: Matrix is really just a vector with an unusual layout. Since you know the correlation between the elements of the matrix, you can write down the matrix as $N^2$ vector with the corresponding correlation matrix. You have means, correlations and variances, hence you fully define a Gaussian random vector. Generate it using the usual software and then rearrange the vector into a matrix. Just respect the original order which was used to define the correlation matrix.
Comment: I am completely new to this field, can you point me to some of the code/libraries which generate such vectors
Comment: Have you tried googling it? Generate multivariate normal will get you lots of hits. For R there is a function `mvrnorm` in the package **MASS**.


Docker compose no response

Question: After docker-compose down and docker-compose up several times, sometime docker-compose up will cause no response. Normally, docker will tell you what container is created. But, nothing is shown. I try to quit Docker App and restart it. Cannot fix it. After restart OS, then docker-compose works fine.
Anyone know this issue?
Update:
Docker version: 1.12.0, build 8eab29e
Docker Composer Version: 1.8.0, build f3628c7
Platform: MacOS 10.11.4
Comment: Possible duplicate of [Stopping stubborn container?](http://stackoverflow.com/questions/42794503/stopping-stubborn-container)
Comment: What version of docker are you running and on what type of host?
Comment: Thanks @BMitch. i edited
Comment: I'd suggest you begin by updating Docker. You should have Docker version 17.03.1-ce, build c6d412e and docker-compose version 1.11.2, build dfed245. After that, it'd be helpful to see your docker-compose.yml file so we can better diagnose. What output are you getting when running docker-compose up?
Answer: You might need to run docker-compose ps to see what is currently running. If I were you I would like to kill the ps by running docker-compose kill and docker-compose rm. Atm the docker compose will be clean and you could run docker-compose up again
Answer: Finally, i found the core issue. For my environment, i use Charles as proxy server. I enable the Mac OS proxy in Charles. Once, i disable it. Docker will work fine.
Answer: Follow documentation on link:
https://docs.docker.com/compose/install/
I used on Ubuntu 16.04 command:
curl -L https://github.com/docker/compose/releases/download/1.14.0/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose
sudo chmod +x /usr/local/bin/docker-compose

After that check if it works. Output should looks like:
$ docker-compose --version
docker-compose version 1.10.1, build b252738

Docker compose no response


Finding subgroups of index 2 of $G = \prod\limits_{i=1}^\infty \mathbb{Z}_n$

Question: I looked at this question and its answer. The answer uses the fact that every vector space has a basis, so there are uncountable subgroups of index 2 if $n=p$ where $p$ is prime.
Are there uncountable subgroups of index 2 if $n$ is not prime ?
The problem looks the same (with minimal change), but the way we found the subgroups is not good for this case (I think).
Comment: Clearly we at least need $n$ to be even.
Answer: If $n$ is odd, $G$ has no subgroups of index $2$. Indeed, if $H$ is a subgroup of index dividing $2$, and $g\in G$, then $2g\in H$ (since $G/H$ has order $2$, so $2(g+H) = 0+H$). Since every element of $G$, hence of $H$, has order dividing $n$, and $\gcd(2,n)=1$, then $\langle 2g\rangle = \langle g\rangle$, so $g\in\langle 2g\rangle\subseteq H$, hence $g+H$ is trivial. That is, $G\subseteq H$. So the only subgroup of index dividing $2$ is $G$.
If $n$ is even, then let $H=2\mathbb{Z}_n$, which is of index $2$ in $\mathbb{Z}_n$. Then $G/\prod_{i=1}^{\infty} H \cong \prod_{i=1}^{\infty}(\mathbb{Z}_n/2\mathbb{Z}_n) \cong \prod_{i=1}^{\infty}\mathbb{Z}_2$.
Note: $\prod_{i=1}^{\infty} H$ is not itself of index $2$ in $G$; in fact, $\prod_{i=1}^{\infty} H$ has infinite index in $G$. We are using $\prod_{i=1}^{\infty}H$ to reduce to a previously solved case.
Since $\prod_{i=1}^{\infty}\mathbb{Z}_2$ has uncountably many subgroups of index $2$ by the previously solved case, by the isomorphism theorems so does $G$.

Below is an answer for the wrong group (I thought $G=\prod_{n=1}^{\infty}\mathbb{Z}_n$; I leave the answer because it is exactly the same idea.)
For each $n$, let $H_n$ be the subgroup of $\mathbb{Z}_n$ given by $2\mathbb{Z}_n$. Note that $H_n=\mathbb{Z}_n$ if $n$ is odd, and $H_n$ is the subgroup of index $2$ in $\mathbb{Z}_n$ if $n$ is even.
Now let $\mathcal{H}=\prod_{n=1}^{\infty}H_n$. Then
$$G/\mathcal{H}\cong\prod_{n=1}^{\infty}(\mathbb{Z}_n/H_n) = \prod_{n=1}^{\infty}(\mathbb{Z}/2\mathbb{Z}).$$
(In the last isomorphism, the odd-indexed quotients are trivial, the even-indexed quotients are isomorphic to $\mathbb{Z}/2\mathbb{Z}$; then delete all the trivial factors).
Since $G/\mathcal{H} \cong \prod_{n=1}^{\infty}(\mathbb{Z}/2\mathbb{Z})$ has uncountably many subgroups of index $2$, so does $G$ by the isomorphism theorems.
Comment: I'm trying to understand why does n have to be even, I got to the point that any subgroup 'have to be a subgroup in every coordinate' but I can't explain to myself why if the subgroup is of index 2 then in every coordinate we have a subgroup of index 2...
Comment: @Belgi: What point? It is **not** true that a subgroup "has to be a subgroup in every coordinate"! Just think about the Klein $4$-group, $\mathbb{Z}_2\times\mathbb{Z}_2$. The subgroup $\{(0,0),(1,1)\}$ is not a "subgroup in every coordinate." However, having a subgroup in every coordinate *does* yield a subgroup of the product. And note that $H$ is **not** a subgroup of index $2$! Instead, I use $H$ to get to a group which we *know* has subgroups of index $2$. If $K$ is a subgroup of index $2$ **in $G/H$**, then there exists a subgroup $\mathcal{K}$ of $G$, (cont)
Comment: @Belgi: such that $H\subseteq\mathcal{K}$, and $\mathcal{K}/H = K$. By the Isomorphism Theorems, $G/\mathcal{K} \cong (G/H)/(\mathcal{K}/H) = (G/H)/K$, and since $(G/H)/K$ has two elements, that means that $[G:\mathcal{K}]=2$. *Nowhere* did I claim, or even imply, that $H$ itself had index $2$. I'm using the isomorphism theorems: There is a one-to-one, inclusion preserving, index-preserving correspondence between subgroups of $G/H$ and subgroups of $G$ that contain $H$.
Comment: Thank you for the correction, I also don't understand the claim "all elements of G have odd order" - If I were to deal with a finite group I could of used lagrange theorem, but with an infinite group I'm a bit lost...
Comment: @Belgi: If $g\in G$, then $g=(a_1,\ldots,a_k,\ldots)$, with $a_i\in \mathbb{Z}_n$ for all $i$. Therefore, $ng = (na_1,\ldots,na_k,\ldots)$, and since $a_i\in\mathbb{Z}_n$, then $na_i=0$ for all $i$. So $ng = (0,0,\ldots,0)$, hence the order of $g$ divides $n$, hence the order of $g$ is odd if $n$ is odd.
Comment: Thanks again. is it ok to say "$H$ has infinite index in $G$" ? do you mean $Hx${0}x{0}x.. ?
Comment: @Belgi: No, it's not okay; it's the result of incompatible nomenclature in the first and second half; I'll fix it.