Não consigo centralizar uma ul dentro da div

Question: Olá!
Não consigo centralizar uma ul dentro da div

CSS
.menu {
  clear:both;
  position:relative;
  width: 100%;
}

.sessoes  {
   width:1000px;
   margin: 0 auto;
}

.menuNav {
   width:100%;
   text-align:center;
   background-color:#3E4095;
}

ul.menuTopo {
   text-align:center;
}

ul.menuTopo li {
    height:50px;
    border-left: #005E9C 1px solid;
}

ul.menuTopo li a {
    display:inline-block;
    height:50px;
    line-height:50px;
    vertical-align:middle;
    text-align:center;
    color: #FFF;
    background-color:#3E4095;
}

ul.menuTopo li a:hover {
    color: #FFF;
    background-color:#CCC;
}

HTML

Principal

Cadastrar

Editar

Pedidos

E-mails

Se eu fizer
ul.menuTopo {
   width: 100%;
   text-align:center;
}

Ao invés de ficar a 100% da div pai que é a div menuNav, ele empurra as divs que estão abaixo dela todas para a esquerda.
Outro problema são as contas:
São 1000px de menuNav (100% da div sessoes). Então tenho uma borda direita de 1 px para cada li e uma boda esquerda de 1px para a primeira li.  Logo, são 1000 - (5+1) = 994. 994/ 5 = 198.8 px. Pode colocar até 195 que dá quebra de linha.
Como concertar isso?
Answer: experimente com esse css ao invés de text-align: center:
margin: auto;

Comment: onde? Em qual estilo?
Comment: na ul que vc quer centralizar
Comment: margin: auto; (ou margin:0  auto;) width:100%; =>Toda a UL foi para direrta. E, margin: auto; => nada ocorreu e permaneceu descentralizado no mesmo lugar. Coloquei uma imagem na pergunta.
Answer: Se eu entendi direito vc pode setar um text-align: center na div PAI da sua UL e na UL setar ela como display: inline-block.
Comment: align: center já estava. Adicionei display: inline-block e continuou na mesma forma.
Answer: Agora entendi isso.
Primeiro: align:center e width: 100%(no meu caso nem precisava por que os links já ocupariam os 100%) na menuNav. Queremos o block apenas nos links e não nas li's. Então, as li's podem ser display: inline apenas.
Na ul, retire os espaços em branco de dentro e de fora com margin:0 e padding: 0
.menuNav {
    width: 100%;
    text-align: center;
    background-color: #3E4095;
}
ul.menuTopo {
    text-align: center;
    margin: 0;
    padding: 0;
}
ul.menuTopo li {
    border-left: #005E9C 1px solid;
    display: inline;
}
ul.menuTopo li:last-child {
    border-right: #005E9C 1px solid;
}
ul.menuTopo li a {
    display: inline-block;
    width: 195px;
    height: 50px;
    line-height: 50px;
    vertical-align: middle;
    text-align: center;
    color: #FFF;
    background-color: #3E4095;
}
ul.menuTopo li a:hover {
    color: #FFF;
    background-color: #CCC;
}

Dessa forma, ou seja, apenas os link's com display:inline-block, somos capazes de dar corpo (altura e largura dentre outras propriedades box), se necessário aos links e não às li's. Sendo assim, não é necessário colocar dimensões nas li's, apenas nos links.
Só uma coisa ainda não entendi: as contas não fecham:
1000px - 6px(bordas) = 994px.
994/5 = 198,8

No máximo que deu para chegar é 195px.
Estou errando em alguma coisa?
Answer: Você pode usar
ul.menuTopo {
   width: fit-content;
   margin: 0 auto;
}


marquee not completing the cycle using css3

Question: I have created a marquee , but the problem is marquee is not completing, i have 5 items , but when the maruqee reaches the fourth item or third item it starts the next cycle,
Am i missing something on the below code.
i have achieved this much. Also is this is the best way to achieve this

.students-container ul {
    list-style-type: none;
    height: auto;
    margin: 1em auto;
    overflow: hidden;
    background: white;
    position: relative;
    box-sizing: border-box;
}

.students-container .student-container{
    top: 6em;
    position: relative;
    box-sizing: border-box;
    animation: marquee 15s linear infinite;
}

.students-container .student-container  a{
    display: flex;
    align-items: center;
    margin-bottom: 15px;
}

.students-container .student-container .student-profile-image-container img{
    object-fit: contain;
    display: block;
    max-width: 230px;
    max-height: 95px;
    width: auto;
    height: auto;
}

.student-container:hover {
    animation-play-state: paused;
}

/* Make it move! */
@keyframes marquee {
    0%   { top:   8em }
    100% { top: -11em }
}

           It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum

           It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum

           It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum

           It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum

           It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum

Any help appreciated :)
Please see the  pen
Answer: The problem is that the end position of the animation has to be equal to the height of all containers combined ( 5x 95px). So all will move up until all dissapear. So that is about 500px
Otherwise the items will move up but not enough distance so every item dissapears out of the screen before returning back.
Also added the hover event on the parent container. SO all items stop moving when one is hovered. Otherwise the hovered item will stop moving, but the rest will keep moving and that would cause a mess.

.students-container ul {
    list-style-type: none;
    height: auto;
    margin: 1em auto;
    overflow: hidden;
    background: white;
    position: relative;
    box-sizing: border-box;
}

.students-container .student-container{
    top: 6em;
    position: relative;
    box-sizing: border-box;
    animation: marquee 2s linear infinite;
}

.students-container .student-container  a{
    display: flex;
    align-items: center;
    margin-bottom: 15px;
}

.students-container .student-container .student-profile-image-container img{
    object-fit: contain;
    display: block;
    max-width: 230px;
    max-height: 95px;
    width: auto;
    height: auto;
}

.students-container:hover .student-container{
    animation-play-state: paused;
}

/* Make it move! */
@keyframes marquee {
    0%   { top:   6em }
    100% { top: calc(-500px - 6em) }
}

           It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum

           It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum

           It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum

           It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum

           It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum

Answer: You should run the animation on the parent element, therefore .students-list, to prevent the running of the children, adjust the positioning of the animation to make it run full cycle, and calculate the height of the parent based on the defined max-height of 95px + margin-bottom of 15px, five times, therefore 550px:

* {box-sizing: border-box}

.students-container {
  position: relative;
  height: 550px; /* 5 x (95px max-height + 15px margin-bottom) */
  overflow: hidden;
  border: 1px solid; /* just for demo */
}

.students-list {
  display: inline-block;
  list-style: none;
  margin: 1em auto;
  background: white;
  position: absolute;
  animation: marquee 10s linear infinite;
}

.student-container a {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.student-profile-image-container img {
  object-fit: contain;
  display: block;
  max-width: 230px;
  max-height: 95px;
  width: auto;
  height: auto;
}

.students-list:hover {
  animation-play-state: paused;
}

@keyframes marquee {
  0%   {bottom: -100%}
  100% {bottom: 100%}
}

           It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum

           It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum

           It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum

           It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum

           It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum

Answer: Remove infinite from your animation

.students-container ul {
    list-style-type: none;
    height: auto;
    margin: 1em auto;
    overflow: hidden;
    background: white;
    position: relative;
    box-sizing: border-box;
}

.students-container .student-container{
    top: 6em;
    position: relative;
    box-sizing: border-box;
    animation: marquee 15s linear;
}

.students-container .student-container  a{
    display: flex;
    align-items: center;
    margin-bottom: 15px;
}

.students-container .student-container .student-profile-image-container img{
    object-fit: contain;
    display: block;
    max-width: 230px;
    max-height: 95px;
    width: auto;
    height: auto;
}

.student-container:hover {
    animation-play-state: paused;
}

/* Make it move! */
@keyframes marquee {
    0%   { top:   8em }
    100% { top: -11em }
}

           It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum

           It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum

           It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum

           It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum

           It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum


Como ler um objeto de um arquivo?

Question: Pessoal quando tento ler os objetos salvos em um arquivo aparece a seguinte mensagem de erro.
Nome: Gabriel
Código: 123
Telefone: 12345678
java.io.StreamCorruptedException: invalid type code: AC
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1600)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:430)
    at Cliente.lerArquivoL(Cliente.java:107)
    at Cliente.ler(Cliente.java:91)
    at TesteCliente.main(TesteCliente.java:8)

O que tenho que fazer para remover esse invalid type code: AC que ele está lendo? O problema é quando está escrevendo que vai "lixo" ou é na leitura que está pegando esse "lixo" ?
Cliete.java
import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.NoSuchElementException;

public class Cliente implements Serializable {
    private static final long serialVersionUID = 1L;
    private static ObjectOutputStream output;
    private static ObjectInputStream input;
    private int codigo;
    private String nome;
    //private Endereco endereco;
    private int telefone;

    public Cliente() {}
    public Cliente(String nome, int codigo, /*Endereco endereco*/ int telefone) {
        this.nome = nome;
        this.codigo = codigo;
        //this.endereco = endereco;
        this.telefone = telefone;
    }

    public int getCodigo() {
        return codigo;
    }
    public void setCodigo(int codigo) {
        this.codigo = codigo;
    }
    public String getNome() {
        return nome;
    }
    public void setNome(String nome) {
        this.nome = nome;
    }
//    public Endereco getEndereco() {
//        return endereco;
//    }
//    public void setEndereco(Endereco endereco) {
//        this.endereco = endereco;
//    }
    public int getTelefone() {
        return telefone;
    }
    public void setTelefone(int telefone) {
        if (telefone > 0) {
            this.telefone = telefone;
        }
    }

