Finding non-zero function such that $f(2x)=f'(x)\cdot f''(x)$

Question: I am thankful if someone can help me or show me the clue. As honestly as possible, I got stuck on this problem.
I need some help in finding a $f(x)\neq 0$ such that $$f(2x)=f'(x) \cdot f''(x),$$ where $f',f''$ are the first and second derivatives, respectively. It is not an ordinary differential equation.
My last try was to put $f(x)=ke^{ax}$, and then
$$ke^{2ax}=kae^{ax}\cdot ka^2e^{ax}.$$ Now by canceling $e^{ax}$, we have $$k=k^2a^3.$$ This shows $k=1,a=1$ and finally $f(x)=e^{x}$. But I want to solve the problem analytically.
Comment: How $k = k^2 a^3$ gives $k=1, a=1$? Since you're asking $k\ne 0$ this gives $k = 1/a^3$, and that gives the family of solutions $\frac{1}{a^3} e^{a x}$.
Comment: Another solution is $f_3(x)=\frac{\sinh (x\sqrt{2})}{\sqrt{2}}$. Found using Taylor expansion of $f(x)$. Using $a_0=1$, $a_1=1$ gives $f(x)=e^x$. Using $a_0=0$, $a_1=0$ gives $f(x)=\frac{4x^3}{9}$. Using $a_0=0$, $a_1=1$ gives $f_3(x)$.
Comment: To my knowledge, this problem cannot be solved analytically without guessing.
Comment: @RamanujanXV. thanks but it's not the same idea... because of multiplication of f',f''
Comment: There are more solutions. For example:
$f(x) = \frac{4}{9}x^{3}$

$f'(x) = \frac{4}{3}x^{2}$

$f''(x) = \frac{8}{3}x$