    public static void escrever(Cliente cliente) {
        abrirArquivoE();
        adicionarE(cliente);
        fecharArquivoE();

    }
    private static void abrirArquivoE() {
        try {
            output = new ObjectOutputStream(Files.newOutputStream(Paths.get("./bin/clientes.obj"), StandardOpenOption.CREATE,StandardOpenOption.APPEND));
        }
        catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }
    private static void adicionarE(Cliente cliente) {
        try {
            output.reset();
            output.writeObject(cliente);
        }
        catch (NoSuchElementException elementException) {
            elementException.printStackTrace();
        }
        catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }
    private static void fecharArquivoE() {
        try {
            if (output != null)
                output.close();
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }
    public static void ler() {
        abrirArquivoL();
        lerArquivoL();
        fecharArquivoL();
    }
    private static void abrirArquivoL() {
        try {
            input = new ObjectInputStream(Files.newInputStream(Paths.get("./bin/clientes.obj")));
        }
        catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }
    private static void lerArquivoL() {
        while (true) {
            try {

                Cliente cliente = (Cliente) input.readObject();
                System.out.printf("Nome: %s\n", cliente.getNome());
                System.out.printf("Código: %d\n", cliente.getCodigo());
                System.out.printf("Telefone: %d\n", cliente.getTelefone());
            }
            catch (EOFException endOfFileException) {
                endOfFileException.printStackTrace();
            }
            catch (ClassNotFoundException classNotFoundException) {
                classNotFoundException.printStackTrace();
            }
            catch (IOException ioException) {
                ioException.printStackTrace();
                break;
            }
        }
    }
    private static void fecharArquivoL() {
        try {
            if (input != null)
                input.close();
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }
}

Classe com o método main, TesteCliente.java
public class TesteCliente {
    public static void main(String[] args) {
        Cliente.escrever(new Cliente("Gabriel", 123, 12345678));
        Cliente.escrever(new Cliente("Maria", 124, 1234567889));
        Cliente.escrever(new Cliente("Carlos", 125, 1234567890));
        Cliente.escrever(new Cliente("Pedro", 126, 1234567890));

        Cliente.ler();
    }
}

Answer: Ola,
Você tem que deixar o OutputStream aberto enquando você estiver escrevendo dados, o método escrever não deve abrir o OutputStream, você tem que alterar a lógica do seu programa para para criar um OutputStream apenas uma vez e usar ele para todos os clientes que você for escrever, entendeu?
Como você chama o método escrever várias vezes irá lançar aquela excessão porque o arquivo é o mesmo.
Você poderia criar uma classe por exemplo ArquivoUtil que abre o arquivo, essa classe vai ser responsável por abrir fechar e ler o arquivo, a classe cliente só usa ela
Ai no seu teste você teria algo mais ou menos assim
public class TesteCliente {
    public static void main(String[] args) {
        ArquivoUtil.abrirArquivo();
        Cliente.escrever(new Cliente("Gabriel", 123, 12345678));
        Cliente.escrever(new Cliente("Maria", 124, 1234567889));
        Cliente.escrever(new Cliente("Carlos", 125, 1234567890));
        Cliente.escrever(new Cliente("Pedro", 126, 1234567890));

        ArquivoUtil.abrirArquivo().ler();
    }
}

Tenta alterar ai o seu código, qualquer coisa posta novamente

Como ler um objeto de um arquivo?


Computing the Integral $\int r^2 \text{J}_0(\alpha r) \text{I}_1(\beta r)\text{d}r$

Question:
I encountered the following integral in a physical problem
  $$I=\int r^2 \text{J}_0(\alpha r) \text{I}_1(\beta r)\text{d}r$$
  where $\text{J}_0$ is the Bessel function of first kind of order $0$ and $\text{I}_1$ is the modified Bessel function of order $1$. Also, $\alpha$ and $\beta$ are arbitrary real numbers.

It seems that MAPLE and WOLFRAM are not able to find the primitive. However, I think that there should be a tidy one in terms of Bessel functions.

My Thought
My instinct in integration tells me to use integration by parts and the recursive relations for Bessel functions. But I couldn't get any where yet.
Comment: u might find this site quiet helful:
http://dlmf.nist.gov/10.22
Comment: @tired: Thanks, how can I search this integral there!? :)
Comment: i just say that u might something useful there. I guess there is a closed form but im not sure.
Comment: @tired: The most similar one there is the relation $10.22.7$. But they have the same multiplier $a$ in the argument! :)
Answer: First note that
$$ r\text{I}_1(\beta r)=\frac{\partial}{\partial\beta} \text{I}_0\left(\beta r\right).$$
Then we can write
\begin{align}
\mathcal{I}(t):=&\int_0^t r^2 \text{J}_0\left(\alpha r\right)\text{I}_1\left(\beta r\right) dr\\
=&\frac{\partial}{\partial\beta}\int_0^t r\text{J}_0\left(\alpha r\right)\text{I}_0\left(\beta r\right)dr\\
=& \frac{\partial}{\partial\beta}\left[\frac{t\left(\alpha \text{J}_1(\alpha t)\text{I}_0(\beta t)+\beta \text{J}_0(\alpha t)\text{I}_1(\beta t)\right)}{\alpha^2+\beta^2}\right].
\end{align}
The last line follows from the formula 220.127.116.11 in Vol. II of Prudnikov-Brychkov-Marychev (and can of course be verified by direct differentiation).
Comment: (+1) Oh, GOD! That was GREAT! :) I would be happier if you included the computation of the last integral! :)
Comment: @H.R. For the proof of the last integral, one only needs to differentiate the expression in square brackets with respect to $t$ and use recursion relations for Bessel functions. However if the answer were unknown, it would be unclear to me how to proceed.
Comment: Of course, taking derivative is much easier than finding primitive! :)
Answer: According to the Start Wearing Purple's answer, I just took the computations and wanted to put the final answer here
$$\eqalign{
  & I = {1 \over {{\alpha ^2} + {\beta ^2}}}\,\,\,\,\left( {\alpha {\text{I}_1}\left( {\beta r} \right){\text{J}_1}\left( {\alpha r} \right) + \beta {\text{I}_0}\left( {\beta r} \right){\text{J}_0}\left( {\alpha r} \right)} \right){r^2}  \cr
  & \,\,\, - {{2\beta } \over {{{\left( {{\alpha ^2} + {\beta ^2}} \right)}^2}}}\left( {\alpha {\text{I}_0}\left( {\beta r} \right){\text{J}_1}\left( {\alpha r} \right) + \beta {\text{I}_1}\left( {\beta r} \right){\text{J}_0}\left( {\alpha r} \right)} \right)r \cr} $$
Hope that it may be useful for future readers. There may still be other heuristic ways to compute this integral so do not hesitate to write a new answer with a different approach. :)


If $\lim_{n\to\infty} f_n = f$ and $\lim_{n\to\infty} y_n = y$, does $\lim_{n\to\infty} f_n(y_n) = f(y)$?

Question: If $\lim_{n\to\infty} f_n = f$ and $\lim_{n\to\infty} y_n = y$, does $\lim_{n\to\infty} f_n(y_n) = f(y)$?
In particular I'm trying to prove that that if $\lim_{n\to\infty} (1+\frac{x}{n})^n = e^x$, and $\lim_{n\to\infty} \lambda_n = \lambda$ where $\lambda_n$ is a sequence of real numbers, then $\lim_{n\to\infty} (1+\frac{\lambda_n}{n})^n = e^\lambda$.
I want to believe this is true in general for any $f_n$ and $\lambda_n$, but I've never seen a proof for this before, and I haven't found this stated as a theorem anywhere.
Note: This is not a homework question, but it is related. The homework solutions are already given to me, and they just conclude this is true without justification, but I don't see why.
The main thing I'm looking for a source of this. Is this a theorem from somewhere that I can use? Should I prove it manually? Again, not relevant to my current homework assignment, but I'd like to know in case this ever comes up again. This solutions seem to imply this is trivial.
Comment: "Uniform convergence" is what you are looking for.
Comment: I didn't realize there were multiple definitions. My textbook define it as $f_n$ converges to $f$ if $f_n(x)$ converges to $f(x)$ for all x in the domain of $f$.
Answer: It is not true in general. Take, for instance,$$f_n(x)=\begin{cases}\sin(nx)&\text{ if }x\in\left[0,\frac\pi n\right]\\0&\text{ otherwise.}\end{cases}$$Then, for each $x\in\mathbb R$, $\lim_{n\to\infty}f_n(x)=0$. However, $\lim_{n\to\infty}\frac\pi{2n}=0$ and $\lim_{n\to\infty}f_n\left(\frac\pi{2n}\right)=1$.
On the other hand, it is true in the context of $\left(\left(1+\frac xn\right)^n\right)_{n\in\mathbb N}$, because it converges uniformly to $e^x$ on any interval $[a,b]$.
Comment: I've looked up uniform convergence again, but I still don't understand why it's applicable here. I mean, it intuitively makes sense to me, but I can't find any proof of this.
Comment: You will find a proof [here](https://math.stackexchange.com/questions/1714973/for-each-bounded-subset-in-mathbbc-lim-n-rightarrow-infty1x-nn-e).
Comment: I'm not confused about why it's uniformly convergent, I'm confused as to why that matters. Why does the function being uniformly convergent imply $f_n(\lambda_n) \rightarrow f(\lambda)$?
Comment: Let $[a,b]$ be an interval containing all $\lambda_n$'s. Take $\varepsilon>0$. Since the convergence is uniform, there is a $N\in\mathbb N$ such that$$n\geqslant N\implies(\forall x\in[a,b]):\lvert f(x)-f_n(x)\rvert<\frac\varepsilon2.$$And since $f$ is continuous and $\lim_{n\to\infty}\lambda_n=\lambda$, there is a $M\in\mathbb N$ such that$$n\geqslant M\implies\lvert f(\lambda)-f(\lambda_n)\rvert<\frac\varepsilon2.$$But then, if $n\geqslant\max\{N,M\}$,$$\lvert f(\lambda)-f_n(\lambda_n)\rvert\leqslant\lvert f(\lambda)-f(\lambda_n)\rvert+\lvert f(\lambda_n)-f_n(\lambda_n)\rvert<\varepsilon.$$
Comment: @J Okay the proof makes sense. Is there a name for this theorem, or even just this concept of a sequence of functions of a sequence? Again, my homework solutions seem to believe it's trivial, but I don't know what to search for to verify if it's something well known or not.
Comment: If it has a name, I am nor aware of it. It is a standard theorem in the context of uniform convergence.
Answer: For the particular case you are considering, the usual trick to obtain the result is the following
$$\left(1+\frac{\lambda_n}{n}\right)^n = \left[\left(1+\frac{\lambda_n}{n}\right)^{\frac n{\lambda_n}}\right]^{\lambda_n}$$
and wlog for $\lambda>0$ by $x=\frac n{\lambda_n}\to \infty$ we can use that
$$\left(1+\frac{\lambda_n}{n}\right)^{\frac n{\lambda_n}}=\left(1+\frac{1}{x}\right)^{x} \to e$$
Refer also to

Composition and Limits at Infinity
Comment: Isn't the first inequality an *equality?* But then you have something like $(x_n)^{\lambda_n}$ where $x_n \to e$ and $\lambda_n \to \lambda$, and it still remains to justify why  $(x_n)^{\lambda_n} \to e^\lambda$.
Comment: @MartinR Opsss yes, I fix the typo!
Answer: Consider $f_n(x)=x^n ,x\in [0,1),n\in \mathbb N$ which converges to $f(x)=0$ at non zero $x, f(x)=1$ at $1$ on $[0,1]$. But take the sequence $y_n=1-1/n$ converging to $1$,but $f_n(y_n)=(1-1/n)^n$ which converges to $1/e$.


Functions with different codomain the same according to my book?

Question: My book gives the following definition:

A function $f$ from $A$ to $B$ is defined as $f\subseteq A\times B$ such that if $(a,b)\in f$ and $(a,b_1)\in f$ then $b=b_1$ and there exists a $(a,b)\in f$ for each $a \in A$ .

Now according to this definition, the function would be the same even if the codomains are different. Is it true?
Comment: Good question and good answers on it. Keep both possibilities in sight. E.g. in set-theory $f\subset A\times B$ s.t. $\forall a\in A\exists!b\in B\;\left(a,b\right)\in f$ is convenient. E.g. in categories $f=\left(A,G,B\right)$ where $G\subset A\times B$ s.t. $\forall a\in A\exists!b\in B\;\left(a,b\right)\in G$ is convenient.
Answer: Yes. You can change th codomain, and as long as it includes the range of $f$, the function is the same.
For example, $\sin\colon\Bbb R\to\Bbb R$ and $\sin\colon\Bbb R\to[-1,1]$ are the same function. Or $f(1)=1$ is the same whether or not $f\colon\{1\}\to\Bbb N$ to $f\colon\{1\}\to\{0,1\}$.
As the other answers indicate, in some contexts a function is a triplet where the codomain is specified explicitly. It can be useful to know the codomain as part of the function. In set theoretic contexts, it is sometimes better to treat a function as a set of ordered pairs with a certain property.
Why is it useful? For example, it dispenses the need to talk about "canonical injection", and we can just talk about inclusion. Now we can say that $f\subseteq g$ when $g$ is a larger function, or that $f\cap g$ is a function. It allows us to define partial functions more easily, especially in the context of predicate logic: we can define a predicate which is a function on its domain, and it is not necessary this domain is the entire universe of the structure (so the predicate cannot be a function symbol). This is very useful, for example, in computability theory.
Comment: An example of the use you mention for the codomain: it's often more convenient to say that the sine function "is not surjective", as opposed to saying it's "not surjective onto $\mathbb{R}$". Or one might say that the first sine function you define "is not surjective" and the second one "is surjective". If the codomain isn't part of the function, then trivially *every* function "is surjective"!
Comment: @Steve: Yes, that is true. If you include the codomain in the definition then it is easier to talk about surjectivity. I don't find that a sufficient reason for doing so, though. :-)
Comment: I don't think this is the correct answer because I don't think this is a matter of usefulness. This is a matter of consensus. Is there a consensus, or not?
Answer: If you look at a function as a pure set of ordered pairs, then yes your observation is true. If you look at it as a triple $(A,B,\text{set of ordered pairs})$ then $B$ matters. If you replace $B$ in the triple by the image (some books call it range) of $f$ (some $B' \subseteq B$), then again your observation is true.
Basically, this is a nit you should not worry too much about.
Answer: This really depends on how you formally define "the same".  In mathematics, this is done by specifying an equivalence relation giving rise to equivalence classes of functions.  It is possible to specify an equivalence relation between functions that requires them to have the same codomain in order to be considered "the same" (i.e., functions with different codomain are not the same), and it is possible to specify an equivalence relation  that ignores the codomain (i.e., functions can be the same even if they have different codomains).
Formally, functions with specified codomains are triples $(\mathcal{X}, \mathcal{Y}, \mathscr{G})$ containing a domain $\mathcal{X}$, a codomain $\mathcal{Y}$, and a graph $\mathscr{G} \equiv \{ (x,f(x)) | x \in \mathcal{X} \}$.  You can define the equivalence relations $\sim$ and $\overset{*}{\sim}$ respectively by:
$$\begin{matrix}
f_0 \sim f_1 & & \iff & & (\mathcal{X}_0, \mathcal{Y}_0, \mathscr{G}_0) = (\mathcal{X}_1, \mathcal{Y}_1, \mathscr{G}_1), \\[6pt]
f_0 \overset{*}{\sim} f_1 & & \iff & & (\mathcal{X}_0, \mathscr{G}_0) = (\mathcal{X}_1, \mathscr{G}_1). \\[6pt]
\end{matrix}$$
The first equivalence relation requires equivalence of the codomains of the two functions, whereas the second does not.  Both give a well-defined notion of when two functions are "the same".
So, the real question here is, which of these two equivalence relations is more useful?  Well, it turns out that the codomain isn't really important for most properties of functions.  Indeed, the "meat" of a function is given by the graph $\mathscr{G}$ that shows all pairs of values (i.e., all the combinations of a value in the domain and the value it maps to).  (However, for some cases where the codomain is important, see here.)  Consequently, we tend to adopt the convention that two functions are considered "the same" if they have the same domain and graph, but we do not require the same codomain.  This means that we adopt the above equivalence relation $\sim$ as specifying when two functions are "the same".
Comment: I don't disagree with either of those comments.  You can certainly enlarge or shrink the codomain (down as far as the range) as your pleasure dictates, but if the function is conceived to *have* a codomain then that is still part of the specification of the function.  (And if it is not part of the function then the function is one *without* a codomain.)  I also agree that sameness is equality, but equality of what?  The specification of the function can include or exclude the codomain, so the equality can include or exclude this part.
Comment: Usually when people say "the same", without any additional qualifiers, they mean equality. Now, you could argue that from a categorical perspective that may very well be "too strong" and the right answer should be "isomorphic", or some variant of that, but nevertheless "the same" is "equality".
Comment: I also wouldn't say that "Formally, functions with specified codomains are triples ...", because I can very well specify $p\colon X\to Y$ and still work under the assumption that the function is a set of ordered pairs, and then I can extend, shrink, or otherwise manipulate $Y$ as my pleasure dictates (and as I said in my answer, this *is* useful and we do end up doing that in some situations throughout mathematics).
Comment: Two things are equal if they are the same thing. It's the connection between syntax and semantics. And yes, I am well aware of the HTT approach to equality is that "some equalities are more equal than others", but in non-category/type theory based approaches, equality *is* equality, not "whatever reasonable equivalence relation you want".
Comment: Yes, and as I said, what *are* the two things in question here?  If we are talking about equality of functions, are the functions just the double of their domain and graph, or are they they triple of their domain, graph and codomain?
Comment: (If you look at the content of the two equivalence relations I have stated here, you will notice that they *are* asserting equality, just equality of different things.)
Answer: Let's stand back a bit -- sometimes it is worth thinking what's behind a convention.
So: start by thinking  how, in practice, we informally prove that there's exactly one function that satisfies a certain description --- e.g. is a unique order-isomorphism between $(A, <)$ and $(B,\prec)$. We need to show that there's at least one such function, and that there is at most one. How do we do the second bit? We show that if $f$ and $f'$ are candidates, then they are the same function. And how do we do that? We show that for every $a$ among the objects $A$, $f(a) = f'(a)$. But why does that show that $f$ and $f'$ are the same function?
It only does so on an extensional understanding of what a function is: we are taking it that functions aren't individuated by the rules we give for associating an argument with value but by the resulting association. So, even if we have two different rules of association, if they both generate the same collection of pairings between arguments and values, we count the rules as two different ways of presenting the same function.
Now this doesn't yet warrant defining functions as collections of argument/value pairings; that identification involves another idea beyond extensionality, call it plenitude.  This is the further idea that any old association of arguments with values (one value per argument) determines a function, even if that association is beyond any possibility that we could describe it. It is one thing to say that different rules can determine the same function (extensionality), it is another thing to say that there can be functions which have no describable rule that determines their values (that functions are as plenitudinous as arbitrary argument/value pairings). Taking the second step might seem natural in hindsight, but its almost universal acceptance was the result of hard won achievements in 19th century mathematics.
OK: if we go for extensionality and plentitude, it becomes entirely natural to define a function from $A$ into $B$ -- or perhaps we should really say "model" or "implement" a function  -- as a set of ordered pairs $(a, b)$ with only one pair for each $a$. That fixes functions as extensional items, and is naturally understood as making the functions as plenitudinous as the relevant sets.
Hence the characterization of functions we find in elementary analysis texts which implements functions as sets of ordered pairs in such a way that changing the co-domain doesn't change the function. That's because what matters in the elementary context is to emphasize an extensional understanding of what functions and to stress that you can have functions associated with no describable rule for associating argument to function.
Now sure, in further non-so-elementary contexts it can be useful to explicitly build into our characterization of a function the domain (if we are going to start seriously dealing with partial functions) and codomain. That refinement doesn't make the implementation in (some of) the elementary texts wrong -- that serves perfectly to make the points the elementary texts need to make.


Creating a new Folder with given path

Question: I'm wondering if any of you have created a function to create a folder within a given path.
For Example:
NewFolder = ['/projects/Resources/backup_Folder']
Comment: what do you want exacly? and maybe you can have a look into the module os.path.
Answer: Use the os library, specifically os.mkdir()
https://docs.python.org/2/library/os.html#os.mkdir
For example,
path = "/usr/temp/foo"
os.mkdir(path)

If the intermediate folders don't exists, use os.makedirs as per Peter Wood's comment
path = "/newfolder1/newfolder2/foo"
os.mkdir(path)

Comment: This won't work if intermediate directories don't exist (e.g. if `/usr/temp` doesn't exist). You need [**`os.makedirs`**](https://docs.python.org/3/library/os.html#os.makedirs)
Comment: Thank you very much Adam! It took me some time to understand what I was doing. I'm new to programming less than a year. landed an internship with a data science team. So this is all a learning experience for me. You were able to solve my issue.
Comment: Happy to help, good luck with your internship

Creating a new Folder with given path


Why can't standard conditional language models be trained left-to-right *and* right-to-left?

Question: From the BERT paper:

Unfortunately, standard conditional language models can only be trained left-to-right or right-to-left, since bidirectional conditioning would allow each word to indirectly "see itself", and the model could trivially predict the target word in a multi-layered context.

I do not understand this. To my understanding training a standard conditional language model  means to collect n-grams and to compute ratios e.g. $p(w_c | w_a, w_b) = \frac{c(w_a,w_b,w_c)}{c(w_a, w_b, *)}$ The probability of $w_c$ after observing $w_a, w_b$ is the number of times the sequence $w_a, w_b, w_c$ is observed by the number of times a sequence $w_a, w_b$ with an arbitrary third element is observed.
And this can certainly be extended to bidirectional like this:  $p(w_c | w_a, w_b, w_d, w_e) = \frac{c(w_a,w_b,w_c,w_d,w_e)}{c(w_a, w_b, *, w_d, w_e)}$.
So I must be misunderstanding something here. What is it? What else would left-to-rigth training of a standard conditional language model be?
This question has been asked in other places with either no answer:
https://ai.stackexchange.com/questions/11755/how-does-bidirectional-encoding-allow-the-predicted-word-to-indirectly-see-itse
or answered but not to my satisfaction:
https://datascience.stackexchange.com/questions/57000/bi-directionality-in-bert-model
I'm asking here again because its about machine learning and I consciously left everything out about bert or higher methods.
Answer: In a standard language model (LM), you're trying to predict the probability of the next word given the past. The past could be a fixed window size of $n$ words, as in your example, or an indefinitely long window size, as in the case of RNNs (and their variants). Without loss of generality, let's stick with the RNN as the LM since that is a relatively common choice. Mathematically, each output $\hat{y}^{(t+1)} \in \Delta^{|V|}$ of an RNN specifies a conditional distribution $p(w^{(t+1)}| x^{(t)}, \ldots, x^{(1)})$ over $|V|$ words in the vocabulary $V$ for the next word $w^{(t+1)}$ given embeddings $x^{(s)}$ for $s = 1, \ldots, t$. This can be expressed as:
$$
h^{(t)} = f(x^{(t)}, h^{(t-1)})\\
\hat{y}^{(t+1)} = p(w^{(t+1)} | x^{(t)}, \ldots, x^{(1)}) = g(h^{(t)}) = \mbox{softmax}(W_oh^{(t)} + b_o)
$$
where $f$ and $g$ are recurrent and softmax neural network layers, respectively.
This is a unidirectional LM since the probability of the next word is only dependent on the past. Suppose we could instead create a "bidirectional LM" using a bidirectional RNN. We would then have:
$$
\overrightarrow{h^{(t)}} = \overrightarrow{f}(x^{(t)}, \overrightarrow{h^{(t-1)}})\\
\overleftarrow{h^{(t)}} = \overleftarrow{f}(x^{(t)}, \overleftarrow{h^{(t+1)}})\\
h^{(t)} = [\overrightarrow{h^{(t)}}; \overleftarrow{h^{(t)}}]\\
\hat{y}^{(t+1)} = p(w^{(t+1)} | x^{(T)}, \ldots, x^{(1)}) = g(h^{(t)}) = \mbox{softmax}(W_oh^{(t)} + b_o)
$$
where $T$ is the length of the entire sequence. The problem here is that you're training the second RNN from back to front. At time $t$, the backward RNN already knows what word should come at time $t+1$ because
$$
\overleftarrow{h^{(t)}} = \overleftarrow{f}(x^{(t)}, \overleftarrow{h^{(t+1)}}) = \overleftarrow{f}(x^{(t)}, \overleftarrow{f}(x^{(t+1)}, h^{(t+2)}))
$$
and the embedding of $w^{(t+1)} = x^{(t+1)}$. Thus, the word is able to "see itself."
This is illustrated in the example below, in which the word "runs" is already seen by the backward RNN (dashed green arrow) before the LM tries to predict it (black arrow).

To remedy this, BERT includes MASK tokens, which mask certain words in the input sequence from being seen by the LM. If the word "runs" were masked, then there would be no way for the LM to know what it is, even if words that came after it (e.g., "quickly", not shown in this example) are present. This is because the only thing that would be revealed is the presence of a MASK token, not the actual word.
In addition, a major difference between BERT and the LM shown here is that BERT is a Transformer-based architecture, but conceptually, the concept of a word "seeing itself" is the same. Note that these MASK tokens could be applied in this LM as well, but the Transformer model just has so much more going on, which is why it performs so well compared to RNNs.
Comment: Beginner question here: is the backwards RNN trying to predict a left-side word given a sequence of right-side words? If so, shouldn't it be predicting the word at time $t-1$ and not at $t+1$?
Comment: @sprajagopal Neither backward nor forward RNN layers predict any word. We use these to get right-to-left and left-to-right representations of a sequence, respectively. In the aforementioned example, only, a word at time t+1 is being predicted.


How to apply Test Driven Development with Django Models?

Question: I've recently learned about Test Driven Development and want to give it a shot while developing a new app in my Django project. I've been reading Test-Driven Development with Python which is great. However, I've sometimes found the example (To Do lists) in the book to be too simple- for instance, when testing Models is introduced, the author has a test that creates to objects, saves them, and then pulls the objects from the database to check their values. Sure, that's easy when your model only has one ModelField.
But what about when your model has twenty ModelFields? Should you have one test that creates an object, with all of its Fields, then saves that object, and then checks the value of each field? Is it better to make individual tests for each field?
In my specific case, I have a model with about five required fields, and then about fifteen more fields that are optional. My thought right now is to first have a function within my TestCase class that creates an object of this Model with the default fields. Then, I will have a test to make sure that object saves normally, and then another test for each individual optional field. Seems like a lot of tests, but isn't many small tests better than one large test?
Insight appreciated!
Answer: I am the author of said book.  I meant that test as more of an introduction to the Django ORM, rather than as a demonstration of best practice, and I try to explain that at the time, but I suppose some confusion was inevitable.  I'll have a think about how I could present things differently.
In any case, if you skip along to a few chapters later in the book, I show how to simplify the test to something that's more best-practicey.
Whether or not you test basic Django models is up to you -- some people will say testing a declarative syntax is over the top, others will say a short test is good to have as a placeholder.  Here's one you might use:
class Book(models.Model):
    title = models.CharField(max_length=200)
    author = models.ForeignKey(Author)
    ISBN = models.CharField(max_length=35)
    abstract = models.TextField()

class BookTest(TestCase):

    def test_defaults(self):
        book = Book()
        self.assertEqual(book.title, '')
        self.assertEqual(book.author, None)
        self.assertEqual(book.ISBN, '')
        self.assertEqual(book.abstract, '')

So that's a placeholder.  It encourages you to add more tests if you start introducing more complex fields like, say, a publication_date field which has a default value of datetime.today() + one_month, which might warrant a bit of testing to make sure you get it right.  Having a placeholder lowers the barrier to subsequent tests.  Other people will tell you that's over the top.  You have to find your own balance.
One thing that's pretty widely accepted is that you should definitely test behaviour.  So, if your model has a custom method:
class Book(models.Model):
    # [...]

    def is_available(self):
        return self.pub_date < datetime.today() and Stock.objects.filter(book=self).count() > 0

Then some sort of test for that is definitely a good idea.
Comment: Haven't read your book, but have watched 2 of your TDD Tutorials. The Oreilly TDD Webcast, and 2013 Pycon (To which I went). Im getting ready to watch some more of your talks on TDD. I have to say you've done a great justice by releasing so many tutorials on TDD.
Answer: This is where model factories would help a lot. There are two popular modules that provide it:

model_mommy
factory_boy

I've personally used factory_boy and find it very easy to use.
Basically, you define a factory with default field values:
class UserFactory(factory.Factory):
    class Meta:
        model = models.User

    first_name = 'John'
    last_name = 'Doe'
    admin = False

Then, you can use the factory and override field values if needed. It also supports Sequences, Lazy Attributes and other useful features for generating the data.
Speaking about your particular task, try not to test what django actually has tests for. For example, there is no need to test whether required argument works. Test your custom model logic involved in manipulating the model.
Also, A Guide to Testing in Django is a good read.
Hope that helps.
Comment: I understand what you're saying, but in speaking specifically with the test driven development approach, I believe that I shouldn't write code until I have a test for it, right? So if I want to have a ModelField on my Model, I must have a test for that, no? It's not that I want to test whether `required` works, it's that I want to test whether or not the field itself works on my Model. I.e, if I create an object and set that field, and save it, does it come back out? Yes in a way this tests Django, but it also provides design and test for my Model itself.
Comment: @Joseph correct, strictly speaking, if you want to follow the TDD approach entirely, then yes, before adding a new field on a model, you need to write a test for it, see it failing, add field and see the test passed. But, personally, I usually don't go so deep. Time is valuable and there are usually more important things to test. This is just my point. And I love testing, really.
Comment: Thanks, I think for now I'll proceed without going that far, like you mention. I've heard that TDD requires some kool-aid drinking, so I wanted to give it an honest try, even where that includes things that *seem* like they make more work or waste time- ideally the payoff is that time and work is saved later. Thanks for your help, and I appreciate the link to A Guide to Testing in Django.
Comment: @Joseph great, thank you. I also recommend watching Carl Meyer's presentation on [`Testing and Django`](http://pyvideo.org/video/699/testing-and-django). Also, there are [other great videos](http://pyvideo.org/search?models=videos.video&q=testing+django) on `django` and `testing`. Let me know if you need any further help. Happy testing!
Answer: Why would you test the saving and loading of values to the database? That's Django's responsibility. Django has a whole suite of tests that check in detail that its database layer is working. There is absolutely no reason to check the basic behaviour of any of your fields, let alone all of them.
Your unit tests are for your logic: your custom methods, your views, your template tags. They are not for logic that is provided by Django by default.
Comment: As mentioned on the other answer, I am specifically referring to Test Driven Development, not "regular" testing of my Django application. Like @alecxe confirmed, truly following the TDD approach requires tests before code, even for something as simple as a ModelField.
Comment: It's not so much testing saving & loading of values, but rather have you chosen the correct fields & properties on those fields.  For example, if you have a field on your model called ```account_number``` that has to be unique, there should be a test to make sure you've written your model to correctly add the ```unique=True``` property on that field as that's a business requirement that should be enforced by tests.


How do I create a new Slideshow in the header?

Question: I've inherited a site with a functioning Slideshow. I haven't been able to figure out how that appears on the site. And I'd like something similar to the functioning Slideshow in the header and have been unable to get that to work. The functioning Slideshow is comprised of:
A Panel Node with content:

View: Slideshow: Slideshow Block
Welcome Message Block
View:Featured Articles: Featured News Block
Home page mini

None of the objects, that I have been able to find, are set to appear (any place I can find), yet the home page shows all the appropriate stuff.
I've tried creating a new Panel Node with all the same content and it doesn't appear. I've tried creating a New Slideshow Block and putting it in the Header Region and the first image appears without rotation.
I'm confused and would appreciate some guidance.
Answer: This is just a guess since the information provided is very limited: Often slideshows in the header are output as background images on the theme level. So maybe you should have a look at your page.tpl.php (and maybe also your template.php) to see if at some point the view is called from there and not from the panel.
Comment: I've found lots of of those. Perhaps you can help me figure out which one(s) apply.

#find . -name page.tpl.php
./sites/all/themes/successinc/page.tpl.php
./sites/all/themes/saprivateschools/templates/page.tpl.php
./sites/all/themes/zen/templates/page.tpl.php
./new/themes/garland/page.tpl.php
./new/themes/seven/page.tpl.php
./new/themes/bartik/templates/page.tpl.php
./new/modules/block/tests/themes/block_test_theme/page.tpl.php
./new/modules/system/page.tpl.php
./themes/garland/page.tpl.php
./themes/seven/page.tpl.php
./themes/bartik/templates/page.tpl.php
Comment: Please go to /admin/build/themes/select and check which theme is in use. It should be the one that is set as standard. Once you get the name of the active theme, check in the folder with that name. For example, if "Bartik" is the theme in use, have a look at bartik/templates/page.tpl.php
Answer: I've had exactly the same thing to do this week.  Do you have a HTML.inc and a slide.inc file.   If it's the same set up it's pretty straight forward.  it loads the variable $slide with $panel info that you call back sequentially.
Could you post some code up and I'll see if it's the same and whether I can help you.
Comment: I can't find any HTML.inc or slide.inc. And there's no special code that I see, everything is done with standard modules.
Comment: I think you need to start by using one of the devel modules, these can help you understand what module and themes and classes are being used to create things https://drupal.org/node/1779516. That and using search in your IDE .


Can I split one RAID1 partition in two?

Question: I have a linux box with CentOS 6.2 and a RAID1 (2x 2Tb) configuration:
/dev/md1 -> / (10G)
/dev/md2 -> /home (1.9T)

I want to split the md2 in two different partitions, so I can get the following configuration:
/dev/md1 -> / (10G)
/dev/md2 -> /home (1T)
/dev/md3 -> /example (900G)

How can I achieve this?
I already know that I can resize the partition, but that doesn't alter the real partition table (only the md device), so how can I do this?
Answer: If you are not using LVM, you need to:

remove the md device (using mdadm),
remove the partition (using fdisk),
recreate the needed partitions (using fdisk),
and then recreate the md device (using mdadm).
Answer: you are best of using logical volumes.
You can then create, expand and pretty much do as much as you want.
there is a nice guide here
http://www.gagme.com/greg/linux/raid-lvm.php
Answer: The correct (initial) way would have been to overlay LVM on top of the RAID array, and then re-allocate volumes as needed.  But you're not at a point where this is probably feasible.
You may still have a way out.  Ext3/Ext2 are re-sizable, although it is slightly risky when you are contracting filesystems.  I don't recommend this unless you have no other options or you're willing to risk your data:

mount the array on a different machine.   This is necessary because your boot/root is on the array, complicating the process.  You could do this with a read-only mount, etc. but let's keep it simple.
you shrink the Ext2/3 filesystem to the new size.  This creates "space".  Note that the shrunk size is limited to the amount of data stored on disk...if you have 3Gbyte of data, you can't shrink it to 2.5Gbyte and expect it to work.
you then shrink the hard drive partition to match.  This is the tricky part.  Shrink too much, and you end up with a nasty overlap that will cause you to loose data.  It doesn't hurt if the partition is slightly larger than the filesystem size; you can always expand the existing partition into the extra space.
Write the partition table out to the MD device.

You have two paths now, one with LVM, one without.
With old-style partitions:

create one or more new disk partitions (as many as needed)
format each partition as a filesystem.
move existing filesystem data into the newly created partitions
edit /etc/fstab to mount the new partitions at boot time

With LVM:

mark all of the existing "new" space as an LVM partition.  Write the partition changes to disk.
create a new Volume Group from the partion.
Allocate logical volumes from the volume group
format each logical volume as a filesystem.
move existing filesystems into the newly created logical volumes
edit your /etc/fstab to mount the new LVM volumes at boot time

Can I split one RAID1 partition in two?


Collecting data across multiple executions of Mojo in custom Maven plugin

Question: I have a multi-module maven project, and I'd like to collect some information about all modules using a custom plugin.
I managed to get what I want for each module. Due to the nature of the information I collect, it would be much more effective to collect it in memory and dump the consolidated results at the very end.
Custom Mojo that illustrates the idea (and I know that does not work, see below):
@Mojo(name = "dummy")
public class DummyMojo extends AbstractMojo {

    private static Set<String> data = Collections.synchronizedSet(new HashSet<String>());

    @Parameter(defaultValue = "${project}", readonly = true)
    private MavenProject mavenProject;

    @Override
    public void execute() throws MojoExecutionException, MojoFailureException {
        data.add(mavenProject.getArtifactId());
        getLog().info("Execution #" + data.size());
    }

}

This collects artifact IDs of all my modules (this is just an example to simplify, in reality I collect some other irrelevant stuff).
I'd like to dump the result at the very end of the build.
If I run this, I observe that 2 instances are created (I have >100 modules):
% mvn com.company:foo:1.0-SNAPSHOT:dummy | grep 'Execution #'
[INFO] Execution #1
...
[INFO] Execution #6
[INFO] Execution #13
[INFO] Execution #14
[INFO] Execution #15
[INFO] Execution #7
[INFO] Execution #8
[INFO] Execution #9
....
[INFO] Execution #90
[INFO] Execution #91
[INFO] Execution #13
[INFO] Execution #92
[INFO] Execution #14
[INFO] Execution #15
[INFO] Execution #39
[INFO] Execution #40
[INFO] Execution #41

So I observe that I cannot collect data for each module and share it across each Mojo execution using a static variable.
If I also print PID and ClassLoader, I observe that it all happens in the same JVM process, but a second classloader is used for some modules. I vaguely know why: the affected modules (legacy stuff) use an exotic plugin (NetBeans Maven plugin), and today I'm discovering that I have to add that disappointment to the heap of issues it caused us.
Anway, questions:
1) Is there a correct way to collect data in memory across all executions of a given Mojo during a single multimodule build? (Or is there a way to ensure all executions happen in same JVM & same class loader?)
2) How can I detect end of build, once all modules have been visited? I suppose there is something on the build I can observe... Sorry my understanding is incomplete there... Lifecycle, reactor... What concept am I missing to implement this?
I'm ready to read about how that is a Bad Idea! I'm just experimenting at this point: if I'm misguided I do need "reguidance".
I checked that Q/A but it was about sharing across 3 different Mojos for a single module.
(For now I can dump the results every time, the last one overwrites the previous result, it's OK for my use case, but if I can improve that, it would be great)
Comment: What kind of data would you like to collect? You example shows your are using `mavenProject.getArtifactId()` ? Do you have the code for example on Github or simething alike?
Comment: I collect the transitive list of dependencies, and put that list of GAVs in a text file. For a time I was using the standard maven dependency plugin, but 1) the existing options for output are very limited, and 2) it is implemented using old complicated APIs, I am not able to understand the code so I cannot develop anything based on that. Nowadays (Maven 3) collecting dependencies is [very easy](https://stackoverflow.com/a/42559904/6730571) (see my comment to that answer ^^), and a custom plugin seemed easy to do... until I found this issue on multimodule builds.
Comment: I think I can put up a small runnable example on GitHub, that will be more representative of the actual problem I'm trying to solve. Not sure I can easily reproduce the ClassLoader issue, though...
Comment: Today again I needed to detect end of build (Q#2), and I realized sonar-scanner-maven must do this because it only does its magic at the very end of the multimodule build. Bingo... but it uses an [ugly trick](https://github.com/SonarSource/sonar-scanner-maven/blob/188.8.131.525/src/main/java/org/sonarsource/scanner/maven/SonarQubeMojo.java), incrementing a counter for each visited "project" and doing the work when total is reached :-/ Dear Maven, can you not offer something simpler?
Answer: SonarQube does this in sonar-scanner-maven, see SonarQubeMojo.
0) Mojo has annotation aggregator = true
1) Data is collected in a static variable in the mojo
2) They determine "end of build" by counting visited modules and comparing that to expected total. If this is not last module then do nothing (or collect what needs collecting...), if it is then run the thing (consolidate results).