Then $f(2x) = \frac{32}{9}x^{3} = \frac{4}{3}x^{2} \cdot \frac{8}{3}x = f'(x) \cdot f''(x)$. Anyway, I don't know a general solution
Comment: perhaps looking at periodic functions and working with $ \hat{f}'\left(n\right)\cdot\hat{f}''\left(n\right)=\hat{f}\left(2n\right)\Rightarrow-in^{3}\left(\hat{f}\left(n\right)\right)^{2}=\hat{f}\left(2n\right) $ might provide a simple solution by just guessing a few Fourier coefficients.
Answer: Too long for a comment.
Assuming $f(x)$ is polynomial of degree $n$, we have $n = (n-1)+(n-2)$ or $n = 3$. Therefore we can look for $f$ in the following form:
$$\begin{align}
f(x) &= a{x^3} + b{x^2} + cx + d \\
f'(x) &= 3a{x^2} + 2bx + c \\
f''(x) &= 6ax + 2b \end{align}$$
Then,
$$f(2x) = f'(x) \cdot f''(x) \implies \begin{cases}8a = 18a^2 \\ 4b = 18ab \\ 2c = 4b^2 + 6ac \\
d = 2bc\end{cases}$$
which gives the solutions $(0,0,0,0)$ or $(4/9,0,0,0)$. So the only polynomial solution is $$f(x) = \frac{4}{9}x^3$$
Answer: So I think one of the difficulties with this problem is that even when restricted to entire functions it is still super open. Basically, as long as you set the initial values for $f(0)$ and $f'(0)$ you get a new function. We shall investigate this equation for entire, complex functions.
Case 1: Let $f(0)=a\neq 0$ and $f'(0)=0$. Then we get
$$0=f(0)-f'(0)f''(0)=a-0f''(0)=a\neq 0$$
which is a contradiction.
Case 2: Let $f(0)=0$ and $f'(0)=0$. We can differentiate the given equation and solve for unknowns to find
$$f''(0)=0$$
$$f^{(3)}(0)=\frac{8}{3}\text{ or }f^{(3)}(0)=0$$
In fact, it won't matter which value $f^{(3)}(0)$ takes as the rest of the coefficients turn out to be $0$. To prove this, we will start with a complicated induction proof.
Claim: For $n\geq 4$, differentiating the given equation $n$ times gives us an equation of the form
$$0=2^n f^{(n)}(2x)-f'(x)f^{(n+2)}-(n+1)f''(x)f^{(n+1)}(x)$$
$$-\frac{n(n+1)}{2}f^{(3)}(x)f^{(n)}(x)+\sum_{i=4}^{\frac{n+5}{2}}c_if^{(i)}(x)f^{(n-i+3)}(x)$$
for odd $n$ and
$$0=2^n f^{(n)}(2x)-f'(x)f^{(n+2)}(x)-(n+1)f''(x)f^{(n+1)}(x)$$
$$-\frac{n(n+1)}{2}f^{(3)}(x)f^{(n)}(x)+\sum_{i=4}^{\frac{n+4}{2}}c_if^{(i)}(x)f^{(n-i+3)}(x)$$
for even $n$. Here, the coefficients $c_i$ are complex numbers and unimportant for the rest of the answer. This is easy to check for $n=4$ and $5$ by simply computation:
$$n=4: 0=16 f^{(4)}(2 x)-f^{(6)}(x) f'(x)-5 f^{(5)}(x) f''(x)-10 f^{(3)}(x) f^{(4)}(x)$$
$$n=5: 0=32 f^{(5)}(2 x)-10 f^{(4)}(x)^2-f^{(7)}(x) f'(x)-6 f^{(6)}(x) f''(x)-15 f^{(3)}(x) f^{(5)}(x)$$
Now, if $n$ is even, then we have
$$0=\frac{d}{dx}\left[2^n f^{(n)}(2x)-f'(x)f^{(n+2)}(x)-(n+1)f''(x)f^{(n+1)}(x)\right.$$
$$\left.-\frac{n(n+1)}{2}f^{(3)}(x)f^{(n)}(x)+\sum_{i=4}^{\frac{n+4}{2}}c_if^{(i)}(x)f^{(n-i+3)}(x)\right]$$
$$=2^{n+1} f^{(n+1)}(2x)-f'(x)f^{(n+3)}(x)-(n+2)f^{(3)}(x)f^{(n+1)}(x)$$
$$-\frac{(n+1)(n+2)}{2}f^{(3)}(x)f^{(n+1)}(x)-\frac{n(n+1)}{2}f^{(4)}(x)f^{(n)}(x)+\frac{d}{dx}\left[\sum_{i=4}^{\frac{n+4}{2}}c_if^{(i)}(x)f^{(n-i+3)}(x)\right]$$
It is slightly tedious to show but it is also the case that
$$-\frac{n(n+1)}{2}f^{(4)}(x)f^{(n)}(x)+\frac{d}{dx}\left[\sum_{i=4}^{\frac{n+4}{2}}c_if^{(i)}(x)f^{(n-i+3)}(x)\right]=\sum_{i=4}^{\frac{n+5}{2}}c^{'}_if^{(i)}(x)f^{(n-i+3)}(x)$$
as desired. The same can be shown starting with odd $n$. Having this formula, we can now show that for $n\geq 4$, we must have $f^{(n)}(0)=0$. Since it is easy to show that $f^{(4)}(0)=f^{(5)}(0)=0$, assume that for some $n> 5$ we have $f^{(m)}(0)=0$ for all $4\leq m<n$. In conjunction with the fact that $f(0)=f'(0)=f''(0)=0$, this gives us that for even $n$ we have
$$0=2^n f^{(n)}(0)-f'(0)f^{(n+2)}(0)-(n+1)f''(0)f^{(n+1)}(0)$$
$$-\frac{n(n+1)}{2}f^{(3)}(0)f^{(n)}(0)+\sum_{i=4}^{\frac{n+4}{2}}c_if^{(i)}(x)f^{(n-i+3)}(0)$$
$$=2^n f^{(n)}(0)-\frac{n(n+1)}{2}f^{(3)}(0)f^{(n)}(0)=f^{(n)}(0)\left(2^n-\frac{n(n+1)}{2}f^{(3)}(0)\right)$$
Since $f^{(3)}(0)\in\left\{\frac{8}{3},0\right\}$, this implies
$$0=\frac{0}{\left(2^n-\frac{n(n+1)}{2}f^{(3)}(0)\right)}=f^{(n)}(0)$$
as desired. The logic is the same for odd $n$. In total, we have proved that if $f(0)=f'(0)=0$, then
$$f(x)\in\left\{0,\frac{4}{9}x^3\right\}$$
Case 3: This case is the most complicated and ambiguous of the three. Suppose that $f(0)=a$ and $f'(0)=b\neq 0$. At this point I don't really know where to go. It's not too bad to solve for as many of the generalized coefficients as you like. In fact, the first eight are
$$\left\{a,b,\frac{a}{b},\frac{2 b^3-a^2}{b^3},\frac{a \left(3 a^2-2 b^3\right)}{b^5},\frac{-15 a^4+12 a^2 b^3+4 b^6}{b^7},\frac{105 a^5-92 a^3 b^3-12 a b^6}{b^9},\frac{-945 a^6+822 a^4 b^3+116 a^2 b^6+8
   b^9}{b^{11}},\frac{10395 a^7-7686 a^5 b^3-2668 a^3 b^6-40 a b^9}{b^{13}},\frac{-135135 a^8+56280 a^6 b^3+74648 a^4 b^6+4192 a^2 b^9+16 b^{12}}{b^{15}},\frac{2027025 a^9+430920 a^7 b^3-2009736 a^5
   b^6-448096 a^3 b^9-112 a b^{12}}{b^{17}},...\right\}$$
If we only look at $(f(0),f'(0))=(a,b)$, there are some interesting functions which pop out;
$$\left(\frac{1}{c^3},\frac{1}{c^2}\right)=\frac{1}{c^3}e^{cx}$$
$$(-1,1)=-e^{-x}$$
$$\left(0,\frac{2}{c}\right)=\frac{2 \sinh (c x)}{c^3}$$
$$\left(0,-\frac{2}{c}\right)=-\frac{2 \sin \left(\sqrt{c} x\right)}{c^{3/2}}$$
which are all the functions previously discussed in answers and comments. For a complex example, we can use the exponential example we found above to get
$$\left(-1,e^{\frac{2\pi i}{3}}\right)=-e^{-e^{\frac{2 \pi i }{3}} x}$$
Comment: Probably a typo. $\frac{2 \sinh(cx)}{c^2}$ is not a solution, $\frac{2\sinh(cx)}{c^3}$ is.
Comment: Whoops, thanks.
Answer: As was observed in answers and comments, the only polynomial solution is $f(x)=\frac{4}{9}x^3$.
Your own work leads to the solutions $f(x) = \frac{1}{a^3}e^{a x}$.
Adding the initial conditions $f(0)=0$, $f'(0)\ne 0$ and assuming that $f$ is analytic, looking at the coefficients of the Taylor series we get $f(x) = \frac{2}{a^3} \sinh(a x)$
Without the initial conditions $f(0)=0$ and using the Taylor series it's clear that there's more solutions, but probably there's no simple formula for the coefficients of the series.
Without the assumption of the function been analytic, I have no idea how the problem could be attacked.
Answer: If $f$ is a solution and $a$ a positive number then $a^{-3}f(ax)$ is also a solution, as the examples so far illustrate.
Answer: Notice that $f'(x)\cdot{f''(x)}=\frac12(f'\cdot{f'})'(x)=f(2x),$ so that $(f'\cdot{f'})'(x)=2f(2x).$ Let $F$ be the antiderivative of $f$ with $F(0)=0.$ As such, let $F_2(x)=F(2x),$ so $F_2'(x)=2F'(2x)=2f(2x).$ Therefore, $f'(x)^2-f'(0)^2=F(2x).$ Perhaps the latter is more easily solvable for $f$ in terms of $F,$ and the equation can then latter be solved for $F$ when reformulated in terms of $F.$
Comment: such a nice idea. Thank you


Generating DAG from another DAG

Question: I want to crate DAG from another DAG dynamically, e.g. when operator will trigger this parent DAG, it should generate new dag.
The following codes runs without errors but DAG is not created.
I can't see the reason.
def generate_dag():

    def do_something():
        print('something')

    default_args = {
        'schedule_interval': '@hourly',
        'start_date': datetime(2022, 1, 1),
        'is_paused_upon_creation': True
    }

    dag = DAG("generated_dag",
              default_args=default_args,
              catchup=False
              )
    with dag:
        do_something = PythonOperator(
            task_id="do_something",
            python_callable=do_something,
            dag=dag
        )
        do_something

    return dag

default_args = {
    'owner': 'airflow',
    'max_active_runs': 1,
    'retries': 0
}

dag = DAG(
    'createme',
    default_args=default_args,
    schedule_interval=None,
    start_date=datetime(2019,4,29),
    catchup=False,
    is_paused_upon_creation=False,
)

def create_dag():
    dag = generate_dag()

    globals()['generated_dag'] = dag

create = PythonOperator(
    task_id="create",
    python_callable=create_dag,
    dag=dag
)
create

I don't want to generate DAG python files in the dags folder.
Answer: You don't need the createme DAG, just run create_dag. Astronomer has a great article with examples https://www.astronomer.io/guides/dynamically-generating-dags/
from datetime import datetime
from airflow.operators.python import PythonOperator
from airflow import DAG

def generate_dag():

    def do_something():
        print('something')

    default_args = {
        'schedule_interval': '@hourly',
        'start_date': datetime(2022, 1, 1),
        'is_paused_upon_creation': True
    }

    dag = DAG("generated_dag",
              default_args=default_args,
              catchup=False
              )
    with dag:
        do_something = PythonOperator(
            task_id="do_something",
            python_callable=do_something,
            dag=dag
        )
        do_something

    return dag

def create_dag():
    dag = generate_dag()

    globals()['generated_dag'] = dag

create_dag()

Generating DAG from another DAG


Why is ${\phi}:(Z, +) \to U_n$ surjective?

Question:
Let $U_{n}$ be the multiplicative group of the $n^\text{th}$ roots of unity; this group is cyclic of order $n$ and is generated by ${\omega} = $$\cos(\frac{2{\pi}}{n}) + i$$\sin(\frac{2{\pi}}{n})$. If we define ${\phi}:(Z, +) \to U_n$ by the equation ${\phi(a)} = {\omega^a}$, show that ${\phi}$ is a homomorphism. Is ${\phi}$ a monomorphism? an epimorphism? an isomorphism?

So, the book that I'm working in explains that the function ${\phi}$ is a homomorphism, which I understand. But, I'd like to know how one can easily show that ${\phi}$ is an epimorphism; that is, how do I show that it is surjective? I can easily find a counterexample in which ${\phi}$ is not one-to-one using the group $U_{4}$, since $1 = {\phi(0)} = {\phi(4)}$. I'd appreciate some help.
Comment: Should your title say surjective instead of not surjective?
Comment: you're right, let me change that
Answer: Pick an element in $U_n$. Can you think of some canonical way of writing it down? (Hint: You know the generator of the group).
Answer: Given $z\in U_n$, you know that $z=e^{i2\pi \frac{k}{n}}$ for some $0\leq k< n$. Then, you can choose precisely $k$ to get $w^k=z$, since $w^k=(e^{i\frac{2\pi}{n}})^k=e^{i\frac{2k\pi}{n}}=z$.


Trabalhando com Generics

Question: Primeiro, a tarefa:

Crie uma nova classe Map, agora usando o nome SortedMap. Ela deve ter
  os mesmos métodos da classe Map da tarefa anterior, e aceitar como
  tipo Chave um tipo K que implemente a interface Comparable. O array
  de pares Chave, Valor deve ser mantido ordenado. Para isso, a cada
  inserção busque a posição correta para inserir e mova todos os
  elementos posteriores do array uma posição.
O método find pode agora realizar um pesquisa binária (chame o método
  pesquisa binária dado no laboratório).

Esse é um trabalho de laboratório, portanto eu já realizei a implementação da classe Map e já fiz algumas alterações para implementar a SortedMap. Fiz a troca dos tipos para 'K' e 'V'. Colocarei o código a seguir e será mais fácil de visualizar.
Implementação da classe Map:
public class Map {

    public static class Pair {
        Object key, value;
    }

    Pair[] m;

    /*
     * Construtor da classe Map
     * Inicializa um array com tamanho 2 e inicializa cada espaço desse array com os atributos Object key e value
     */
    public Map () {
        m = new Pair[2];
        //Atentar à esse detalhe! Cada espaço do array M ta sendo inicializado com os atributos do tipo Pair
        for( int i = 0; i < m.length; i++ )
            m[i] = new Pair();
    }

    /*
     * Método put: associa o valor a chave. Se a chave nao existir, encontra um espaço vazio (que se não houver, é aumentado o tamanho do array).
     * Caso a chave exista, atualiza-se o valor correspondente
     */
    public void put(Object key, Object value) {
        int posicao = find(key);

        if( posicao == -1 ) {
            posicao = makeRoom();
            m[posicao].key = key;
        }

        m[posicao].value = value;
    }

    /*
     * Método expand: dobra o tamanho do array e inicializa todos os espaços gerados com atributos da classe Pair
     */
    private void expand () {
        Pair[] newVector = new Pair[m.length*2];

        for ( int i = 0; i < m.length; i++ )
            newVector[i] = m[i];

        for( int i = m.length; i < newVector.length; i++ )
            newVector[i] = new Pair();

        m = newVector;
    }

    /*
     * Método find: localiza uma chave no array, se não encontrar, retorna -1
     */
    private int find(Object key) {
        for( int i = 0; i < m.length; i++ )
            if(key.equals(m[i].key))
                return i;

        return -1;
    }

    /*
     * Método get: retorna o valor correspondente a chave. Se não encontrar a chave, retorna null
     */
    public Object get(Object key) {
        int posicao = find(key);
        if( posicao == -1 )
            return null;
        else
            return m[posicao].value;
    }

    /*
     * Método remove: remove o valor e a chave passada, caso existam
     */
    public void remove (Object key) {
        int posicao = find(key);
        if( posicao != -1 ) {
            m[posicao].key = null;
            m[posicao].value = null;
        }
    }

    /*
     * Método keys: cria e retorna um array com todas as CHAVES presentes na estrutura
     */
    public Object[] keys () {
        Object[] allKeys = new Object[numKeys()];

        for( int i = 0, j = 0; i < m.length; i++ )
            if( m[i].key != null )
                allKeys[j++] = m[i].key;

        return allKeys;
    }

    /*
     * Método numKeys: Conta quantas chaves foram declaradas na estrutura e retorna o valor
     */
    public int numKeys () {
        int totalKeys = 0;

        for( int i = 0; i < m.length; i++ )
            if( m[i].key != null )
                totalKeys++;

        return totalKeys;
    }

    /*
     * Método makeRoom: busca por espaço null e retorna a posição. Caso não encontre, dobra o tamanho do array e retorna a primeira posição livre do novo array
     */
    private int makeRoom() {
        for( int i = 0; i < m.length; i++ )
            if( m[i].key == null )
                return i;

        int posicao = m.length;
        expand();
        return posicao;
    }

}

Implementação da SortedMap (classe Map com os tipos alterados para utilização de Generics).
public class SortedMap<K, V> implements Comparable<K> {

public static class Pair {
    Object key, value;
}

Pair[] m;

/*
 * Construtor da classe Map
 * Inicializa um array com tamanho 2 e inicializa cada espaço desse array com os atributos Object key e value
 */
public SortedMap () {
    m = new Pair[2];
    //Atentar à esse detalhe! Cada espaço do array M ta sendo inicializado com os atributos do tipo Pair
    for( int i = 0; i < m.length; i++ )
        m[i] = new Pair();
}

/*
 * Método put: associa o valor a chave. Se a chave nao existir, encontra um espaço vazio (que se não houver, é aumentado o tamanho do array).
 * Caso a chave exista, atualiza-se o valor correspondente
 */
public void put(K key, V value) {
    int posicao = find(key);

    if( posicao == -1 ) {
        posicao = makeRoom();
        m[posicao].key = key;
    }

    m[posicao].value = value;
}

/*
 * Método expand: dobra o tamanho do array e inicializa todos os espaços gerados com atributos da classe Pair
 */
private void expand () {
    Pair[] newVector = new Pair[m.length*2];

    for ( int i = 0; i < m.length; i++ )
        newVector[i] = m[i];

    for( int i = m.length; i < newVector.length; i++ )
        newVector[i] = new Pair();

    m = newVector;
}

/*
 * Método find: localiza uma chave no array, se não encontrar, retorna -1
 */
private int find(K key) {

    pesquisaBinaria(key, m, 0, m.length);

    return -1;
}

/*
 * Método get: retorna o valor correspondente a chave. Se não encontrar a chave, retorna null
 */
@SuppressWarnings("unchecked")
public V get(K key) {
    int posicao = find(key);
    if( posicao == -1 )
        return null;
    else
        return (V) m[posicao].value;
}

/*
 * Método remove: remove o valor e a chave passada, caso existam
 */
public void remove (K key) {
    int posicao = find(key);
    if( posicao != -1 ) {
        m[posicao].key = null;
        m[posicao].value = null;
    }
}

/*
 * Método keys: cria e retorna um array com todas as CHAVES presentes na estrutura
 */

  @SuppressWarnings( "unchecked" )
    public Vector<K> keys() {
        Vector<K> keySet = new Vector<K>(numKeys());
        for( int i = 0, j = 0; i < m.length; i++ )
            if( m[i].key != null )
                keySet.put(j++, (K) m[i].key );
        return keySet;
    }

/*
 * Método numKeys: Conta quantas chaves foram declaradas na estrutura e retorna o valor
 */
public int numKeys () {
    int totalKeys = 0;

    for( int i = 0; i < m.length; i++ )
        if( m[i].key != null )
            totalKeys++;

    return totalKeys;
}

/*
 * Método makeRoom: busca por espaço null e retorna a posição. Caso não encontre, dobra o tamanho do array e retorna a primeira posição livre do novo array
 */
private int makeRoom() {
    for( int i = 0; i < m.length; i++ )
        if( m[i].key == null )
            return i;

    int posicao = m.length;
    expand();
    return posicao;
}

 public static <K extends Comparable<K>> int pesquisaBinaria( K key, K m, int begin, int end ) {
        int i = (begin + end) / 2;
        if( m[i] == key )
            return i;
        if( begin >= end )
            return -1; // Não foi encontrado
        else if( m[i].compareTo( key ) < 0 )
            return pesquisaBinaria( key, m, i + 1, end );
        else
            return pesquisaBinaria( key, m, begin, i - 1 );
    }

@Override
public int compareTo(K o) {

    return 0;
}

}
O problema ocorre quando eu chego no método 'keys()'. Preciso criar uma classe Vector, porque não há como, no método keys(), retornar um Vetor de tipo genérico. Então pelo que eu entendi da explicação do professor, eu devo criar uma classe Vector (ele colocou uma como exemplo, mas eu gostaria de fazer a minha para aprender e entender como tudo está funcionando). O penúltimo é a buscaBinaria() dada em laboratório e que deve ser implementada no método find(). O último método é o compareTo, que precisa ser implementado mas eu não sei como fazê-lo.
Se eu não tiver sido claro na dúvida, é só perguntar. Obrigado! :)
CLASSES PARA TESTE DO PROGRAMA -- PROFESSOR
Atentar ao fato de que alguns métodos do professor estão com nomes diferentes no meu código
Implementação da SortedMap:
// Generics: construção que permite passar um tipo como parâmetro
// Pode ser usado para Classes e para métodos.
public class Map< Tipo_Key, Tipo_Value > {

    public static class Pair {
        // Transformando o map em String => Integer
        public Object key;
        public Object value;
    }

    Pair[] m;

    public Map() {
        m = new Pair[2];

        for( int i = 0; i < m.length; i++ )
            m[i] = new Pair();
    }

    /**
     * Expande o array m.
     */
    private void expand() {
        Pair[] novo = new Pair[2 * m.length];

        for( int i = 0; i < m.length; i++ )
            novo[i] = m[i];

        for( int i = m.length; i < novo.length; i++ )
            novo[i] = new Pair();

        m = novo;
    }

    /**
     *
     * @param key
     *            A chave que vai ser inserida. Não pode ser null.
     * @param value
     *            O valor a ser associado a esta chave
     */
    public void put( Tipo_Key key, Tipo_Value value ) {
        int posicao = find( key );

        if( posicao == -1 ) {
            posicao = makeRoom();
            m[posicao].key = key;
        }

        m[posicao].value = value;
    }

    private int find( Tipo_Key key ) {
        for( int i = 0; i < m.length; i++ )
            if( key.equals( m[i].key ) )
                return i;

        return -1;
    }

    /**
     * Encontra uma chave null. Se for preciso, expande o array m.
     *
     * @return
     */
    private int makeRoom() {
        for( int i = 0; i < m.length; i++ )
            if( m[i].key == null )
                return i;

        int posicao = m.length;
        expand();
        return posicao;
        // ou return m.length - 1;
    }

    /**
     * Retorna o valor associado a uma chave.
     *
     * @param key
     *            a chave
     * @return o valor associado, ou null.
     */
    @SuppressWarnings( "unchecked" )
    public Tipo_Value get( Tipo_Key key ) {
        int posicao = find( key );

        return posicao == -1 ? null : (Tipo_Value) m[posicao].value;
    }

    /**
     * Retorna o número de chaves não nulas no map
     *
     * @return o número de chaves.
     */
    public int getNumKeys() {
        int numKeys = 0;

        for( int i = 0; i < m.length; i++ )
            if( m[i].key != null )
                numKeys++;

        return numKeys;
    }

    /**
     * Remove uma chave e o seu valor do Map. Se não encontrar, não faz nada.
     *
     * @param key
     *            A chave do valor a ser removido
     */
    public void remove( Tipo_Key key ) {
        int posicao = find( key );

        if( posicao != -1 ) {
            m[posicao].key = null;
            m[posicao].value = null;
        }
    }

}

Implementação do método keys():
/**
     * Retorna um array contendo todas as chaves no map.
     *
     * @return o array de chaves.
     */
    @SuppressWarnings( "unchecked" )
    public Vector<Tipo_Key> keys() {
        Vector<Tipo_Key> keySet = new Vector<Tipo_Key>(getNumKeys());

        for( int i = 0, j = 0; i < m.length; i++ )
            if( m[i].key != null )
                keySet.put(j++, (Tipo_Key) m[i].key );

        return keySet;
    }

Implementação da classe Vector:
Pelo que eu entendi, não é possível retornar um vetor de tipo genérico no método keys, sendo necessário criar essa classe
public class Vector<T> {

    private Object o[];

    public Vector( int size ) {
        o = new Object[size];
    }

    public void resize( int newSize ) {
        Object novo[] = new Object[newSize];

        for( int i = 0; i < o.length; i++ )
            novo[i] = o[i];
    }

    public void put( int i, T value ) {
        o[i] = value;
    }

    @SuppressWarnings( "unchecked" )
    public T at( int i ) {
        return (T) o[i];
    }

    public String toString() {
        String aux = "[";

        for( int i = 0; i < o.length - 1; i++ )
            aux += o[i] + ",";

        if( o.length > 0 )
            aux += o[o.length - 1];

        return aux + "]";
    }

    public int find( T value ) {
        for( int i = 0; i < o.length; i++ )
            if( o[i].equals( value ) )
                return i;

        return -1;
    }

    public int size() {
        return o.length;
    }
}

Implementação da buscaBinaria() dada em laboratório:
  public static <T extends Comparable<T>> int pesquisaBinaria( T key, T v[], int begin, int end ) {
        int i = (begin + end) / 2;

        if( v[i] == key )
            return i;
        if( begin >= end )
            return -1; // Não foi encontrado
        else if( v[i].compareTo( key ) < 0 )
            return pesquisaBinaria( key, v, i + 1, end );
        else
            return pesquisaBinaria( key, v, begin, i - 1 );
    }

Implementação da classe Teste:
Onde está localizada a main para execução e teste do programa
public class Teste {

    public static void main( String[] args ) {
        Map<String, Integer> m = new Map<String, Integer>();
        Map<Integer, String> nMes = new Map<Integer, String>();
        String mes = "Feve", resto = "reiro";

        m.put( "Janeiro", 31 );
        m.put( "Fevereiro", 28 );

        nMes.put( 2, "Fevereiro" );

        System.out.println( "FEV: " + m.get( mes + resto ) );
        // Imprime 28

        m.put( "Fevereiro", 29 );

        System.out.println( m.get( "Fevereiro" ) );
        // Imprime 29

        Vector<String> chave = m.keys();
        for( int i = 0; i < chave.size(); i++ )
            System.out.println( chave.at( i ) + "=>" + m.get( chave.at( i ) ) );

        //for( String k : m.keys() )
        //    System.out.println( k + " => " + m.get( k );

        m.remove( "Janeiro" );

        System.out.println( m.get( "Fevereiro" ).getClass().getName() );
        int numDias = m.get( "Fevereiro" );

        if( numDias < 30 )
            System.out.println( "Não tem 30" );
    }
}

Answer: Usando mais os tipos genéricos
Aqui, poderia usar K e V como tipos da chave e do valor, respectivamente:
public class SortedMap<K, V> implements Comparable<K> {

    public static class Pair {
        Object key, value;
    }

Além disso, você pode forçar o tipo K ser algo que implemente Comparable.
Exemplo:
public class SortedMap<K extends Comparable<K>, V> implements Comparable<K> {

    public static class Pair {
        K key;
        V value;
    }

Método keys()
Não posso dizer sobre o que o professor pensa, mas pelo enunciado e pela implementação de Map, meu entendimento é que o método keys() em SortedMap poderia ter a seguinte assinatura:
public K[] keys() { ... }

Você poderia optar por abstrair o array em uma classe como Vector, mas esta nada mais seria do que um objeto contendo um array interno e alguns métodos de acesso como size() e get(). Se tiver tempo, pode fazer isto, mas não vejo como essencial.
Comparando
Na verdade, a classe SortedMap não tem que comparar nada. Quem implementa Comparable e consequentemente o método compareTo é o tipo que é usado como chave do mapa.
Por exemplo, se você usa String ou Integer ou qualquer tipo básico do Java, tal método já é implementado e você não precisa fazer nada.
A ideia da interface Comparable é que você pode implementar a interface arbitrariamente em qualquer classe comparando quaisquer atributos que ela tenha para definir a ordenação.

Trabalhando com Generics


Large Binlogs Generated When Reverting Features

Question: We're using features to manage content types and field groups, and every code update, when we perform a features-revert to push out the latest CTs and field group changes, we get a huge amount of data written to our binlogs -- a gig about every 10 mins:
-rw-rw----. 1 mysql mysql 1073759569 Aug  1 02:31 mysql-bin.000138
-rw-rw----. 1 mysql mysql 1073766800 Aug  1 02:42 mysql-bin.000139
-rw-rw----. 1 mysql mysql 1074139941 Aug  1 02:50 mysql-bin.000140
-rw-rw----. 1 mysql mysql 1073954804 Aug  1 02:59 mysql-bin.000141

which quickly locks up our MySQL servers.
What might be causing the large amount of data to be written? What can we be doing on the MySQL side and the Drupal side to keep this in check?
Answer: DISCLAIMER : Not a Drupal Expert, Just a MySQL DBA
There are really two classes of answers for this question

STANDALONE DB SERVER
MASTER/SLAVE REPLICATION

STANDALONE DB SERVER
If you know you are going to perform a feature-revert, the simplest thing to do is this
StandAlone Method #1 : Disable Binary Logs

STEP 01) Run SET GLOBAL SQL_LOG_BIN = 0;
STEP 02) Run your feature-revert
STEP 03) Run SET GLOBAL SQL_LOG_BIN = 1;