C# Minimize Whole Application

Question: Is there a possible way in Visual Studio that you are able to minimize your whole application? I tried this:
private void button4_Click_2(object sender, EventArgs e)
{
    Application.WindowState = FormWindowState.Minimized;
    this.WindowState = FormWindowState.Minimized;
}

There is an error which is 'System.Windows.Forms.Application' does not contain a definition for 'WindowState' which means (if you didn't already know) that the application as a whole doesn't have a window factor (this I already knew) but is there a way to minimize all the windows in an application all at once?
Comment: Possible duplicate of [Is there a way to programmatically minimize a window](http://stackoverflow.com/questions/69352/is-there-a-way-to-programmatically-minimize-a-window). You shouldn't need to do it to `Application` - it obviously is a different type.
Answer: Try something like this.
foreach (Form form in Application.OpenForms)
{
    form.WindowState = FormWindowState.Minimized;
}

Answer: You can simply loop through all of the open forms in your application and set their WindowState property to "Minimized". Get the OpenForms collection for your Application class.
private void button4_Click_2(object sender, EventArgs e)
{
    foreach (var form in Application.OpenForms)
    {
        form.WindowState = FormWindowState.Minimized;
    }
}

C# Minimize Whole Application


MTR doesn't recognize IPs of hops

Question: I am building an integrated network operations portal that ties together information from a number of resources.  One thing I would like to understand is the topology of the network, and I am trying to use MTR to do so.  Unfortunately I don't think it is able to indeitfy the IP address of the Switches, Firewall, or Virtual (vSphere) switches.
I know there are a couple of hops to get to that end point.  And this output is useful, as I would be able to get understand the numbner of jumps between endpoints and therefore with enough data I will be able co confirm what is on the same sengment (logical or virtual), however I want to be able to understand how those segments fit together.
<code>$ mtr --show-ips  --report-wide 10.8.100.12
Start: Sat Feb 27 12:00:05 2016
HOST: tbrown                         Loss%   Snt   Last   Avg  Best  Wrst StDev
  1.|-- ???                            100.0    10    0.0   0.0   0.0   0.0   0.0
  2.|-- ???                            100.0    10    0.0   0.0   0.0   0.0   0.0
  3.|-- drblah02.xyz.com (10.8.100.12)  0.0%    10   76.2  76.1  73.7  80.7   2.3
</code>
Do these devices need to be enabled to provide this information somehow?
Comment: There's no such thing as a Layer 2 hop. If your switches are functioning as switches (as opposed to routers) then they won't show up in your trace. Hop count is a metric of how many routers the traffic passes through.
Comment: mtr won't see the switches as they work at layer 2.
Comment: hmm ok then.  So does the above look indicative of layer 2 hops?  My switches are Layer 3, but i are functioning most at layer 2 right now.
Comment: OK thanks I am staring to undertsand a bit more.  I need the right vocabulary to research and communicate.    I will dig into the traceroute documentation,  I get that only devides that decrement the TTL will get recorded.  Why do some of those devices not report back the host - instead I am getting a *.
Comment: Oh man, don't take it personal but before starting an "integrated network mgmt portal" why not get accustomed with the basics first? *sigh*
Comment: Because I dig in and figure out what I don't know, then fill the gaps.
Answer: The number of lines in the trace output will indicate how many times the hop limit (also called time to live) has been decreased on the path from you towards your peer. Thus a device which does not decrease the hop limit, will be invisible to the trace. For example switches will not be seen in the trace, because they operate at a lower layer than IP.
What also matters is how the device behaves once the hop limit goes to zero. If the device silently drops the packet, you will see a blank line. If the device produce an ICMP packet with a proper error code, you will see the source IP (or hostname) of that ICMP packet.
There are multiple possible reasons for a router to show up as a blank line in the trace:

It may configured to rate limit the amount of ICMP packets it will produce or to not send them at all.
It may have bugs in the ICMP generation (one possible bug is to use the remaining hop limit from the original packet in the ICMP packet).
It may not have enough CPU capacity to respond to all packets.

If you see multiple blank lines just before the final target, it is possibly to a bug in the IP stack on the target itself. If the target copies the hop limit from the original packet to the response, the response will not come back unless the original hop limit was enough to cover the route both ways. This will usually lead to the path looking twice as long as it really is - with no responses from the second half of the path.
Comment: I wonder if it is based around the vSphere   interface to the network.  Also (oddly) there are nodes equi distant away (yet on different subnets)  that come back with completely different routes.  BTW thans for the reponse, i am understanding peice by peice.
Comment: vSphere networking doesn't route traffic. a vSphere vSwitch and the host pNIC won't add hops to the path.

MTR doesn't recognize IPs of hops


Keep pagination repeatable if change operations are performed

Question: If one wants to paginate results from a data source that supports pagination we have to go to a process of:

defining the page size - that is the number of results to show per page;
fetch each page requested by the user using an offset = page number (0 based) * page size
show the results of the fetched page.

All this is works just fine not considering the fact that an operation may affect the backend system that screws up the pagination taking place. I am talking about someone inserting data between page fetches or deleting data.
<code>page_size = 10;
get page 0 -> results from 0 to 9;
user inserts a record that due to the query being executed goes to page 0 - the one just shown;
get page 1 -> results from 10 to 19 - the first results on the page is the result on the old page 0.
</code>
The described behavior can cause confusion to the viewer. Do you know any practical solution to workaround this problem.
Comment: i was about to ask the same question. I have noticed this happening a lot on Stackoverflow and Twitter recently.
Answer: There are a few schools of thought o this.

data gets updated let it be
You could implement some sort of caching method that will hold the
entire result set (This might not be
an option if working with really
large Datasets)
You could do a comparison on each page operation and notify the
user if the total record count
changes

.
Answer: If the updates you are concerned with are primarily new insertions (for example, StackOverflow itself seems to suffer from this problem when paging through questions and new questions come in) one way to handle it is to capture a timestamp when you issue the first pagination query, and then limit the results of requests for subsequent pages to items which existed before that timestamp.
Answer: As long as users understand that the underlying data is always changing, they won't be confused.  So just do it the straightforward way.
You could cache the first few pages of the result and use that for subsequent views, but then the results will be out of sync with the database, which is even more confusing.
Answer: One option is to exclude new incoming data objects from the result. This could be done with the session start time. You could add this for example to your JWT and then have a similar behavior like Twitter (14 new Twitts).


Wrong output while merging sorted arrays of equal length

Question: I'm trying to merge 2 sorted arrays of equal length. However, I'm not getting the desired output.
Here is my code:
    public static int[] mergeSorted(int[] arr1, int[] arr2){
        int n = arr2.length;

        int[] ans = new int[2*n];

        int k = 0;
        int i = 0;
        int j = 0;

        while(i < n && j < n){
            if(arr1[i] <= arr2[j]){
                ans[k] = arr1[i];
                i++;
            }
            else{
                ans[k] = arr2[j];
                j++;
            }
            k++;
        }

        while(i < n){
            ans[k] = arr1[i];
            k++;
            i++;
        }

        while(j < n){
            ans[k] = arr2[j];
            k++;
            j++;
        }

        return ans;
    }

    public static void main(String[] args){
        int[] arr1 = new int[]{1, 3, 5, 100, 34, 29};
        int[] arr2 = new int[]{2, 4, 6, 9, 13, 300};

        int[] ans = mergeSorted(arr1, arr2);

        for(int el : ans)
            System.out.print(el + " ");
    }

Output:
1 2 3 4 5 6 9 13 100 34 29 300
Clearly, this is not correct. However, this code works for smaller inputs. Where am I going wrong?
EDIT: Test cases were wrong as they were not sorted. Code was fine.
Comment: Your method would work if your two input arrays were sorted.
Comment: easiest approach: add all the elements, then run a sorting algorithm.
Comment: I know there are other ways to solve this but I want to know what I'm particularly doing wrong here.
Comment: Your title says you want to merge two sorted arrays, and yet your first array is unsorted.
Comment: @NomadMaker I have mentioned it in the edits section of my question.
Answer: For the merge operation to work, the two arrays you are merging should be in sorted order. The first array is not in sorted order:
    int[] arr1 = new int[]{1, 3, 5, 100, 34, 29};

Change it to:
    int[] arr1 = new int[]{1, 3, 5, 29, 34, 100};

Comment: And that is why I refrain from using random test cases which pop into my head. Thanks a ton!


Error 403 Forbidden

Question: So on my website am trying new form software out and once  have installed it I cannot access it at all and I get this error:
I'm Guessing its something to do with my .htaccess file so here is the contents of that:
Options -MultiViews
RewriteEngine On

RewriteCond %{HTTP_USER_AGENT} libwww-perl.*
RewriteRule .* – [F,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.html [NC,L]

Also I have checked the file permissions and they are correct
any help much appreciated
Tom
Comment: It may be a regular 404 (not found) error triggering a forbidden request (e.g. directory indexing) resulting in this page.
Comment: How would one find this out? Also any fix?
Answer: I am guessing that the forum is a separate application which you are trying to run inside the existing application. In which case, you might be missing rewritebase directive. something like:
RewriteBase /forum/

Have a look at http://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewritebase
Comment: Is the .htaccess file inside a folder named /forum ? If so, add RewriteBase /forum/ just after RewriteEngine On
Comment: The .htaccess is in the root www.webname.co.uk/

Error 403 Forbidden


Getting the value from momentJS subtract without a time zone or offset (GMT +0000)

Question: I wish to produce a date 30 days in the past using momentJS - it's pretty easy, I just use the following
const date30DaysPast = moment().utc().subtract(30, 'days').toDate(); // Sun Oct 29 2017 13:23:46 GMT+0100 (CET)

This is all great however I want the returned date to have no Time Zone or offset, I want the time to be GMT+0000 not as above GMT+0100 (CET) - for example:

Sun Oct 29 2017 13:23:46 GMT+0000

I wish to force this as I am using testing servers that are in different locations, and rather than take the time from the local browser I just want set a standard time. I thought using the utc method would do this for example should I write something like this in my test:
const oct4th2017 = moment.utc(new Date('October 04, 2017 11:13:00'));

the output is

Wed Oct 04 2017 09:13:00 GMT+0000

How can I remove the offset / time zone and set it to GMT on my original subtract method? I have tried wrapping in a parent utc method like so
const date30DaysPast = moment.utc(moment().utc().subtract(30, 'days').toDate());

but this doesn't work. I get the momentJS object.
Any advice could be appreciated, should my wording be bad or confusing please say so and I shall reword my question.
Answer: You already have your moment.js object without timezone. But the toDate() method creates a native Date object, which always has the local timezone (though it has various UTC methods).
Comment: I thought as much, removing the `toDate()` just returns an object, for example, `Moment{_isAMomentObject: ...` I just need to know how to get the value of the date without using the `toDate` method
Comment: or `valueOf()` to get the timestamp in milliseconds since 1st Jan 1970
Comment: or [`toISOString()`](http://momentjs.com/docs/#/displaying/as-iso-string/), in general see [Display](http://momentjs.com/docs/#/displaying/) section of the docs.


After installing Drush on Mac it only downloads drupal 6x

Question: I am having issues installing Drush on Mac OSX 10.9.5. I have tried a variety of methods. The most successful have been;
Using homebrew
Drush 7 using composer
Each method had produced a version of Drush, however each appears old and drush dl drupal downloads the 6.x version, as does drush dl drupal 7.x.
Can you please suggest:
1) How to ensure old versions of drush are removed to ensure that a new installation goes smoothly.
2) The recommended method for installing the latest stable Drush version on Mac OSX 10.9.5
I had tried to delete the old drush version manually by removing folders. Now the composer installation method seems to fail as I get:
Pauls-iMac:~ Trotter$ composer global require drush/drush:dev-master
Changed current directory to /Users/Trotter/.composer
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
  - Installing drush/drush (dev-master 78b1538)
    Cloning 78b15385ba97890dc3431790494f26d6be99ede9
    Failed to download drush/drush from source: The process "git clone --no-checkout 'git://github.com/drush-ops/drush.git' '/Users/Trotter/.composer/vendor/drush/drush' && cd '/Users/Trotter/.composer/vendor/drush/drush' && git remote add composer 'git://github.com/drush-ops/drush.git' && git fetch composer" exceeded the timeout of 300 seconds.
    Now trying to download from dist
  - Installing drush/drush (dev-master 78b1538)
    Loading from cache

    Skipped installation of bin drush for package drush/drush: name conflicts with an existing file
    Skipped installation of bin drush.php for package drush/drush: name conflicts with an existing file
    Skipped installation of bin drush.bat for package drush/drush: name conflicts with an existing file
    Skipped installation of bin drush.complete.sh for package drush/drush: name conflicts with an existing file

I can see that I don't have drush installed as what drush gives No such file or directory and drush info gives -bash: drush: command not found
Comment: Which drush not what drush. Try uninstalling drush via composer.json first http://drupal.stackexchange.com/questions/135599/how-to-uninstall-drush-via-composer
Comment: Do you have write permission to your ~/.composer directory?
Comment: Actually it looks like the ssh command to github is timing out. I had this issue on Yosemite. You might need to flush the DNS cache. What fixed it in the end for me was a p-ram reset. Reboot with command, option, P and R keys held down until you hear the chime a couple of times.
Answer: Drush 7.x doesn't only download Drupal 7 of course. Drush 5 will download Drupal 7 too. Drush 7 is required for Drupal 8 and needs to be selected when installing with composer global require drush/drush:dev-master. Ps the recommended method is the composer method. This what I use on OS X 10.9.
Find old versions of drush with which drush. Check where they live withls -l [path from which drush]. Rinse and repeat until the only one left is in your home folder inside the hidden composer directory.
Check the version of the installed drush with drush --version
Make sure you don't have a .drushrc somewhere with a default core version specified.
Comment: Thanks for all of your helpful suggestions Queenvictoria. I tried the RAM set. I  I have managed to remove a 'require dev' dependancy that composer seemed to have (I noticed Updating dependencies (including require-dev) when updating in composer). After doing that I was able to download Drush 6 with composer. This install of Drush was able to download D7 using `drush dl drupal-7.x`
Answer:
Skipped installation of bin drush for package drush/drush: name conflicts with an existing file

Make sure to unset COMPOSER_BIN_DIR shell variable before running Composer command as it may conflict with bin-dir defined in your composer.json file. To check your current value of bin-dir, run composer config bin-dir (where your Drush may be present).


Angular js : Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource

Question: I am getting this error when I am trying to post data using $http.post() in Angular Js.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at {{post url}}. This can be fixed by moving the resource to the same domain or enabling CORS.
This is my code :
<code>var ionicAppControllers = angular.module('ionicAppControllers', []);

ionicAppControllers.config(function($httpProvider) {
    //Enable cross domain calls
    $httpProvider.defaults.useXDomain = true;

    //Remove the header containing XMLHttpRequest used to identify ajax call
    //that would prevent CORS from working
    delete $httpProvider.defaults.headers.common['X-Requested-With'];
});

ionicAppControllers.controller('createItemCtrl', ['$scope', '$http',
    function($scope, $http) {
        $scope.parts = [];

        $scope.add = function() {
            $scope.parts.push({
                id: '',
                code: '',
                description: ''
            });
        };
        $scope.submitItemForm = function(isValid) {
            if (isValid) {
                $scope.postdata = {};
                $scope.postdata.item = $scope.item;
                $scope.postdata.description = $scope.description;
                for (var i in $scope.parts)
                {
                    for (var j in $scope.parts[i])
                    {
                        if (j == '$$hashKey')
                        {
                            delete($scope.parts[i][j]);
                            //console.log(j);
                        }
                    }
                }
                $scope.postdata.parts = $scope.parts;
                console.log($scope.postdata);
                $http({
                    method: 'POST',
                    url: 'URL',
                    data: $scope.postdata, // pass in data as strings
                    headers: {'Content-Type': 'application/json'}
                }).success(function(data) {
                    if (data.success)
                    {
                        alert('sucess');
                    }
                    else
                    {
                        alert('fail');
                    }
                });
            }
        };
        $scope.add();
    }]);
</code>
Comment: I don't know what is it...just written to remove error...
Answer: This has nothing to do with Angular . The Server application should enable or allow request generated from your Angular Application which is hosted or running on any machine . If your running your app in localhost. Use CORS extension for chrome. If its from other server . lets say www.example.com .
The server code must be changed nothing on the front end perspective .
Please refer this link.
http://enable-cors.org/server.html
Answer: if you use ASP MVC and get jsonresult you must to add this xml code in web.config
<code>    <?xml version="1.0" encoding="utf-8"?>
<configuration>
 <system.webServer>
   <httpProtocol>
     <customHeaders>
       <add name="Access-Control-Allow-Origin" value="*" />
     </customHeaders>
   </httpProtocol>
 </system.webServer>
</configuration>
</code>
Comment: Did they mention anywhere they're using ASP.NET MVC?


SQL Server 2008: how does NOLOCK works for CTE?

Question: I have CTEs which all uses NOLOCK inside. But then selects from those CTEs in parent CTEs using children CTEs doesn't use NOLOCK in presumption that it is already NOLOCK'd. And the final select doesn't use NOLOCK either.
Something like that:
with cte1 as
(select * from tab1 (nolock)),
cte2 as
(select * from cte1)

select * from cte2

or shall I write
with cte1 as
(select * from tab1 (nolock)),
cte2 as
(select * from cte1 (nolock))

select * from cte2 (nolock)

thanks
Comment: I wouldn't use `SELECT *` or `NOLOCK` at all. Seeing that CTEs are supported on SQL 2005 and higher, there are better ways to ensure you're reading committed but historic data than NOLOCK.
Comment: I dont want long running report to be locking a table.. whats my other options are?
Answer: You don't need the outer nolock to avoid taking shared locks on tab1. You can easily verify this by setting up a SQL Profiler trace capturing the various events in the locks category, filtering on the spid of an SSMS connection and trying both versions.
nolock is quite a dangerous setting though, are you aware of all of the possible downsides to using it (dirty reads, reading data twice or not at all)?
Answer: NOLOCK on an "outer" query applies to any inner queries too. A CTE is just a macro like a view or inline table udf: nothing more, nothing less. So you actually have (ignoring NOLOCK hints)
select * from (
               select * from (
                             select * from tab1
                             ) t1
               ) t2

From Table Hints on MSDN, under "Remarks"

All lock hints are propagated to all the tables and views that are accessed by the query plan, including tables and views referenced in a view.

In this case, you need only one. Doesn't matter where.
Where it does matter is where you have JOINs. If cte1 was a join of 2 tables, you'd need it for each table,. Or specify it once at a higher/outer level.
Oh, and I'll join in with everyone else: NOLOCK is a bad idea
Answer: The innermost nolock is sufficient, no need to repeat it for the outer selects.
You can test this by starting a transaction without ending it:
begin transaction
; with YourCte ( ...

Then you can view the locks using Management Studio.  They'll be there until the transaction times out.
Comment: Depends on the isolation level. Shared locks are normally released as soon as the data is read.
Answer: NOLOCK for CTEs work the same way as with everything else: it causes inconsistent results. Use SNAPSHOT instead, see SQL Server 2005 Row Versioning-Based Transaction Isolation.


Kotlin - Passar dados entre Fragments

Question: Estou com um problema numa aplicação que estou a desenhar.
Tenho 3 Fragments ( F1, F2, e F3):

No F1 (contém uma list com uma serie de desportos) o utilizador faz a escolha relativamente a um desporto (utilizo um RecycleView  para isto).
No F2 (contém uma list com uma serie de espaços) o utilizar escolhe o espaço ( utilizo também um RecycleView)

A questão é que no F3 quero "resumir" as escolhas do utilizador( Desporto selecionado, espaço selecionado).
A minha questão é qual e a forma mais eficiente de passar estes argumentos entre os 3 fragments?! SharedViewMOdel ou utilizado o SafeArgs?!
Ja tentei utilizar o SharedViewModel mas no F3 a variavel vai sempre a null.
   override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.itemview.text=listsports[position]

holder.itemview.setOnClickListener{

val sViewModel=SharedViewModel()

sViewModel.setSport(adapterposition)

v:View->v.findNavcontroller().navigate(R.id.action_F1_to_F2)}
    }
}

Answer: Conforme recomendado pela google, melhor usar SafeArgs para fazer essa tarefa.
Dentro do seu código ficaria algo assim:
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    holder.itemview.text=listsports[position]

    holder.itemview.setOnClickListener{

        val sport = listsports[position]

        val navegarF2 = F1Directions.actionF1toF2(sport)
        v:View->v.findNavcontroller().navigate(navegarF2)
    }
}

Será necessário declarar o tipo de dado que está passando entre os fragmentos, se precisar passar algum tipo de objeto é necessário que a classe do mesmo extenda Parcelable e de alt+enter na classe que será gerado automaticamente a implementação.
Se fosse passar uma suposta classe "sports" com 3 parametros, com parcelable ficaria assim:
clas Sports(val nome: String?, val time: String?, val jogadores: ArrayList<String>?): Parcelable {
constructor(parcel: Parcel) : this(
    parcel.readString(),
    parcel.readString(),
    parcel.createStringArrayList()) {
}

override fun writeToParcel(parcel: Parcel, flags: Int) {
    parcel.writeString(nome)
    parcel.writeString(time)
    parcel.writeStringList(jogadores)
}

override fun describeContents(): Int {
    return 0
}

companion object CREATOR : Parcelable.Creator<sports> {
    override fun createFromParcel(parcel: Parcel): sports {
        return sports(parcel)
    }

    override fun newArray(size: Int): Array<sports?> {
        return arrayOfNulls(size)
    }
}

Lembrando que todo código dentro do {..} foi gerado automaticamente.
Documentação:
https://developer.android.com/guide/navigation/navigation-pass-data?hl=pt-br
https://developer.android.com/reference/android/os/Parcelable

Kotlin - Passar dados entre Fragments


How to test whether a covariance matrix has changed over two time points?

Question: My task is to test if there's change in covariance matrix of 6 variables. Values of 6 variables are measured twice from same subjects (3 years between measurements).
How can I do that? I've been doing most of my work using SAS.
Comment: Thank you for your answers. I was thinking of Box M, but I wasn't sure if it applies into repeated measures. Had to get that Rencher's book. I'm quite certain that nested model comparison can be done used for example proc mixed of SAS as well. Nevertheless, thank you! I'm new here and hopefully I'm someday able to provide some answers as well:o)
Comment: Welcome to the site! Thanks are very welcome but in this site you should not give them as an answer. You can express your gratitude by upvoting the answers you like and accepting the one you liked the best. You can also add comment to the answer. It also helps if you put in the question the things you tried or think might be of help to solve the problem.
Answer: Assuming that your distributions are multivariate normal (as the tests for covariance matrices tend to assume that, anyway), your null hypothesis is that the two populations differ only by shift. You can test this with a Kolmogorov-Smirnov test on the two groups of data from which their means were subtracted.
Rencher (2002) (Sec. 7.3.2) provides the likelihood ratio test statistic for comparing two matrices (Box M-test) as follows:
$$M=|S_1|^{\nu_1/2} |S_2|^{\nu_2/2}/|S_p|^{(\nu_1+\nu_2)/2}$$
where $S_1$ and $S_2$ are the sample covariance matrices in the two samples, $S_p$ is the pooled covariance matrix, $\nu_1$ and $\nu_2$ are the degrees of freedom (sample size minus 1). Asymptotically, $-2\log M$ follows $\chi^2$ distribution with $p(p+1)/2$ degrees of freedom where $p$ is the size of the matrices. Rencher (2002) also gives the Bartlett-corrected version of the test and an $F$-approximation. This, however, is a two-sample test, rather than the repeated measures test, so it may be somewhat conservative.
Comment: What is an alternative of the Box's M-test for Homogeneity of Covariance Matrices if distributions are not multivariate normal?
Comment: I'd say it's inapplicable. Everything has to be normal for the likelihood ratios to apply. Otherwise you would have to go to moment-based statistics, and then you need fourth order moments to get covariances of covariances.
Answer: You could use structural equation modelling software.
This is a sketch of how the process might work in Amos:

Add all your variables for time 1 ($X1, ..., X_6$) and time 2 ($Y_1, ..., Y_6$)
Draw double headed arrows between all variables (i.e., you are letting the software know that all variances and covariances are free to vary, and thus, your model should perfectly represent data)
Name all variances and covariances
The above is model 1 (i.e., no equality constraints)
Then add equality statements to model 2 (i.e., variances and covariances constrained)

Equal variances for corresponding variables at different times points: e.g., var_x1 = var_y1     var_x2 = var_y2 and so on
equal covariances for corresponding time points: e.g., cov_x1_x2 = cov_y1_y2    cov_x1_x3 = cov_y1_y3 and so on

Examine the difference in fit between the two models

model 2 is nested within model 1, so you should be able to use nested model comparison tests like chi-square difference tests.
Answer: This can probably be tested with proc mixed (well you have to assume multivariate normality). Stack all data on one column. You'll need then indicators for the subject ID and for the time-point. You'll have to define both subject ID and time point-indicator as class variables. Fit an intercept only model; then use perhaps a repeated statement to fit an unconstrained variance/covariance structure (type=un). Write down the $-2\ln(\mathcal{L})$ where $\mathcal{L}$ is the likelihood) and the degrees of freedom. Then fit a second model, but this time in the repeated statement, use the group= option to make SAS fit separate covariance structures for each time-point (i.e. each time-point is a group). Write down the $-2\ln(\mathcal{L})$ and df. Then conduct the LRT test of no difference in fit using the difference in -2loglikelihoods and dfs between the two models, which should be distributed chi-squared under the null hypothesis of no difference in fit between the two models.
Comment: Welcome to the site, @Andres. You can use LaTeX here. I did so in your post to make it a little neater.