This will disable binary logging during the feature revert and reenable afterwards
StandAlone Method #2 : Erase All Binary Logs Except the Last One
You could crontab a job that runs this:
PURGE BINARY LOGS BEFORE NOW();

StandAlone Method #3 : Erase All Binary Logs
You could crontab a job that runs this:
RESET MASTER;

MASTER/SLAVE REPLICATION
In standard MySQL Master/Slave Replication, a Master Has Binary Logging Active and the Slave Does Not. You cannot just disable binary logging like you would for a StandAlone DB Server because you need to replicate the DB Changes of the feature-revert.
Here is what to do stem the rise of binary logs and relay logs
Replication Master (Manage Binary Logs)
At the completion of a feature-revert, which binary logs are safe to remove so that MySQL Replication can still work and remain intact?
Here is what you do:

STEP 01) Run SHOW SLAVE STATUS\G On the Slave.

For example:
mysql> show slave status\G
*************************** 1. row ***************************
             Slave_IO_State: Waiting for master to send event
                Master_Host: 10.64.97.249
                Master_User: replicant
                Master_Port: 3306
              Connect_Retry: 60
            Master_Log_File: mysql-bin.000658
        Read_Master_Log_Pos: 799061333
             Relay_Log_File: relay-bin.003861
              Relay_Log_Pos: 47059
      Relay_Master_Log_File: mysql-bin.000658
           Slave_IO_Running: Yes
          Slave_SQL_Running: Yes
            Replicate_Do_DB:
        Replicate_Ignore_DB:
         Replicate_Do_Table:
     Replicate_Ignore_Table:
    Replicate_Wild_Do_Table:
Replicate_Wild_Ignore_Table:
                 Last_Errno: 0
                 Last_Error:
               Skip_Counter: 0
        Exec_Master_Log_Pos: 799061333
            Relay_Log_Space: 47059
            Until_Condition: None
             Until_Log_File:
              Until_Log_Pos: 0
         Master_SSL_Allowed: No
         Master_SSL_CA_File:
         Master_SSL_CA_Path:
            Master_SSL_Cert:
          Master_SSL_Cipher:
             Master_SSL_Key:
      Seconds_Behind_Master: 0
1 row in set (0.00 sec)

STEP 02) Get binary log from Relay_Master_Log_File

Field #10 of SHOW SLAVE STATUS\G
That would be mysql-bin.000658

STEP 03) On the Master, Run PURGE BINARY LOGS TO 'mysql-bin.000658';

Replication Slave (Manage Relay Logs)
To force a Slave to Throttle the amount of Relay Logs to Just 2GB, add this to the Slave's my.cnf
[mysqld]
relay_log_space_limit=2G

and restart mysql on the Slave. When a Relay Log is fully processed it is automatically deleted and makes room for the next Relay Log.
EPILOGUE
You should make sure you have this set in /etc/my.cnf on the StandAlone DB Server or Master
[mysqld]
expire_logs_days = 3;

and restart mysql. This will make sure all binary logs older that 3 days are automatically deleted.
If you are curious and want to know what runs in a feature-revert You could

Look through source code of the feature-revert module
take the binary logs and dump the contents in plain text SQL

Run the following:
mysqlbinlog mysql-bin.000138 mysql-bin.000139 mysql-bin.000140 mysql-bin.000141 > Revert.sql
less Revert.sql

UPDATE 2012-08-09 12:40 EDT
If you are concerned with point-in-time recovery, you must decide how many days worth of binary logs you are willing to keep.
Here is a scenario: Say you want to be able to revert back up to 7 days ago. You would have to setup the following:
STEP 01) Have the Slave maintain its set of Binary Logs with an expiration of 7 days
Add this to /etc/my.cnf on the Slave
[mysqld]
log-bin=mysql-bin
expire_logs_days=7

STEP 02) service mysql restart
STEP 03) Perform a midnight Backups on the Slave as follows

STOP SLAVE;
FLUSH LOGS;
mysqldump on the Slave
START SLAVE;