Using tokens in block titles

Question: Plugging tokens into a block's title only shows the input text instead of what the token's supposed to output.
Is there a way to enable/use tokens in block titles, or maybe an alternative method of getting the results I want?
I've tried using Token Filter module, but it doesn't change the functionality.
I am trying to insert the [user:profile-realname] token into a block title (specifically the User Menu block title). The token is in my list of tokens available to use via HELP in the backend.
Comment: drupal version?  where are you trying to set the title, inside a module or from the block admin page?  what tokens are you trying to access?
Comment: added version to title
Comment: Created an edit
Comment: a detail blog: http://goo.gl/77zEds
Answer: AFAIK, this cannot be achieved using the block title field, however using the Token Filter module, you can just drop the token in the body area of the block and wrap it in an H2 tag and it will appear as if it was the block title. (Just set the block title to <none>)
Comment: Does this also apply to the Node Title field? I want to add tokens to the Node title of the basic page content type, trying the same mechanism as Mechaflash. Will I also have to use Token Filter, or can I put Tokens directly into the Node title field (using the web interface, no php coding)?
Comment: no, it doesn't. If you wish to put it in the title field, you will need to follow Lance's answer to the question.
Answer: Try the token_replace() function in the block preprocessor. Example:
$node = menu_get_object();  // Get the current node
if ($node) {
  $vars['elements']['#block']->subject = token_replace($vars['elements']['#block']->subject, array('node' => $node));
}

Maybe you have to load the user too to have the user tokens available.
Comment: I'm probably not going to try this as nicoz answer is the easiest way to do this.  I would rather not mess with tpl files if I don't have to.
Answer: Once Support token replacement for block titles is implemented, you'll be able to use the [current-user:profile-realname] token.
Comment: So how do i reliable determine what tokens are going to validate? Or were you saying in that thread that there isn't a way to validate non-core tokens?
Answer: Set Title to empty, and just add a Global Text Area in Views Header! Add here h tags or whatever html you want. Much easier and no coding required...

Using tokens in block titles


Knowledge Distillation math proof

Question: In the paper "Distilling the Knowledge in a Neural Network" by Hinton, soft target of student model is defined as cross-entropy $C$ between teacher model and student model.
Assume that $i$ is an integer, $i \in [1, N]$, where $N$ is number of class models are trained to classify.
In section 2.1, the paper is written as follow:
Each case in the transfer set contributes a cross-entropy gradient, $dC/dz_i$, with respect to each logit, $z_i$ of the distilled model.
If the cumbersome model has logits $v_i$ which produce soft target probabilities $p_i$ and the transfer training is done at a temperature of $T$, this gradient is given by:
$$
\frac{\partial C}{\partial z_i} = \frac{1}{T}(q_i - p_i) = \frac{1}{T}(\frac{e^{z_i/T}}{\sum_j e^{z_j/T}} - \frac{e^{v_i/T}}{\sum_j e^{v_j/T}}) \tag{2}
$$
If the (softmax) temperature is high compared with the magnitude of the logits, we can approximate:
$$
\frac{\partial C}{\partial z_i} \approx \frac{1}{T}\left(\frac{1 + z_i/T}{N + \sum_j z_j/T} - \frac{1 + v_i/T}{N + \sum_j v_j/T}\right) \tag{3}
$$
If we now assume that the logits have been zero-meaned separately for each transfer case so that
$\sum_j z_j = \sum_j v_j = 0$ Eq. 3 simplifies to:
$$
\frac{\partial C}{\partial z_i} \approx \frac{1}{NT^2} (z_i - v_i) \tag{4}
$$
So in the high temperature limit, distillation is equivalent to minimizing
$$
\frac{1}{2}(z_i − v_i)^2 \tag{5}
$$
, provided the logits are zero-meaned separately for each transfer case.
I believe this is a good paper, but it skipped so many steps that it is hard for a beginner like me to understand.
I already manage to get Eq. 2 by using cross entropy, and my problems are Eq. 3 and Eq. 5.
For Eq.3, I tried to use $\lim_{T\to\infty}e^{z_i/T} = \lim_{T\to\infty}1+z_i/T=1$, but I'm not sure I am correct or not.
For Eq.5, I just don't know how to get the equation.
Comment: If anyone is curious, this paper is from 2015.
Answer: For equation $(3)$, they use the approximation that
$$e^{x}\approx 1+x$$
when $x$ is small. Here $x$ are $\frac{z_i}{T}$ and also $\frac{v_i}{T}$.When $T$ is huge, this approximation is good.
For equation $(5)$, the quadratic equation attains the minimum when $z_i=v_i$ which is the same as setting equation $(4)$ to be $0$.
Comment: So does that means Eq. 3 using Taylor series first order approximation?
And I'm confuse about your explanation of Eq. 5.
Did you mean we are using Eq. 5 to optimize instead of Eq. 4?
Comment: yes, first order Taylor. Approximation $(4)$ tells us that minimizing $C$ is approximately minimizing $(5)$.

Knowledge Distillation math proof