STEP 04) Delete backups older than 14 days
Once you have Steps 3 and 4 automated, you must let mysql rotate the binary logs on the Slave. You should not manually delete the binary logs on the Slave. Keep in mind that point-in-time recovery is not automatic. It is rigorous manual process.
Would you like a description of a point-in-time recovery ??? Here we go...
Let's say you have the following

It's August 9, 2012 12:11 PM
run mysqldumps on the Slave every night at midnight
each backup is named by date Backup_99999999.sql in /backups
and you have the following list of binary logs on the Slave

_
-rw-rw---- 1 mysql mysql 1073742269 Aug  2 11:22 mysql-bin.001789
-rw-rw---- 1 mysql mysql 1073762807 Aug  2 16:22 mysql-bin.001790
-rw-rw---- 1 mysql mysql 1073742048 Aug  2 21:28 mysql-bin.001791
-rw-rw---- 1 mysql mysql 1073741969 Aug  3 06:34 mysql-bin.001792
-rw-rw---- 1 mysql mysql 1073741954 Aug  3 11:20 mysql-bin.001793
-rw-rw---- 1 mysql mysql 1073742182 Aug  3 16:19 mysql-bin.001794
-rw-rw---- 1 mysql mysql 1073742228 Aug  3 21:37 mysql-bin.001795
-rw-rw---- 1 mysql mysql 1073753003 Aug  4 06:32 mysql-bin.001796
-rw-rw---- 1 mysql mysql 1073742100 Aug  4 13:18 mysql-bin.001797
-rw-rw---- 1 mysql mysql 1073741891 Aug  4 18:56 mysql-bin.001798
-rw-rw---- 1 mysql mysql 1073742424 Aug  5 06:12 mysql-bin.001799
-rw-rw---- 1 mysql mysql 1073742017 Aug  5 18:35 mysql-bin.001800
-rw-rw---- 1 mysql mysql 1073741952 Aug  6 05:27 mysql-bin.001801
-rw-rw---- 1 mysql mysql 1073757571 Aug  6 13:00 mysql-bin.001802
-rw-rw---- 1 mysql mysql 1073742172 Aug  6 17:35 mysql-bin.001803
-rw-rw---- 1 mysql mysql 1073742067 Aug  7 00:35 mysql-bin.001804
-rw-rw---- 1 mysql mysql 1073777487 Aug  7 10:45 mysql-bin.001805
-rw-rw---- 1 mysql mysql 1073791986 Aug  7 15:51 mysql-bin.001806
-rw-rw---- 1 mysql mysql 1073742035 Aug  7 20:37 mysql-bin.001807
-rw-rw---- 1 mysql mysql 1073741978 Aug  8 05:28 mysql-bin.001808
-rw-rw---- 1 mysql mysql 1073742217 Aug  8 10:30 mysql-bin.001809
-rw-rw---- 1 mysql mysql 1073742422 Aug  8 14:41 mysql-bin.001810
-rw-rw---- 1 mysql mysql 1073743447 Aug  8 18:47 mysql-bin.001811
-rw-rw---- 1 mysql mysql 1073742241 Aug  9 00:36 mysql-bin.001812
-rw-rw---- 1 mysql mysql 1073741985 Aug  9 08:45 mysql-bin.001813
-rw-rw---- 1 mysql mysql  743967477 Aug  9 12:10 mysql-bin.001814

You want to reload the Master going back to August 5, 2012 02:30 PM
Here are you steps
STEP 01) Take all binary logs that encompass August 5, 2012 from 12:00AM to 2:30PM. This would be binlogs mysql-bin.001799 and mysql-bin.001800. These are used because

PRINCIPLE : the first write of a binlog is also the last write of the previous binlog

the last write to mysql-bin.001798 is Aug 4 18:56 (6:56PM) 2012-08-04 18:56:00
the first write to mysql-bin.001799 is Aug 4 18:56 (6:56PM) 2012-08-04 18:56:00
the last write to mysql-bin.001799 is Aug 5 06:12 (6:12AM) 2012-08-05 06:12:00
the first write to mysql-bin.001800 is Aug 5 06:12 (6:12AM) 2012-08-05 06:12:00
the last write to mysql-bin.001800 is Aug 5 18:35 (6:35PM) 2012-08-05 18:35:00

The range 2012-08-04 18:56:00 to 2012-08-05 18:35:00 is the narrowest range that surround 2012-08-05 00:00:00 to 2012-08-05 14:30:00. This is why binlogs mysql-bin.001799 and mysql-bin.001800 are the correct choices
STEP 02) Generate all the SQL that ran August 5, 2012 from 12:00AM to 2:30PM
mysqlbinlog --start-datetime="2012-08-05 00:00:00" --stop-datetime="2012-08-05 14:30:00" mysql-bin.001799 mysql-bin.001800 > ForwardChanges.sql

STEP 03) Make a copy of the August 5, 2012 midnight backup to PITR.sql
cp /backups/Backup_20120805.sql PITR.sql

STEP 04) Append ForwardChanges.sql to PITR.sql
cat ForwardChanges.sql >> PITR.sql

STEP 05) Load PITR.sql into the Master
mysql -h IPAddressOfMaster -u ... -p... < PITR.sql

When the script is done, the database will be in the state it was as of August 5, 2012 2:30PM
Pretty easy, huh ???
Comment: Thanks @RolandoMySQLDBA. What about point-in-time recovery, if bin logs are cleared from the slaves? Would that be based on binlogs from the master?


Multiple voices in Lilypond: stem directions, beams, and merged noteheads

Question: With quite a bit of trial and error I figured out a way to write the following bar in Lilypond:

There are four voices, the top voice has upward stems, the two lower voices have downward stems, and the stems of the middle voice (in eighth notes) should be chosen as if there were no other voices. Furthermore, the notes of the middle voice should be beamed per beat.
This is the code:
\new Staff  \relative c' {
  \key b \minor
  \time 3/4
  \clef "treble_8"
  \mergeDifferentlyHeadedOn

<< { \voiceOne d2 d4 } \\
   { \voiceTwo s4 fis,2 } \\
   { \voiceThree \stemNeutral d'8[ b] fis[ b] d[ b] } \\
   { \voiceFour b,2. } >> |
}

I think the code is quite clumsy and I was wondering if there is a more elegant and efficient way to do this. There are still about 50 similar bars to come ...
I would be very curious to know how someone with better Lilypond skills than me would solve such a problem.
Comment: Just FYI, the normal standard would be that you have two different note heads--a solid one for the eighth notes and an unfilled one for the half note. The eighth notes would also be slightly separated from the half note. I understand if you're avoiding that intentionally for a cleaner look. But I just wanted to mention the possibility.
Comment: @trlkly: Yes, I know, but I think it looks indeed much cleaner that way.
Answer: If you have 50 similar bars, I would definitely separate each voice into its own variable. The usual way to go about this is making a variable that contains the things that you want to have in each voice, like this:
global = {
    \key b \minor
    \time 3/4
    \mergeDifferentlyHeadedOn
    \mergeDifferentlyDottedOn
    % whatever else you prefer
}

Then you make a variable for each voice, and you include the global variable into the voice like this
one = {
    \global    % this inserts the whole content of the "global" variable
    \voiceOne
    d2 d4 |
    e2 e4 |   % I made up some more notes
    cis2 cis4 |
    % etc.
}

and you make variables for all the other voices in a similar way. Then you combine them together:
\score
{
    \new Staff <<
        \clef "G_8"  % shorter than "treble_8", that's all
        \new Voice \one
        \new Voice \two
        \new Voice \three
        \new Voice \four
    >>
    \layout { }
    \midi { } % only if you want MIDI output
}

In this way, you have four voices, each of them is filled in from one variable (here, they are called \one through \four but you can use more imaginative names). It's a pretty clean solution (you can even split it into multiple files easily) because you can "factor out" the common stuff into the \global variable (again, you can call this variable however you want) and often you can easily make use of things like \repeat unfold etc.
Comment: @MattL. - I don't think there's a way around that. On the other hand, as far as I know, LilyPond is not designed to work this way — at least not at scale. Using `<<{}\\{}>>` should be temporary, not fundamental to the coding of the piece. If I understand correctly, every time `<<{}\\{}>>` is used, LilyPond silently adds at least two additional `Voice` contexts to your `\score`. One `<<{}\\{}>>` for every measure could end up basically creating hundreds of `Voice` contexts and make the application choke. Ask me how I know.
Comment: Re "the code for a single bar is then spread out over the source file": have a look at \parallelMusic. Re "could end up basically creating hundreds of `Voice` contexts and make the application choke": did you witness it choking? I don't see why those extra `Voice` contexts would be particularly more expensive compared to the objects LilyPond already has to create to typeset the music.
Comment: Thanks for your answer, that's indeed neater. The disadvantage for me is just that the code for a single bar is then spread out over the source file (one part per voice). But I guess there is no way around that, or is there?
Comment: @MattL. — I don't think so either. And I would actually argue that it's (mostly) better to have it this way. Removing whole bars is more difficult, that's true, but otherwise, you keep together things that musically belong together. Then you can make good use of `\repeat unfold`, automatic filling of notes/durations etc. (For extreme case, imagine an orchestral score with 20 instruments interleaved like in your snippet. Things like "I need to change the violins to play this melody in these 4 bars" become a nightmare.)
Comment: @ABOUSAMRAJean: Thanks for pointing out \parallelMusic, didn't know about this.
Comment: @ABOUSAMRAJean - To my understanding, yes, it choked. I found this -> https://lists.gnu.org/archive/html/bug-lilypond/2019-03/msg00003.html <- which discussed the same behavior I was witnessing.
Comment: That's interesting. Now, they say on that thread that this is a common problem, and I have never heard about it in several years now watching LilyPond lists, so it might have been fixed in the meantime (didn't search commit history, though).


reading specific contact information

Question: I'm currently doing development on an Android app that requires me to read all the contacts on a device and select only specific contacts based on criteria (only contacts that have at least one valid mobile number and all email addresses linked to that contact).
I've tried the recommended approach at https://stackoverflow.com/a/19563999/3262731, but on a test device with approximately 800 contacts, retrieving all the records and then filtering takes about 17-20 seconds.
Ideally I'd love to build the criteria into a query that joins the contacts, phone, and email store tables in the contacts db as opposed to filtering in my code.
Does anyone have any suggestions please?
Answer: According to http://developer.android.com/reference/android/provider/ContactsContract.Contacts.html

Query

If you need to read an individual contact, consider using CONTENT_LOOKUP_URI instead of CONTENT_URI.
If you need to look up a contact by the phone number, use PhoneLookup.CONTENT_FILTER_URI, which is optimized for this purpose.
If you need to look up a contact by partial name, e.g. to produce filter-as-you-type suggestions, use the CONTENT_FILTER_URI URI.
If you need to look up a contact by some data element like email address, nickname, etc, use a query against the ContactsContract.Data
table. The result will contain contact ID, name etc.
Comment: Thanks Drakosha but what i'd like to do is not look up a contact - i'd like to retrieve all contacts (first, last names and mobile numbers) based on whether they have at least 1 mobile number and retrieve all their email addresses as well.
Answer: The android documentation seems to contain information in what you're looking for found here.
private static final String[] PROJECTION =
    {
        /*
         * The detail data row ID. To make a ListView work,
         * this column is required.
         */
        Data._ID,
        // The primary display name
        Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ?
                Data.DISPLAY_NAME_PRIMARY :
                Data.DISPLAY_NAME,
        // The contact's _ID, to construct a content URI
        Data.CONTACT_ID
        // The contact's LOOKUP_KEY, to construct a content URI
        Data.LOOKUP_KEY (a permanent link to the contact
    };

return new CursorLoader(getActivity(), contentUri, PROJECTION, SELECTION, SELECTION_ARGS, SORT_ORDER);

More details on how to define your criteria in the documentation. I would think this would be faster than using a ContentResolver as well.
Comment: Thanks Nelson, that was my starting point but its not exactly what i require and the documentation itself doesn't provide much in the way of clues for getting data from the different contact tables (email, phone) simultaneously.

reading specific contact information


What is the definition of a 2-graph?

Question: A normal category is built on the simple notion of a graph defined with two functions and two types
$s, t: Arrows \to Vertices $
Add to that a notion of a path and equations between paths and one gets the notion of a category. Indeed it is well known that every Graph gives rise the Free Category of that graph.
But what about 2-categories? Those have morphisms between morphisms, so it seemed to me that a simple graph as above won't do. (Or I could not understand the magic reasoning that would get me there)
So I asked what structure would play the same role on Twitter and Eugenia Cheng answered that

Yes, you need 2-cells ---s,t---> arrows ---s,t---> vertices. ie a 2-graph.

So that's a good concise answer for Twitter, and it gave me confidence that I had asked a good question. But I could not find much about 2-graphs online. It is clearly the right answer as the ncatlab page on strict 2-categories mentions them, but then links to a page with a definition of globular sets which is completely opaque to me.
Can anyone perhaps develop the point made by Eugenia, and perhaps point to a resource that describes 2-graphs in more detail? I would have expected some document to show how one builds paths on 2-graphs to get a 2-category, the way it is done with simple categories.
Answer: Since they don't have composition, $2$-graphs are much easier to describe than $2$-categories. You have a set of $0$-morphisms (objects), for any two objects, you have a set of 1-morphisms between them, and for any two parallel $1$-morphisms, you have a set of 2-morphisms between them.
That's it. As you can imagine, this is pretty easy to generalize to $n$-graphs or $\infty$-graphs, which are more commonly called globular sets. However, in that context, you often consider all of the $k$-morphisms as being in one set. That means that you need some extra data about the source and target of each. This turns out to be easier to work with, since it means that a globular set is just a functor from a particular category (whose objects are natural numbers) to the category of sets.
Comment: This was both an interesting question as well as an interesting answer.
Answer: While it is possible to freely generate a 2-category from a 2-graph in the sense described by Eugenia and SCappella, this is not the most powerful notion of "free on a..." that goes with a 2-category. For instance, suppose one wants to construct the 2-category "freely generated by an adjunction." Well, first one should give two objects $x,y$, and two 1-morphisms $f:x\to y$ and $g:y\to x$. Next, one needs 2-morphisms $\eta:1_x\to g\circ f$ and $\varepsilon:f\circ g\to 1_y$. But here we have identities and compositions, so we have no apparent way to freely generate this 2-category from a 2-graph.
However, it is freely generated by a computad. A computad is the generalization of a 2-graph in which the source and target of a 2-edge may lie in the 1-category freely generated by a given 1-graph. This allows the introduction of generating 2-cells whose domain and codomain are not among the generating 1-cells, as is actually the case with all four 1-cells associated to $\eta$ and $\varepsilon$ above.
Now we can finish our construction of the free adjunction $\mathcal A$ by freely generating a 2-category from our computad, then taking a quotient by imposing the triangle identities. Then for any 2-category $\mathcal K$ equipped with a choice of an adjunction, there is a unique 2-functor $\mathcal A\to \mathcal K$ mapping the generating adjunction in $\mathcal A$ to the chosen adjunction in $\mathcal K$.
Comment: Thanks for the answer. I will keep coming back to it over time, as I get more understanding of the concepts involved (especially a computad).

What is the definition of a 2-graph?


Scala Convert java.sql.ResultSet to Json Object

Question: I'm using Spark 2.3.1 and I've retrieved the resultSet from MySQL using JDBC Connection. resultSet is type of java.sql.ResultSet. so how to Convert ResultSet into JSON Object.
I don't have to use Spark SQL
Code for fetching resultSet is this
var connection:Connection = null
connection: java.sql.Connection = null

scala> Class.forName(driver)
res0: Class[_] = class com.mysql.jdbc.Driver

scala> connection = DriverManager.getConnection(url, username, password)
connection: java.sql.Connection = com.mysql.jdbc.JDBC4Connection@79777da7

scala> val statement = connection.createStatement()
statement: java.sql.Statement = com.mysql.jdbc.StatementImpl@68360fb9

scala> val resultSet = statement.executeQuery("SELECT * FROM table_name")
resultSet: java.sql.ResultSet = com.mysql.jdbc.JDBC42ResultSet@4ebed2b3

Answer: you can get resultset meta and take columns count, then iterate:
val meta = resultSet.getMetaData
val colsCount = meta.getColumnCount
var colsMap: Map[Int, String] = Map.empty[Int, String]
// save col index and colName to a map, to compute later json with "key" and value
for (i <- 1 to colsCount) {
   colsMap +=  i -> meta.getColumnName(i)
}

while (resultSet.next()) {
     for (i <- 1 to colsCount) {
        val value = resultSet.getObject(i)
        // here you take colName from specific index and save it in a list of JsValues
        // as { "colsMap(i)" : "value" }
        // using spray-json or any other json library
     }
}

Edit: Based on my research I want to extend this answer.
So to Convert ResultSet to Json String I'm using JacksonMapper library, to import this library command would be like this
./bin/spark-shell --packages "com.lambdaworks:jacks_2.11:2.3.3" --driver-class-path path-of/mysql-connector-java-5.1.49.jar
--jars path-of/mysql-connector-java-5.1.49.jar
-i path-to/ScalaApp.scala

Program snippet
import scala.collection.mutable.ArrayBuffer

import scala.collection.mutable.Map
import com.lambdaworks.jacks._

val meta = query_resultSet.getMetaData

    // Get total column count from metadata
    val colsCount = meta.getColumnCount
    var colsMap: Map[Int, String] = Map.empty[Int, String]

    // Create ArrayBuffer[ArrayBuffer[Map(String, String)]]
    var final_array = ArrayBuffer[ArrayBuffer[scala.collection.mutable.Map[String, String]]]()

    // Fill colsMap from columnName
    for (i <- 1 to colsCount) {
        colsMap +=  i -> meta.getColumnName(i)
    }

    while (query_resultSet.next()) {
        var result_array = ArrayBuffer[scala.collection.mutable.Map[String, String]]()
        for (i <- 1 to colsCount)
        {
            var temp_map = scala.collection.mutable.Map[String, String]()
            val cols = colsMap(i)
            val value = query_resultSet.getObject(i)
            temp_map(s"$cols") = s"$value"
            result_array += temp_map
        }
        final_array += result_array
    }

    // for Array: use JacksMapper to convert ArrayBuffer[Map(String, String)] to [{"column1":"value1"},{"column2":"value2"}]

     val  json_string = JacksMapper.writeValueAsString(final_array)

Here we are using Jackson Mapper Library to Convert Map values into Json String.
Answer: You can do something like this:
import value.{JsObj,JsArray}
val emp = JsObjSpec("name" -> getNameFromRS()),
                           "last_name" -> str(getNameFromRS()),
                           "profession" -> str(getProfFromRS()),
                           "country" -> enum("US"),
                           "languages" -> arrayOfStr((getLangFromRS()),
                           "age" -> getAgeFromRS(),,
                           * -> any
                           )

Comment: Actually at run time I don't have knowledge about table schema, because query will fire on tables according to loop variable, so can you please elaborate your answer, because I'm new to scala.
Answer: If using a third party library is an option here, you could use jOOQ's JSON export functionality for this:
DSLContext ctx = ...
String json = ctx.fetch(resultSet).formatJSON();

There are various JSON formatting options for different record and result layouts. The example above reads directly from your JDBC ResultSet, but you could, of course, also create and execute your query with jOOQ directly, or use the native SQL/JSON support. A lot of times, it's not necessary to write any middleware logic when you want to produce JSON from database results. You could generate the JSON directly from within SQL.
Disclaimer: I work for the company behind jOOQ.


SQL Server: cursor only returns records first time when running in Management Studio

Question: I'm hoping someone can help with this! I'm trying to write a stored procedure that uses a cursor. When I test this in Management Studio, the sproc only returns records the first time it's run. If I copy/past to another query window, it again returns records only the first time. When run from C#, the sproc works as expected.
The query below demonstrates the problem. Thanks in advance!
-------------------------------------------------------------------
-- Query to reproduce problem with using cursor - management studio
-------------------------------------------------------------------
--
Declare     crsrTest Cursor For
Select      TABLE_NAME
From        INFORMATION_SCHEMA.TABLES;

Declare     @TableName  varchar(128);
Open        crsrTest;

--
-- This will only return records the *first* time when running in MS.
-- Every time after that, I get the 'No records' message.
--
if @@FETCH_STATUS <> 0
    Print 'No records';
while   @@FETCH_STATUS = 0 begin
    Fetch   Next
    From    crsrTest
    Into    @TableName;
    Print   @TableName;
end;

Close       crsrTest;
Deallocate  crsrTest;

Comment: `@@FETCH_STATUS` is updated only after `FETCH`, and not reset afterwards. Use a loop of the form `WHILE 1 = 1 BEGIN; FETCH ...; IF @@FETCH_STATUS <> 0 BREAK; ... END;` (Repeating the statement is also possible, but I don't like repeating myself.)
Comment: What you might consider is not using a cursor in the first place. Not sure what your real code is doing but row by agonizing row processing can usually be avoided.
Comment: Ugh - I knew someone would tell me not to use a cursor. I already knew this. I know they can *usually* be avoided. That wasn't my question!
Answer: You are missing a FETCH NEXT between the OPEN and IF @@FETCH_STATUS <> 0:
DECLARE crsrTest CURSOR FOR
     SELECT TABLE_NAME
     FROM INFORMATION_SCHEMA.TABLES;

DECLARE @TableName VARCHAR(128);

OPEN crsrTest;

FETCH NEXT FROM crsrTest INTO @TableName;
PRINT @TableName;

-- This will always return records
IF @@FETCH_STATUS <> 0
   PRINT 'No records';

WHILE @@FETCH_STATUS = 0
BEGIN
    FETCH NEXT FROM crsrTest INTO @TableName;
    PRINT @TableName;
END;

CLOSE crsrTest;
DEALLOCATE crsrTest;

Stay away from cursors if you can (you seem to be new at them, that's why I'm telling). If you're an ORACLE guy, this is not as fast as iterations in PL/SQL.
Comment: Seriously, it's not hard to figure it out. I added the missing PRINT statement.
Comment: It could be easily fixed by switching FETCH and PRINT places inside WHILE. And would look much cleaner.
Comment: I don't use cursors, except for rare one-time transformation where I want to be able to isolate each step and be able to test them individually. I am merely fixing his CURSOR, which is the scope of the question and, as they should, people advise to avoid cursors at all cost.
Comment: Silly me thanks. Yes I know not to use cursors if you can avoid them.
Comment: I really appreciate the feedback! For the record it's almost always better to NOT use a cursor but...in *this* case I'm joining a table with a few records to a function that accepts a parameter based on one of the columns from the first table. You can't actually use a join in this case - you must use a cross apply. For my particular application, the cross apply takes 15 seconds. Using a cursor to iterate the handful of records from the first table and calling the function in the loop runs in 1 second. Same results. "It doesn't matter what the textbook says, it matters what the computer does."
Comment: Cursors have their use. But always avoid them if you can.


Multiple voices (divisi) in one part

Question: In LilyPond, how do you produce results like this? I want to go from a regular section to divisi, but I am unable to figure it out.

I attempted to use \parallelMusic and \new StaffGroup, but those basically created a new time signature and I had to set the key again. Additionally, the aesthetics were strange.
How can I do something that will produce the same results as something like this?
Answer: Googling "lilypond multiple voices" could've helped ;) Depending on what you want to do exactly there's multiple options: http://lilypond.org/doc/v2.18/Documentation/notation/multiple-voices
For longer passages it would be: (example from the guide)
\new Staff <<
  \new Voice = "first"
    { \voiceOne r8 r16 g e8. f16 g8[ c,] f e16 d }
  \new Voice= "second"
    { \voiceTwo d16 c d8~ d16 b c8~ c16 b c8~ c16 b8. }
>>

I.e. you simply need to explicitly declare the separate voices
Answer: One possibility is to typeset that music using two different parts. Then, you specify \RemoveEmptyStaves to hide the lower voice for the first few measures. If it's the opening measures you're hiding, you also need to override some \Score presets. Input into their correct \contexts, the necessary code will be:
\version "2.18.2"

sop = \relative c'' {
  c8 e g e c e g e |
  c e g e c e g e |
  c e g e c e g e |
  c e g e c e g e |
  c e g e c e g e |
  c e g e c e g e |
}

alt = \relative c'' {
  R1 |
  R |
  R |
  R |
  R |
  c2 e4 g |
}

\layout {
  \context {
    \Staff \RemoveEmptyStaves
  }
  \context {
    \Score
    \override VerticalAxisGroup.remove-first = ##t
  }
}

\score{
  \context StaffGroup <<
    \sop
    \alt
  >>
}

See more here at the LilyPond Snippet Repository.
Comment: This worked! Thanks so much for providing an example, it made it a lot more clear.

Multiple voices (divisi) in one part


Criar Date passando números tem resultado diferente de passar uma string com os mesmos valores

Question: Estou estudando a parte de datas do JavaScript e vi algo que não sei explicar.
Segue o código:

var envio = new Date(2018, 02, 20);
var envio2 = new Date("2018-02-20");

console.log("Virgula: " + envio);
console.log("String: " + envio2);

O resultado que isso me traz:
Virgula: Tue Mar 20 2018 00:00:00 GMT-0300 (Horário Padrão de Brasília) scripts.js:489:13
String: Mon Feb 19 2018 21:00:00 GMT-0300 (Horário Padrão de Brasília)

Entendi que no caso do mês, a versão com vírgula, conta a partir do zero, mas não entendi o motivo de na versão com string, estar com o dia 19.
Alguém sabe o que pode estar acontecendo?
Answer: Quando você chama o construtor passando números, o mês é indexado em zero (janeiro é zero, fevereiro é 1, etc). Então new Date(2018, 02, 20) corresponde a 20 de março. Se quer 20 de fevereiro, faça new Date(2018, 1, 20).
Outro detalhe é que ele seta o horário para meia-noite no fuso horário do ambiente no qual está rodando (no caso do browser, geralmente ele usa o do sistema operacional). Por isso no seu teste o resultado foi 20 de março à meia-noite no Horário de Brasília (este trecho da documentação diz que os campos não informados - no caso, a hora, minuto e segundo - são setados para zero, por isso o horário é meia-noite).
Já quando você passa uma string no formato ISO 8601 contendo somente a data (sem o horário), o mês é indexado em 1 (janeiro é 1, fevereiro é 2, etc) e o horário é setado para meia-noite em UTC (que por sua vez, corresponde à 9 da noite do dia anterior no Horário de Brasília, já que o Horário de Brasília está 3 horas atrás do UTC - ou 2 horas, quando é horário de verão). Mas quando você imprime a data, ela é mostrada no fuso horário do browser, por isso ela mostra dia 19 de fevereiro às 21h (pois dia 19 às 21h no Horário de Brasília equivale a dia 20 à meia-noite em UTC).
Para ser mais preciso, a documentação cita que ao passar uma string para o construtor de Date, ele usa a mesma lógica do método parse. E este, por sua vez, usa estas regras (e neste link está descrito o que eu já disse acima: "date-only forms are interpreted as a UTC time and date-time forms are interpreted as local time").

Ou seja, se você colocar o horário na string, aí ele considera o fuso horário do browser:

// sem horário, considera meia-noite em UTC
console.log('UTC: ' + new Date("2018-02-20"));

// com horário, considera o fuso horário do browser
console.log('Fuso do browser: ' + new Date("2018-02-20T00:00"));

Isso tudo acontece porque o Date do JavaScript na verdade representa um timestamp (um ponto na linha do tempo), não uma data específica (um único valor de dia, mês, ano, hora, minuto e segundo).
Para mais detalhes, leia aqui, aqui, aqui, aqui e aqui.


SonarQube Eclipse plugin throws error on local analysis

Question: We are running SonarQube 3.7. I'm using the SonarQube plugin for Eclipse, version 184.108.40.20630627-1142, on Eclipse 3.7.2. I have associated my projects with the SonarQube projects and am able to view issues from the server side great.
However, if I switch to Local analysis, I get the following error, after CheckStyle, PMD, etc have run:
15:16:23.217 INFO  - Execute decorators...
Exception in thread "main" org.sonar.runner.impl.RunnerException: Unable to execute Sonar
    at org.sonar.runner.impl.BatchLauncher$1.delegateExecution(BatchLauncher.java:79)
    at org.sonar.runner.impl.BatchLauncher$1.run(BatchLauncher.java:63)
    at java.security.AccessController.doPrivileged(Native Method)
    at org.sonar.runner.impl.BatchLauncher.doExecute(BatchLauncher.java:57)
    at org.sonar.runner.impl.BatchLauncher.execute(BatchLauncher.java:50)
    at org.sonar.runner.impl.BatchLauncherMain.execute(BatchLauncherMain.java:41)
    at org.sonar.runner.impl.BatchLauncherMain.main(BatchLauncherMain.java:59)
Caused by: org.sonar.api.utils.SonarException: Fail to decorate 'CLASSPATH.REDACTED.ClockEventHelperIT'
    at org.sonar.batch.phases.DecoratorsExecutor.executeDecorator(DecoratorsExecutor.java:85)
    at org.sonar.batch.phases.DecoratorsExecutor.decorateResource(DecoratorsExecutor.java:71)
    at org.sonar.batch.phases.DecoratorsExecutor.decorateResource(DecoratorsExecutor.java:64)
    at org.sonar.batch.phases.DecoratorsExecutor.decorateResource(DecoratorsExecutor.java:64)
    at org.sonar.batch.phases.DecoratorsExecutor.execute(DecoratorsExecutor.java:56)
    at org.sonar.batch.phases.PhaseExecutor.execute(PhaseExecutor.java:118)
    at org.sonar.batch.scan.ModuleScanContainer.doAfterStart(ModuleScanContainer.java:142)
    at org.sonar.api.platform.ComponentContainer.startComponents(ComponentContainer.java:88)
    at org.sonar.api.platform.ComponentContainer.execute(ComponentContainer.java:73)
    at org.sonar.batch.scan.ProjectScanContainer.scan(ProjectScanContainer.java:186)
    at org.sonar.batch.scan.ProjectScanContainer.scanRecursively(ProjectScanContainer.java:181)
    at org.sonar.batch.scan.ProjectScanContainer.doAfterStart(ProjectScanContainer.java:174)
    at org.sonar.api.platform.ComponentContainer.startComponents(ComponentContainer.java:88)
    at org.sonar.api.platform.ComponentContainer.execute(ComponentContainer.java:73)
    at org.sonar.batch.scan.ScanTask.scan(ScanTask.java:57)
    at org.sonar.batch.scan.ScanTask.execute(ScanTask.java:45)
    at org.sonar.batch.bootstrap.TaskContainer.doAfterStart(TaskContainer.java:82)
    at org.sonar.api.platform.ComponentContainer.startComponents(ComponentContainer.java:88)
    at org.sonar.api.platform.ComponentContainer.execute(ComponentContainer.java:73)
    at org.sonar.batch.bootstrap.BootstrapContainer.executeTask(BootstrapContainer.java:156)
    at org.sonar.batch.bootstrap.BootstrapContainer.doAfterStart(BootstrapContainer.java:144)
    at org.sonar.api.platform.ComponentContainer.startComponents(ComponentContainer.java:88)
    at org.sonar.api.platform.ComponentContainer.execute(ComponentContainer.java:73)
    at org.sonar.batch.bootstrapper.Batch.startBatch(Batch.java:92)
    at org.sonar.batch.bootstrapper.Batch.execute(Batch.java:74)
    at org.sonar.runner.batch.IsolatedLauncher.execute(IsolatedLauncher.java:45)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.sonar.runner.impl.BatchLauncher$1.delegateExecution(BatchLauncher.java:75)
    ... 6 more
Caused by: org.sonar.api.utils.HttpDownloader$HttpException: Fail to download [http://cm-sonar/api/sources?resource=REDACTED:shared-core:REDACTED.ClockEventHelperIT&format=txt]. Response code: 500
    at org.sonar.api.utils.HttpDownloader$BaseHttpDownloader$HttpInputSupplier.getInput(HttpDownloader.java:266)
    at org.sonar.api.utils.HttpDownloader$BaseHttpDownloader$HttpInputSupplier.getInput(HttpDownloader.java:230)
    at org.sonar.batch.bootstrap.ServerClient.request(ServerClient.java:88)
    at org.sonar.batch.bootstrap.ServerClient.request(ServerClient.java:82)
    at org.sonar.batch.scan.LastSnapshots.loadSourceFromWs(LastSnapshots.java:62)
    at org.sonar.batch.scan.LastSnapshots.getSource(LastSnapshots.java:52)
    at org.sonar.plugins.core.issue.IssueTracking.mapIssues(IssueTracking.java:82)
    at org.sonar.plugins.core.issue.IssueTracking.track(IssueTracking.java:59)
    at org.sonar.plugins.core.issue.IssueTrackingDecorator.doDecorate(IssueTrackingDecorator.java:107)
    at org.sonar.plugins.core.issue.IssueTrackingDecorator.decorate(IssueTrackingDecorator.java:91)
    at org.sonar.batch.phases.DecoratorsExecutor.executeDecorator(DecoratorsExecutor.java:80)
    ... 36 more

Everything runs fine on the server. Any ideas?
Comment: what happens when you try to reach 'http://cm-sonar/api/sources?resource=REDACTED:shared-core:REDACTED.ClockEventHelperIT&format=txt' from your browser ?
Comment: Having the same issue with the same version of server and Eclipse plugin.  If I click on the link I get an error page from Sonar that says there was a problem and the page can't be displayed.  This issue happens for some and not for others, very strange.
Comment: @FreddyMallet-SonarSource if I go to the link from the error in my browser, it says: "undefined method `source' for nil:NilClass"
Comment: The offending file seems to have key `CLASSPATH.REDACTED.ClockEventHelperIT`. But the WS ask for effective key `REDACTED:shared-core:REDACTED.ClockEventHelperIT`. `REDACTED:shared-core` must be the project key so its fine. But then the second part of the key is `REDACTED.ClockEventHelperIT`. Can you just give/confirm the following information: project key (`REDACTED:shared-core`), source folder path relative to root project (`src/main/java` ?), path of offending file (`src/main/java/CLASSPATH/REDACTED/ClockEventHelperIT.java` ?), and package of offending file (`CLASSPATH.REDACTED` ?)
Comment: @JulienHENRY Sorry, in my redaction of the actual classpaths, in one place I just wrote "REDACTED" and in the other place I wrote "CLASSPATH.REDACTED". These are actually the same.
Comment: @JulienHENRY, here are the answers to each of your questions.

I'm using fake classpaths here but the patterns match the real ones.

Project key: `com.company.project.toolsuite:shared-core`.

We have multiple source folders in the project -- this particular one is `runtime-tests`.

Java file path relative to project root: `runtime-tests/com/company/project/shared/ClockEventHelperIT.java`.

Package name is: `com.company.project.shared`.

Please let me know what else I can provide to help.
Answer: I also encountered a "Unable to execute Sonar... Fail to download... Response code: 500" with my installation (Sonar v3.7.2, Eclipse plugin v3.2 and Eclipse 4.3) when running a local analysis.
I noticed one of my classes in my stacktrace Caused by line (where yours shows "ClockEventHelperIT"). The class doesn't exist in my server side repository (it's new) and is also located in the default Java package. It was a throwaway class so I decided to remove it and re-run the analysis. That solved it for me.
Comment: In my case this class mentioned is already in the server's analysis. In fact I haven't even changed that file.
Answer: We are experiencing the same problem off and on with our projects.  The "fix" that we have found is to make sure that the case that the username is in the sonar plugin matchese the case that they would log into the sonar server with.  For now, this has fixed this particular issue, though I'm not sure if it actually fixes a problem.
When debugging we found no errors in the sonar logs, this is a very strange issue.
For your information we are running local analysis in Eclipse on Windows 7, and our Sonar Server is running on Red Hat Enterprise 6.2
Comment: We aren't normally using any credentials to log in to the SonarQube server. In our organization, only project leads and the Configuration Management team have accounts on SonarQube. So I'm not sure if this would even apply to me (what login would I put in the plugin configuration, if I don't use one normally to look at SonarQube?)
Comment: At the sonar level project permissions configuration you can configure the 'anonymous' group to be able to run local scans or dry runs.  That should be what you need.
Comment: However, if it works sometimes and not others regardless of configuring the authentication, it sounds like there's probably a bug here.
Comment: It is due to authentication every time for our team.
Answer: We had the same issue and for us it was because the class identified in the stack trace was in a non-standard folder (Maven standard). (i.e. outside the src/main/java, src/test/java, src/main/resources, src/test/resources).
I refactored these classes into the standard Maven folders and this problem was fixed.


scroll infinito com msg ao chegar no final dos resultados

Question: estou iniciando agora em javascript e ajax entao tem muita coisa que ainda tenho duvida
eu criei um sistema de scroll infinito mas oque nao estou sabendo criar é:
quando chegar ao final da coluna ou ( nao existir mais nada para ser mostrado )
gosta que o ajax incluise um arquivo php onde por exemplo, estara uma div footer com os dados do site
eu ate consigo mostrar uma msg no final mas a msg fica repitindo toda vez que eu tento desser mais a janela
$(document).ready(function() {

var win = $(window);
// Each time the user scrolls
win.scroll(function() {
    // End of the document reached?
    if ($(document).height() - win.height() == win.scrollTop()) {
        $('#loading').show();

        var id = $(".tm:last").attr("id");
        var cat = $(".tm").attr("cat");

        $.ajax({
            url: 'load2.php?id='+id+'&cat='+cat,
            dataType: 'html',
            success: function(html) {

                if(html){
                $('#posts').append(html);
                $('#loading').hide();
                }else{

                 ---- aqui que esta a treta !!! ----
                $('#posts').append("
End of countries !!!!!!!
");
                }

            }
        });

    }
});

});
Answer: Pra não repetir a mensagem basta você checar se já inseriu a mensagem antes. De preferência antes de chamar o ajax, pra economizar recursos.
$(document).ready(function() {
var win = $(window);

// Each time the user scrolls
win.scroll(function() {
    // End of the document reached?
    if ($(document).height() - win.height() == win.scrollTop()) {
        $('#loading').show();

        var id = $(".tm:last").attr("id");
        var cat = $(".tm").attr("cat");

        // Se já temos uma div com a classe "fim", nem chama o ajax de novo
        if ( $('.fim').length > 0 ) {
           $('#loading').hide();
           return false;
        }

        $.ajax({
            url: 'load2.php?id='+id+'&cat='+cat,
            dataType: 'html',
            success: function(html) {

                if(html){
                $('#posts').append(html);
                $('#loading').hide();
                }else{

                 // coloque uma classe "fim" na mensagem
                $('#posts').append("

End of countries !!!!!!!

");
                }

            }
        });

    }
});

Comment: perfeito amigo , funcionou corretamente !!!!!!!!!!!!!!!!!!!!!!!!!!
Comment: agradeço por ter me ajuda com essa duvida amigo , muito obrigado mesmo
Comment: ricardo , eu deveria ter me empresado melhor na pergunta , a solução que vc me deu e exatamente oque eu presisava , mas ao inves de mostrar a msg , o apende deveria incluir um arquivo php com o html do footer , eu esqueci de colocar isso na duvida a cima :/
Comment: @JonnysJ. não tem como você inserir um arquivo php ali, porque quando o javascript roda o trabalho do servidor já está feito. O que você pode fazer é retornar o conteúdo que viria nesse php na função ali do `load.php` que retorna a resposta do Ajax. Aí ao invés de checar se `html` está vazio você faz um teste pra saber qual conteudo ele tem. E se não for posts você insere ali no `append()` deu pra entender?
Comment: bom foi exatamente oq fiz mas nao funcionou
Comment: var arq = 'End of countries !!!!!!!';
                $('#fot').append(arq);
    alert(arq);
Comment: eu achei que ele iria inserir o dodigo html na pagina , entao quando ele inserisse o codigo , ai puxaria o arquivo php com o codigo do footer
Comment: não vai funcionar. Quando o javascript roda a resposta do ajax já é tarde demais pra usar qualquer função do PHP. Suas opções são colocar o código HTML escrito dentro do javascript ou retornar esse código junto com a resposta do ajax.
Comment: entao minha unica solução seria criar o scroll infinito dentro de uma div e ao chegar no final da div , carregasse mais artigos , assim o footer sempre vai estar la certo? e nao vai precisar ser carregado script acima
Comment: http://pt.stackoverflow.com/questions/165161/scroll-ligado-a-uma-div-no-html-com-javascrip criei um novo topico sobre isso


entity eck create new property type or/and behaviour

Question: I guess everyone here has done what I want multiple times and I am probably just stupid but I can't seem to find it.
So in my drupal 7 installation I want to create an entity with a date property(so all bundles have a date that is set by a user). Perfect scenario is that this date is like the date field with calender to select a date.
I can't find how to do this but that's probably because I have no idea what to look for.
Can someone put me in the right direction for this?
Making it more clear:
I could just add a date field in all bundles but that seems not the best way to me and I would like to learn drupal in it's best practice.
thanks in advance
Answer: You can follow the documentation of eck modules. https://www.drupal.org/node/1370980
The last version introduces the concept of behaviour and you can create your own.

Install the module date_popup
Implement the hook hook_ctools_plugin_directory()
Create your plugin
In the default_widget callback return a renderable array where the #type is date_popup
Comment: looks like i found function `function HOOK_eck_property_types()`  + `function  HOOK_eck_property_types_alter(&$types)` +

`function HOOK_eck_property_type_schema_alter(&$type, &$schema)`
Comment: Cool, thanks! But how to create new type (not a property behaviour)?


Decode this message received by Space Defence Control

Question: The following is in my A level textbook categorised as an 'easy' question:

Decode this message received by Space Defence Control. MKW PWCCFQ USFGWJOWWM LU FSSARFGKLQC SOWFUW UWQH KWOS XW QWWH PRAW CFOFGMLG ABQFDRBMU XLMK KLCK USWWH OFUWA CBQU

I've looked at so many different variables, such as how often letters occur, and what these numbers correspond to in the alphabet, but I just cannot get anywhere.
I fail to see how this is 'easy' or even mathematical, as the person who encoded it could've chosen any method they wanted to, and so getting the right one is just guessing and trial and error.
What am I missing here?
Comment: This would be a better fit for puzzling.se
Comment: What textbook is this? (Just out of curiosity)
Comment: This isn't really a math question, but more of a linguistics one. If you make educated guesses (like a three letter word that begins a sentence is quite likely to be "the," and study what two letter words there are), you'll get somewhere.
Comment: @Stone Edexcel for year 1&AS
Comment: Depends on what kind of cipher was used.  Simple substitution?  What language?  French?
Comment: Most frequent letter in English is E (also frequently a double letter), most frequent three-letter word is THE, then HIGH is a good guess for `KLCK`. "Space control" is a good clue. And so it goes.
Answer: It is a substitution cipher where the ciphertext is given by the bijection
$$\begin{matrix} a&b&c&d&e&f&g&h&i&j&k&l&m \\ F&D&G&H&W&J&C&K&L&E&Z&O&P\\
n&o&p&q&r&s&t&u&v&w&x&y&z\\
Q&R&S&I&A&U&M&B&V&X&T&Y&N \end{matrix}$$
Given the encoded message:

MKW PWCCFQ USFGWJOWWM LU FSSARFGKLQC SOWFUW UWQH KWOS XW QWWH PRAW CFOFGMLG ABQFDRBMU XLMK KLCK USWWH OFUWA CBQU

then the decoded message is:

the meggan spacefleet is approaching please send help we need more galactic runabouts with high speed laser guns

P.S. I found an online Substitution Solver which is able to decipher this "english" message automatically!!!
Answer: user296602 has the right idea. I have not found a pattern in the cipher so you have to figure out one letter at a time. After making a few educated guesses it basically becomes a game of Wheel of Fortune. The message reads:
The Meggan spacefleet is approaching please send help we need more galactic runabouts with high speed laser guns


Masquerade with nftables

Question: I have PC-1 with 2 uplinks (modem1 and modem2) and LAN on eth0 interface:
# ip -c -brief addr
lo               UNKNOWN        127.0.0.1/8
eth0             UP             192.168.0.7/24
modem2           UNKNOWN        10.73.15.79/27
modem1           UNKNOWN        10.176.229.31/26

('unknown' state for modem1 and modem2 is seemed ok).
I've setup routing as follows:
# ip -c rule
0:      from all lookup local
32764:  from 10.73.15.79 lookup 2
32765:  from 10.176.229.31 lookup 1
32766:  from all lookup main
32767:  from all lookup default

# ip -c route ls table main
default
        nexthop via 10.176.229.32 dev modem1 weight 1
        nexthop via 10.73.15.80 dev modem2 weight 1
10.73.15.64/27 dev modem2 proto kernel scope link src 10.73.15.79
10.176.229.0/26 dev modem1 proto kernel scope link src 10.176.229.31
192.168.0.0/24 dev eth0 proto kernel scope link src 192.168.0.7

# ip -c route ls table 1
default via 10.176.229.32 dev modem1
10.73.15.64/27 dev modem2 scope link
10.176.229.0/26 dev modem1 scope link src 10.176.229.31
127.0.0.0/8 dev lo scope link
192.168.0.0/24 dev eth0 scope link

# ip -c route ls table 2
default via 10.73.15.80 dev modem2
10.73.15.64/27 dev modem2 scope link src 10.73.15.79
10.176.229.0/26 dev modem1 scope link
127.0.0.0/8 dev lo scope link
192.168.0.0/24 dev eth0 scope link

So, locally on PC-1, I have internet access.
I have also PC-2 within the LAN, and would like to setup masquerade on PC-1 to provide internet for PC-2.
I'm trying the following nftables config:
# nft list ruleset
table ip filter {
        chain input {
                type filter hook input priority 0; policy accept;
        }

        chain forward {
                type filter hook forward priority 0; policy accept;
        }

        chain output {
                type filter hook output priority 0; policy accept;
        }
}
table ip nat {
        chain input {
                type nat hook input priority 0; policy accept;
                ip protocol icmp accept
        }

        chain prerouting {
                type nat hook prerouting priority 0; policy accept;
        }

        chain postrouting {
                type nat hook postrouting priority 100; policy accept;
                ip saddr 192.168.0.0/24 oifname "modem*" masquerade
        }

        chain output {
                type nat hook output priority 0; policy accept;
        }
}

But it does not work. I have tried several different versions of the config, but unsuccessfully. How can I setup nftables for masquerade?
I also setup:
# sysctl -w net.ipv4.ip_forward="1"
net.ipv4.ip_forward = 1

Linux kernel 4.19.0
Edit:
I have configured masquerade with nftables on another PC successfully.
The difference noticed by me (I do not know whether it has sense):
On PC-1:
# sudo iptables -S
iptables: No chain/target/match by that name.

On another PC:
# sudo iptables -S
-P INPUT ACCEPT
-P FORWARD ACCEPT
-P OUTPUT ACCEPT

Comment: What does not work? The masquerading rules are fine, I'd replace `"modem*"` with two lines, one each for `modem1` and `modem2`, though (personal preference). Also +1 for nftables. This is for initial setup, for production use I'd change the default policies, of course.
Comment: @Lenniey ping from PC-2 does not pass. With iftop I see requests from PC-2 on eth0, but uplinks are empty.
Comment: Ah, you are missing your forward entries. Try something like `iifname "eth0" oifname "modem*" accept`, `iifname "modem*" oifname "eth0" ct state established accept` and `iifname "modem*" oifname "eth0" ct state related accept`
Comment: @Lenniey I've added the rules to chain forward of ip filter table. But the result is the same.
Comment: I have configured masquerade with nftables on another PC successfully. Seems the problem is not in nftables.
Answer: So, the problem - IPV4_DEVCONF_FORWARDING was unset on eth0 interface.
I have set it with help of libnl - method rtnl_link_inet_set_conf.
Edit:
This is the same option sysctl net.ipv4.conf.eth0.forwarding.
Thanks for @A.B.
Comment: @A.B. I enabled the global toggle manually but did not realize - I have soft, which can change "forwarding" on an interface.
Comment: afaik IPV4_DEVCONF_FORWARDING for eth0 means sysctl net.ipv4.conf.eth0.forwarding. Considering you wrote you enabled the global toggle, this should have been set also for eth0. It would thus have been hard to guess from the question that it wasn't there.

Masquerade with nftables


CloudFoundry App instances - EF Core database migration

Question: I've written a .NET Core Rest API which does migrate/ update the database (using Entity Framework Core) in Startup.cs. Currently, only one instance is running in the production environment. It seems to be recommended to run 2 instances in production.

What happens while executing the cf push command? Are both instances stopped automatically or do I need to execute cf stop?

In addition, how do I prevent both instances from updating the database?
I've read about the CF_INSTANCE_INDEX environment variable. Is it OK to only start the database migration when CF_INSTANCE_INDEX is 0? Or does CloudFoundry provide the next mechanism: start the first instance and when this one is up-and-running, the second instance will be started?
Answer:
What happens while executing the cf push command? Are both instances stopped automatically or do I need to execute cf stop?

Yes, your app will stop. The new code will stage (i.e. buildpacks run) and produce a droplet. Then the system will bring up all the requested instances using the new droplet.

In addition, how do I prevent both instances from updating the database? I've read about the CF_INSTANCE_INDEX environment variable. Is it OK to only start the database migration when CF_INSTANCE_INDEX is 0?

You can certainly do it that way. The instance number is guaranteed to be unique and the zeroth instance will always exist, so if you limit to the zeroth instance then it's guaranteed to only run once.
Another option is to run your migration as a task (i.e. cf run-task). This runs in its own container, so it would only run once regardless of the number of instances you have. This SO post has some tips about running a migration as a task.

Or does CloudFoundry provide the next mechanism: start the first instance and when this one is up-and-running, the second instance will be started?

It does, it's the --strategy=rolling flag for cf push.
See https://docs.cloudfoundry.org/devguide/deploy-apps/rolling-deploy.html
I'm not sure that this feature would work for ensuring your migration runs only once. According to the docs (See "How it works" section at the link above), your new and old containers could overlap for a short period of time. If that's the case, running the migration could potentially break the old instances. It'll be a short period of time, just until they get replaced with new instances, but maybe something to consider.
Comment: Steeltoe has [support for running tasks in .NET](https://docs.steeltoe.io/api/v3/management/tasks.html) and a [sample that uses it to manage db migrations](https://github.com/SteeltoeOSS/Samples/tree/main/Management/src/CloudFoundry).


Connection pool in LINQ to SQL

Question: In  a C# 2008 windows application that use call a web service, there is a large volume of statements that look like the following:
In a C# 2008 application, I am using linq to sql statements that look like the following:
//Code
  TDataContext TData = new TDataContext();
  var TNumber = (from dw in cms_TData.people
  where dw.Organization_Name.ToUpper().Trim() == strOrgnizationName.Trim().

Right before every call that is made to the database, a new data context object is created.
Would this cause some kind of connection pooling problem to the database? If so, can you tell me how to resolve the connection pooling problem?
Comment: what connection pooling problem are you mentioning?
Comment: Which we generally use to conenct to the DB.
Answer: Connection pooling is not a problem, it is a solution to a problem. It is connection pooling that enables you write
TDataContext TData = new TDataContext();

without a fear of exhausting the limited number of RDBMS connections, or slowing down your system to a crawl due to closing and re-opening connections too often. The only issue that you may run into with the code like that is caching: whatever is cached in TData is gone when it goes out of scope, so you may re-read the same info multiple times unnecessarily. However, the cache on RDBMS side would help you in most cases, so even the caching is not going to be an issue most of the time.
Answer: A DataContext is a lightweight object which closes the database connection as soon as it has completed as a task.
Consequently, creating a large number of these objects shouldn't cause a connection pooling problem unless, possibly, they are being created simultaneously on different threads.

Connection pool in LINQ to SQL


Is applying dimension reduction to mixed type data valid for outlier detection after that?

Question: I'm facing with anomaly detection (outlier detection) task with mixed (numerical and categorical) multi-feature data set. I understand that many of the possible multivariate outlier detection methods require numerical only features so I'm wondering to apply mixed-type dimension reduction technique (like FAMD) to obtain full-numerical features.
My question is if is it a valid approach? I somewhat fear that the very outlier nature of outliers may be neutralized by the dimension reduction's effect.
Answer: It sounds like an interesting idea to use FAMD to obtain purely numerical data. However, as you have already pointed out, dimension reduction would severely interfere with the anomaly detection task, since isolation information could easily be removed. Think of the popular simple outlier detection method using PCA: There, you use the distance of a point to the principal component subspace as the outlier score, but, when using this very PCA for dimensionality reduction, those outlier scores would all become zero.
The approach I would suggest is to use one-hot encoding for the categorical variables and then to apply Isolation Forest or variants thereof like e.g. Extended Isolation Forest. This method is very well established and known to work well.


How do I add the sort extension to an IMAP server?

Question: if we do own a Mail server supporting, how is it possible to add a sort extension to it?
Also how is it possible for a client using java mail to check if the server does indeed support the Sort extension?
For ref: question asked at https://stackoverflow.com/questions/1388208/how-do-i-add-the-sort-extension-to-the-imap-server
Answer: It depends on the mail server you're using.  It will either be a simple matter of changing a config option, installing a plugin, patching the software, or bugging a commercial vendor to make the necessary changes.
As far as determining whether the server supports it, yes the client should be able to determine whether the server supports the extension by examining the list of capabilities printed when the client connects.  For example, my IMAP server says:
<code>* OK [CAPABILITY IMAP4rev1 UIDPLUS CHILDREN NAMESPACE THREAD=ORDEREDSUBJECT THREAD=REFERENCES SORT QUOTA IDLE ACL ACL2=UNION]
</code>
Which indicates that my server already supports sorting.
Comment: So it's option the last, "bugging a commercial vendor to make the necessary changes".  Good luck with that.
Comment: this is what i got at mine (copied from debug output):

A0 CAPABILITY
* CAPABILITY IMAP4rev1 UNSELECT IDLE NAMESPACE QUOTA XLIST CHILDREN XYZZY

A2 CAPABILITY
* CAPABILITY IMAP4rev1 UNSELECT LITERAL+ IDLE NAMESPACE QUOTA ID XLIST CHILDREN X-GM-EXT-1

Making an educated guess: My server does not support sort ?
Comment: Not as-is, by the look of it.  Whether or not you can enable it depends on what sort of IMAP server you're running.
Comment: Its Gmail btw :)


Assign two domains to different web servers (Zend Server & IIS) on same machine

Question: I have two sites implemented in one machine. One site is hosted in IIS, and another is in Zend Server. Each site will have a domain, and I have only one IP to assign both.
How can I configure DNS so that both sites are accessed correctly from the internet?
Answer: Only one process can listen on a particular IP:port combination, regardless of DNS. If you only have one IP address, and both sites must be accessible on port 80, you've got problems.
If you really can't get a second IP address or port, you will have to run a reverse-proxy on port 80 to listen to incoming connections, pick out the Host: header, and redirect the HTTP request to the appropriate server (which will be running behind the scenes on a non-80 port).
This could be a third server, or one of the existing servers if they have the ability to work as a reverse proxy (eg IIS with ApplicationRequestRouting.)
Answer: You need to use "A" records for whatever domains you want to resolve to that IP address. Use CNAME records for subdomains. See this:
http://www.tech-recipes.com/rx/311/dnsbind-resource-record-cname-canonical-names-host-aliases/


Extrair .zip com status

Question: Como extair arquivos .zip de uma maneira que eu possa ver os status dos itens que estão sendo extraídos.
Ex: static string GetStatus() { return "Extraindo... " + current_arquivo; }
Usando o sistema OpenSource do Ionic.Zip Ionic.Zip no codeplex
Answer: Acho que pode usa da seguinte maneira:
Dentro do ForEach você Terá cada Arquivo..
private void MyExtract()
{
  string zipToUnpack = "C1P3SML.zip";
  string unpackDirectory = "Extracted Files";
  using (ZipFile zip1 = ZipFile.Read(zipToUnpack))
  {
      // here, we extract every entry, but we could extract conditionally
      // based on entry name, size, date, checkbox status, etc.
      foreach (ZipEntry e in zip1)
      {
        e.Extract(unpackDirectory, ExtractExistingFileAction.OverwriteSilently);
      }
   }
}

Clique Mais Referências

Extrair .zip com status


Metrics around Kafka Producer

Question: Is there a way we can find some metrics around batching. For eg. How many bytes of data are being transmitted on every batch and at what time intervals.
Answer: Kafka provides you a method called metrics() in the KafkaProducer.
You can get the metrics as a map.You can find more info below.
https://kafka.apache.org/0102/javadoc/org/apache/kafka/clients/producer/KafkaProducer.html#metrics()

Metrics around Kafka Producer


How to convert ImageInputStream to BufferedImage in Java?

Question: I'm trying to retrieve a image blob from mysql database and converting it back to image file. Iterating mysql ResultSet as:
while(rs.next())
{
   byte[] byteArray=rs.getBytes("image_blob");
   InputStream in=new ByteArrayInputStream(byteArray);
   ImageInputStream is = ImageIO.createImageInputStream(in);
   BufferedImage image_Bf=ImageIO.read(is);
   ImageIO.write(image_Bf, "png",new File("images/"+rs.getString("name")));
}

When I compile and run my java class it gives me error:

java.lang.IllegalArgumentException: image == null!

How can i solve this issue?
Comment: can you be clearer by providing the stack trace
Answer: ImageIO.read(is); returns null for you.  Javadoc says that means it can't locate an appropriate ImageReader, which seems to be a sign of an invalid input.
Actually, your error is in this string: rs.getBytes("name");. You are not getting image content to byteArray, but rather image name in byte form, so ImageIO.read fails.
EDIT:
If it still fails with same error, then you'll have to debug. Try outputting the byte buffer to the file directly. Do you get a valid image this way? I'm pretty sure ImageIO needs a correct image to operate on and convert to PNG.
while(rs.next())
{
   byte[] byteArray=rs.getBytes("image_blob");
   FileOutputStream fos = new FileOutputStream("images/"+rs.getString("name"));
   fos.write(byteArray);
   fos.close();
}

Comment: yes it's my error but it gives same error at rs.getBytes("image_blob").
Comment: Try to see what you're actually getting from the database. See updated answer.
Comment: updated answer doesn't save file as image(.png/jpg). it save .txt file containing image bytes
Comment: But .txt containing image bytes is essentially the image, just change the extension? It reflects exactly what you get from your blob field, if you can't open the resulting file as an image, you can't convert it using `ImageIO` either. Perhaps the data in your blob field isn't stored as bytes, but encoded somehow - as base64 or hex for example?
Answer: successfully resloved this issue.Here is correct code for retrieving images from database
while (rs.next())
            {
                Blob image_blob=rs.getBlob("image_100x100");
                int blobLength = (int) image_blob.length();
                byte[] blobAsBytes = image_blob.getBytes(1, blobLength);
                InputStream in=new ByteArrayInputStream( blobAsBytes );
                BufferedImage image_bf = ImageIO.read(in);
                ImageIO.write(image_bf, "PNG", new File(folder_path+"/"+rs.getString("name")));
            }